π The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
feat: Implement admin dashboard with statistics and user management
Smaug673960c3977aa163
diff --git a/backend/.env.example b/backend/.env.exampleindex 9f656954..1f2fab4f 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -11,7 +11,7 @@ DATABASE_PASSWORD=root## Security & JWTJWT_SECRET=your_secret_key # Change this to a secure random string in production-+ADMIN_ACCOUNTS=id1,id2,id3 # Comma-separated list of user IDs that should have admin privileges (e.g., 1,2,3). Optional.# S3 / MinIO configuration (optional, leave empty to disable)MINIO_ACCESSKEY=access_keydiff --git a/backend/app/migrations/000017_users_created_index.down.sql b/backend/app/migrations/000017_users_created_index.down.sqlnew file mode 100644index 00000000..8166c9a8--- /dev/null+++ b/backend/app/migrations/000017_users_created_index.down.sql@@ -0,0 +1 @@+DROP INDEX idx_users_created ON users;diff --git a/backend/app/migrations/000017_users_created_index.up.sql b/backend/app/migrations/000017_users_created_index.up.sqlnew file mode 100644index 00000000..95696b5b--- /dev/null+++ b/backend/app/migrations/000017_users_created_index.up.sql@@ -0,0 +1 @@+CREATE INDEX idx_users_created ON users(created_timestamp);diff --git a/backend/controllers/stats.controller.go b/backend/controllers/stats.controller.gonew file mode 100644index 00000000..d3b6fa81--- /dev/null+++ b/backend/controllers/stats.controller.go@@ -0,0 +1,74 @@+package controllers++import (+ "alexandrie/app"+ "errors"+ "net/http"+ "strconv"++ "github.com/gin-gonic/gin"+)++type StatsController interface {+ GetOverviewStats(c *gin.Context) (int, any)+ GetUserStats(c *gin.Context) (int, any)+ GetNodeStats(c *gin.Context) (int, any)+}++func NewStatsController(app *app.App) StatsController {+ return &Controller{app: app}+}++func (ctr *Controller) GetOverviewStats(c *gin.Context) (int, any) {+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err+ }++ stats, err := ctr.app.Services.Stats.GetOverviewStats()+ if err != nil {+ return http.StatusInternalServerError, err+ }++ return http.StatusOK, stats+}++func (ctr *Controller) GetUserStats(c *gin.Context) (int, any) {+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err+ }++ stats, err := ctr.app.Services.Stats.GetUserStats()+ if err != nil {+ return http.StatusInternalServerError, err+ }++ return http.StatusOK, stats+}++func (ctr *Controller) GetNodeStats(c *gin.Context) (int, any) {+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err+ }++ topLimit := 5+ if top := c.Query("top"); top != "" {+ parsed, err := strconv.Atoi(top)+ if err != nil {+ return http.StatusBadRequest, err+ }+ if parsed <= 0 {+ return http.StatusBadRequest, errors.New("top must be a positive integer")+ }+ if parsed > 50 {+ parsed = 50+ }+ topLimit = parsed+ }++ stats, err := ctr.app.Services.Stats.GetNodeStats(topLimit)+ if err != nil {+ return http.StatusInternalServerError, err+ }++ return http.StatusOK, stats+}diff --git a/backend/models/README.md b/backend/models/README.mddeleted file mode 100644index 3863d86d..00000000--- a/backend/models/README.md+++ /dev/null@@ -1,164 +0,0 @@-# Models Layer--## Overview--Models define the data structures used throughout the Alexandrie application. They represent database tables, API request/response formats, and business entities with their properties and relationships.--## Architecture--```-βββββββββββββββββββ-β Database β-ββββββββββ¬βββββββββ- β Maps to- βΌ-βββββββββββββββββββ-β Models β β Data structures (This layer)-ββββββββββ¬βββββββββ- β Used by- βΌ-βββββββββββββββββββ-β Repositories β-β Services β-β Controllers β-βββββββββββββββββββ-```--## JSON Serialization--### Excluding Fields from JSON--Use `json:"-"` to hide sensitive data:--```go-type User struct {- Password string `json:"-"` // Never included in JSON- Email string `json:"email,omitempty"` // Omit if empty-}-```--### Custom JSON Field Names--```go-type Node struct {- CreatedTimestamp int64 `json:"created_at"` // Maps to "created_at" in JSON- UpdatedTimestamp int64 `json:"updated_at"`-}-```--## Database Tags--Models use struct tags for database mapping:--```go-type User struct {- ID uint64 `json:"id" db:"id"`- Username string `json:"username" db:"username" validate:"required,min=3,max=25"`-}-```--## Validation--### Built-in Validation--Use validation tags for automatic checks:--```go-type CreateUserRequest struct {- Username string `json:"username" validate:"required,min=3,max=25"`- Email string `json:"email" validate:"required,email"`- Password string `json:"password" validate:"required,min=8"`-}--// In controller/service-if err := validator.Validate(request); err != nil {- return fmt.Errorf("validation error: %w", err)-}-```--## Request/Response DTOs--### Separate DTOs from Models--Create specific types for API requests/responses:--```go-// Request DTO-type CreateNodeRequest struct {- Name string `json:"name" validate:"required,max=50"`- ParentID uint64 `json:"parent_id"`- Role int `json:"role" validate:"required,min=1,max=4"`- Content string `json:"content"`-}--// Response DTO-type NodeResponse struct {- ID uint64 `json:"id"`- Name string `json:"name"`- CreatedAt int64 `json:"created_at"`- Owner string `json:"owner"`-}--// Convert model to response-func ToNodeResponse(node *Node, ownerName string) NodeResponse {- return NodeResponse{- ID: node.ID,- Name: node.Name,- CreatedAt: node.CreatedTimestamp,- Owner: ownerName,- }-}-```--## Common Issues--### Issue: "json: unsupported type" error--**Cause**: Trying to serialize unsupported types (channels, functions)--**Solution**: Use proper JSON-serializable types:--```go-// Wrong-type Node struct {- Metadata chan string // Cannot serialize-}--// Correct-type Node struct {- Metadata any // Use json.RawMessage or map[string]any-}-```--### Issue: Circular reference during JSON serialization--**Cause**: Model references itself or creates a cycle--**Solution**: Use pointers and omit empty, or create response DTOs:--```go-// Problematic-type Node struct {- Parent *Node- Children []Node // Causes infinite loop-}--// Better-type Node struct {- ParentID uint64- // Load children separately when needed-}-```--### Issue: Zero values being serialized--**Cause**: Not using `omitempty` tag--**Solution**: Add `omitempty` for optional fields:--```go-type Node struct {- ParentID uint64 `json:"parent_id,omitempty"`- Description string `json:"description,omitempty"`-}-```diff --git a/backend/models/stats.model.go b/backend/models/stats.model.gonew file mode 100644index 00000000..49e36f6a--- /dev/null+++ b/backend/models/stats.model.go@@ -0,0 +1,34 @@+package models++import "alexandrie/types"++type MonthlyCount struct {+ Month string `json:"month" db:"month"`+ Count int64 `json:"count" db:"count"`+}++type UserStats struct {+ TotalUsers int64 `json:"total_users"`+ GrowthLast12Months []MonthlyCount `json:"growth_last_12_months"`+}++type NodeOwnerStats struct {+ UserID types.Snowflake `json:"user_id" db:"user_id"`+ Username string `json:"username" db:"username"`+ NodeCount int64 `json:"node_count" db:"node_count"`+ TotalSize int64 `json:"total_size" db:"total_size"`+}++type NodeStats struct {+ TotalNodes int64 `json:"total_nodes"`+ TotalSize int64 `json:"total_size"`+ GrowthLast12Months []MonthlyCount `json:"growth_last_12_months"`+ TopUsersByNodes []NodeOwnerStats `json:"top_users_by_nodes"`+ TopUsersBySize []NodeOwnerStats `json:"top_users_by_size"`+}++type OverviewStats struct {+ TotalUsers int64 `json:"total_users"`+ TotalNodes int64 `json:"total_nodes"`+ TotalSize int64 `json:"total_size"`+}diff --git a/backend/permissions/constants.go b/backend/permissions/constants.goindex 420df18e..2c701010 100644--- a/backend/permissions/constants.go+++ b/backend/permissions/constants.go@@ -4,7 +4,7 @@ package permissionstype UserRole intconst (- RoleNone UserRole = 0+ RoleNone UserRole = 1 << 0RoleAdministrator UserRole = 1 << 1RoleManager UserRole = 1 << 2RoleModerator UserRole = 1 << 3diff --git a/backend/repositories/manager.go b/backend/repositories/manager.goindex 6d0c533b..f75435e1 100644--- a/backend/repositories/manager.go+++ b/backend/repositories/manager.go@@ -10,6 +10,7 @@ type RepositoryManager struct {db *sqlx.DBUser UserRepositoryNode NodeRepository+ Stats StatsRepositorySession SessionRepositoryPermission PermissionRepositoryLog LogRepository@@ -25,7 +26,7 @@ func NewRepositoryManager(db *sqlx.DB) (*RepositoryManager, error) {rm.initializeRepositories()rm.initialized = true- logger.Success("Repository manager", "Initialized successfully")+ logger.Success("repository manager", "Initialized successfully")return rm, nil}@@ -33,6 +34,7 @@ func (rm *RepositoryManager) initializeRepositories() {rm.User = NewUserRepository(rm.db)rm.Session = NewSessionRepository(rm.db)rm.Node = NewNodeRepository(rm.db)+ rm.Stats = NewStatsRepository(rm.db)rm.Permission = NewPermissionRepository(rm.db)rm.Log = NewLogRepository(rm.db)rm.OIDCProvider = NewOIDCProviderRepository(rm.db)@@ -41,7 +43,7 @@ func (rm *RepositoryManager) initializeRepositories() {func (rm *RepositoryManager) Close() error {rm.initialized = false- logger.Success("Repository manager", "Closed successfully")+ logger.Success("repository manager", "Closed successfully")return rm.db.Close()}diff --git a/backend/repositories/stats.repository.go b/backend/repositories/stats.repository.gonew file mode 100644index 00000000..d253b3ef--- /dev/null+++ b/backend/repositories/stats.repository.go@@ -0,0 +1,130 @@+package repositories++import (+ "alexandrie/models"+ "fmt"++ "github.com/jmoiron/sqlx"+)++type StatsRepository interface {+ GetUsersTotal() (int64, error)+ GetUsersMonthlyGrowth(sinceTimestamp int64) ([]models.MonthlyCount, error)+ GetNodesTotal() (int64, error)+ GetNodesTotalSize() (int64, error)+ GetNodesMonthlyGrowth(sinceTimestamp int64) ([]models.MonthlyCount, error)+ GetTopUsersByNodeCount(limit int) ([]models.NodeOwnerStats, error)+ GetTopUsersByNodeSize(limit int) ([]models.NodeOwnerStats, error)+}++type StatsRepositoryImpl struct {+ db *sqlx.DB+}++func NewStatsRepository(db *sqlx.DB) StatsRepository {+ return &StatsRepositoryImpl{db: db}+}++func (r *StatsRepositoryImpl) GetUsersTotal() (int64, error) {+ var total int64+ if err := r.db.Get(&total, `SELECT COUNT(*) FROM users`); err != nil {+ return 0, fmt.Errorf("failed to count users: %w", err)+ }+ return total, nil+}++func (r *StatsRepositoryImpl) GetUsersMonthlyGrowth(sinceTimestamp int64) ([]models.MonthlyCount, error) {+ rows := []models.MonthlyCount{}+ err := r.db.Select(&rows, `+ SELECT+ DATE_FORMAT(FROM_UNIXTIME(created_timestamp / 1000), '%Y-%m') AS month,+ COUNT(*) AS count+ FROM users+ WHERE created_timestamp >= ?+ GROUP BY month+ ORDER BY month ASC`, sinceTimestamp)+ if err != nil {+ return nil, fmt.Errorf("failed to aggregate users monthly growth: %w", err)+ }+ return rows, nil+}++func (r *StatsRepositoryImpl) GetNodesTotal() (int64, error) {+ var total int64+ if err := r.db.Get(&total, `SELECT COUNT(*) FROM nodes`); err != nil {+ return 0, fmt.Errorf("failed to count nodes: %w", err)+ }+ return total, nil+}++func (r *StatsRepositoryImpl) GetNodesTotalSize() (int64, error) {+ var totalSize int64+ if err := r.db.Get(&totalSize, `SELECT COALESCE(SUM(size), 0) FROM nodes`); err != nil {+ return 0, fmt.Errorf("failed to sum nodes size: %w", err)+ }+ return totalSize, nil+}++func (r *StatsRepositoryImpl) GetNodesMonthlyGrowth(sinceTimestamp int64) ([]models.MonthlyCount, error) {+ rows := []models.MonthlyCount{}+ err := r.db.Select(&rows, `+ SELECT+ DATE_FORMAT(FROM_UNIXTIME(created_timestamp / 1000), '%Y-%m') AS month,+ COUNT(*) AS count+ FROM nodes+ WHERE created_timestamp >= ?+ GROUP BY month+ ORDER BY month ASC`, sinceTimestamp)+ if err != nil {+ return nil, fmt.Errorf("failed to aggregate nodes monthly growth: %w", err)+ }+ return rows, nil+}++func (r *StatsRepositoryImpl) GetTopUsersByNodeCount(limit int) ([]models.NodeOwnerStats, error) {+ if limit <= 0 {+ limit = 5+ }++ rows := []models.NodeOwnerStats{}+ err := r.db.Select(&rows, `+ SELECT+ n.user_id AS user_id,+ u.username AS username,+ COUNT(n.id) AS node_count,+ COALESCE(SUM(n.size), 0) AS total_size+ FROM nodes n+ JOIN users u ON u.id = n.user_id+ GROUP BY n.user_id, u.username+ ORDER BY node_count DESC, total_size DESC+ LIMIT ?`, limit)+ if err != nil {+ return nil, fmt.Errorf("failed to get top users by node count: %w", err)+ }++ return rows, nil+}++func (r *StatsRepositoryImpl) GetTopUsersByNodeSize(limit int) ([]models.NodeOwnerStats, error) {+ if limit <= 0 {+ limit = 5+ }++ rows := []models.NodeOwnerStats{}+ err := r.db.Select(&rows, `+ SELECT+ n.user_id AS user_id,+ u.username AS username,+ COUNT(n.id) AS node_count,+ COALESCE(SUM(n.size), 0) AS total_size+ FROM nodes n+ JOIN users u ON u.id = n.user_id+ GROUP BY n.user_id, u.username+ ORDER BY total_size DESC, node_count DESC+ LIMIT ?`, limit)+ if err != nil {+ return nil, fmt.Errorf("failed to get top users by node size: %w", err)+ }++ return rows, nil+}diff --git a/backend/repositories/user.repository.go b/backend/repositories/user.repository.goindex 4b1a41aa..2c23052f 100644--- a/backend/repositories/user.repository.go+++ b/backend/repositories/user.repository.go@@ -17,6 +17,7 @@ type UserRepository interface {GetAll() ([]*models.User, error)GetByID(id types.Snowflake) (*models.User, error)GetByUsername(username string) (*models.User, error)+ GetAppAdmins() ([]*models.User, error)HasPassword(id types.Snowflake) (bool, error)SearchPublic(query string) ([]*models.User, error)CheckUsernameExists(username string) (bool, error)@@ -24,6 +25,7 @@ type UserRepository interface {Update(id types.Snowflake, user *models.User) (*models.User, error)UpdatePassword(id types.Snowflake, password string) errorUpdatePasswordResetToken(id types.Snowflake, resetToken string) error+ UpdateRole(id types.Snowflake, role int) error // Separate method for securityDelete(id types.Snowflake) error}@@ -73,6 +75,15 @@ func (r *UserRepositoryImpl) GetByUsername(username string) (*models.User, errorreturn &user, nil}+func (r *UserRepositoryImpl) GetAppAdmins() ([]*models.User, error) {+ var admins []*models.User+ err := r.db.Select(&admins, `SELECT id, username, role, created_timestamp, updated_timestamp FROM users WHERE role = 2`)+ if err != nil {+ return nil, fmt.Errorf("failed to get app admins: %w", err)+ }+ return admins, nil+}+func (r *UserRepositoryImpl) HasPassword(id types.Snowflake) (bool, error) {var count interr := r.db.Get(&count, `SELECT COUNT(*) FROM users WHERE id = ? AND password IS NOT NULL`, id)@@ -143,6 +154,14 @@ func (r *UserRepositoryImpl) UpdatePasswordResetToken(id types.Snowflake, resetTreturn nil}+func (r *UserRepositoryImpl) UpdateRole(id types.Snowflake, role int) error {+ _, err := r.db.Exec(`UPDATE users SET role=? WHERE id=?`, role, id)+ if err != nil {+ return fmt.Errorf("failed to update user role: %w", err)+ }+ return nil+}+func (r *UserRepositoryImpl) Delete(id types.Snowflake) error {_, err := r.db.Exec(`DELETE FROM users WHERE id=?`, id)if err != nil {diff --git a/backend/router/router.go b/backend/router/router.goindex ab1bca8d..fae0fa41 100644--- a/backend/router/router.go+++ b/backend/router/router.go@@ -71,5 +71,6 @@ func InitRouter(app *app.App) *gin.Engine {routes.Uploads(app, mainGroup)routes.Backup(app, mainGroup)routes.Nodes(app, mainGroup)+ routes.Stats(app, mainGroup)return router}diff --git a/backend/router/routes/stats.go b/backend/router/routes/stats.gonew file mode 100644index 00000000..b8b5520a--- /dev/null+++ b/backend/router/routes/stats.go@@ -0,0 +1,19 @@+package routes++import (+ "alexandrie/app"+ "alexandrie/controllers"+ "alexandrie/middlewares"+ "alexandrie/utils"++ "github.com/gin-gonic/gin"+)++func Stats(app *app.App, router *gin.RouterGroup) {+ stats := router.Group("/stats")+ statsCtrl := controllers.NewStatsController(app)++ stats.GET("/overview", middlewares.Auth(), middlewares.Admin(), utils.WP(statsCtrl.GetOverviewStats))+ stats.GET("/users", middlewares.Auth(), middlewares.Admin(), utils.WP(statsCtrl.GetUserStats))+ stats.GET("/nodes", middlewares.Auth(), middlewares.Admin(), utils.WP(statsCtrl.GetNodeStats))+}diff --git a/backend/services/README.md b/backend/services/README.mddeleted file mode 100644index 30ff8b42..00000000--- a/backend/services/README.md+++ /dev/null@@ -1,276 +0,0 @@-# Services Layer--## Overview--The services layer contains the business logic of the Alexandrie application. Services orchestrate operations between repositories, enforce business rules, and handle complex workflows that span multiple data entities.--## Architecture--```-βββββββββββββββββββ-β Controllers β β HTTP Request Handlers-ββββββββββ¬βββββββββ- β- βΌ-βββββββββββββββββββ-β Services β β Business Logic Layer (This layer)-ββββββββββ¬βββββββββ- β- βΌ-βββββββββββββββββββ-β Repositories β β Data Access Layer-ββββββββββ¬βββββββββ- β- βΌ-βββββββββββββββββββ-β Database β β MySQL-βββββββββββββββββββ-```--## Key Components--### Service Manager (`manager.go`)--**Initialization:**--```go-serviceMgr, err := services.NewServiceManager(repos, snowflake, minioClient)-if err != nil {- log.Fatal(err)-}-```--### Available Services--- **`auth.service.go`** - Authentication, login, registration, token management-- **`user.service.go`** - User profile operations, validation, updates-- **`node.service.go`** - Document/note business logic, hierarchy management-- **`permission.service.go`** - Access control rules and authorization-- **`session.service.go`** - User session lifecycle management-- **`log.service.go`** - Activity and connection logging-- **`minio.service.go`** - Object storage operations-- **`resource.service.go`** - File and media management--## Usage Example--### Service Implementation Pattern--```go-type NodeService interface {- GetNodeById(id uint64) (*models.Node, error)- CreateNode(node *models.Node) error- UpdateNode(node *models.Node) error- DeleteNode(id uint64) error-}--type nodeService struct {- nodeRepo repositories.NodeRepository- permissionRepo repositories.PermissionRepository- snowflake *snowflake.Snowflake-}--func (s *nodeService) CreateNode(node *models.Node) error {- // 1. Validate business rules- if err := s.validateNode(node); err != nil {- return fmt.Errorf("validation failed: %w", err)- }-- // 2. Generate unique ID- node.ID = s.snowflake.Generate()-- // 3. Perform repository operations- if err := s.nodeRepo.Create(node); err != nil {- return fmt.Errorf("failed to create node: %w", err)- }-- // 4. Handle related operations (permissions, logs, etc.)- if err := s.createDefaultPermissions(node); err != nil {- return fmt.Errorf("failed to set permissions: %w", err)- }-- return nil-}-```--### Cross-repos Communication--Services can depend on other repos for complex operations:--```go-// Permission service uses node service for validation-func (s *permissionService) GrantAccess(nodeId, userId uint64, level int) error {- // Verify node exists- node, err := s.nodeRepo.GetByID(nodeId)- if err != nil {- return fmt.Errorf("node not found: %w", err)- }-- // Verify user exists- user, err := s.userRepo.GetByID(userId)- if err != nil {- return fmt.Errorf("user not found: %w", err)- }-- // Create permission- permission := &models.Permission{- NodeID: nodeId,- UserID: userId,- Level: level,- }-- return s.permissionRepo.Create(permission)-}-```--## Best Practices--### Business Rule Validation--Services enforce all business rules before data persistence:--```go-func (s *nodeService) validateNode(node *models.Node) error {- // Check required fields- if node.Name == "" {- return errors.New("node name is required")- }-- // Validate name length- if len(node.Name) < 1 || len(node.Name) > 50 {- return errors.New("node name must be 1-50 characters")- }-- // Check parent exists if specified- if node.ParentID != 0 {- _, err := s.nodeRepo.GetByID(node.ParentID)- if err != nil {- return errors.New("parent node not found")- }- }-- return nil-}-```--### Error Wrapping--Provide context when wrapping errors:--```go-if err := s.nodeRepo.Create(node); err != nil {- return fmt.Errorf("failed to create node '%s': %w", node.Name, err)-}-```--### Transaction Management--For operations spanning multiple repositories, use transactions:--```go-func (s *nodeService) MoveNode(nodeId, newParentId uint64) error {- tx, err := s.db.Begin()- if err != nil {- return err- }- defer tx.Rollback()-- // Update node parent- if err := s.nodeRepo.UpdateParent(tx, nodeId, newParentId); err != nil {- return err- }-- // Update hierarchy metadata- if err := s.updateHierarchy(tx, nodeId); err != nil {- return err- }-- return tx.Commit()-}-```--## Common Patterns--### ID Generation--Use Snowflake for distributed unique IDs:--```go-func (s *nodeService) CreateNode(node *models.Node) error {- node.ID = s.snowflake.Generate()- node.CreatedTimestamp = time.Now().Unix()- node.UpdatedTimestamp = time.Now().Unix()-- return s.nodeRepo.Create(node)-}-```--## Common Issues--### Issue: Circular dependency between services--**Cause**: Service A imports Service B, which imports Service A--**Solution**: Extract shared logic to a utility package or use interfaces:--```go-// Instead of importing the service, define an interface-type NodeValidator interface {- Exists(id uint64) bool-}--// Pass interface in constructor-func NewPermissionService(nodeValidator NodeValidator) *permissionService {- return &permissionService{validator: nodeValidator}-}-```--### Issue: Service grows too large--**Cause**: Single service handling too many responsibilities--**Solution**: Split into smaller, focused services (for future refactoring):--```go-// Instead of one large NodeService, split into:-- NodeService // Basic CRUD-- NodeHierarchyService // Parent/child operations-- NodeSearchService // Search and filtering-- NodeExportService // Export to PDF, Markdown, etc.-```--### Issue: Race conditions in concurrent operations--**Cause**: Multiple goroutines modifying shared state--**Solution**: Use proper locking or atomic operations:--```go-import "sync"--type nodeService struct {- mu sync.RWMutex- cache map[uint64]*models.Node-}--func (s *nodeService) GetFromCache(id uint64) *models.Node {- s.mu.RLock()- defer s.mu.RUnlock()- return s.cache[id]-}-```--## Service Initialization--Services are initialized through the ServiceManager in the main application:--```go-// In main.go or app initialization-app, err := app.InitApp(config)-if err != nil {- log.Fatal(err)-}--// Access services through app-user, err := app.Services.User.GetUserById(userId)-node, err := app.Services.Node.GetNodeById(nodeId)-```diff --git a/backend/services/manager.go b/backend/services/manager.goindex a70d4488..25a9ffa1 100644--- a/backend/services/manager.go+++ b/backend/services/manager.go@@ -14,6 +14,7 @@ type ServiceManager struct {Access permissions.AccessGuardAuth AuthServiceUser UserService+ Stats StatsServiceNode NodeServicePermission PermissionServiceSession SessionService@@ -33,7 +34,7 @@ func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowfla}sm.initialized = true- logger.Success("Service manager", "Initialized successfully")+ logger.Success("service manager", "Initialized successfully")return sm, nil}@@ -41,6 +42,7 @@ func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManagsm.Access = permissions.NewAccessGuard(repos.Node, repos.Permission)sm.Auth = NewAuthService(repos.User, repos.Session, repos.Log, snowflake)sm.User = NewUserService(repos.User, repos.Log, snowflake, sm.Access)+ sm.Stats = NewStatsService(repos.Stats)sm.Minio = NewMinioService(minioClient)sm.Node = NewNodeService(repos.Node, repos.Permission, sm.Minio, snowflake, sm.Access)sm.Permission = NewPermissionService(repos.Permission, repos.Node, snowflake, sm.Access)diff --git a/backend/services/node.service.go b/backend/services/node.service.goindex 351cae76..ee796a14 100644--- a/backend/services/node.service.go+++ b/backend/services/node.service.go@@ -168,7 +168,7 @@ func (s *nodeService) CreateNode(ctx context.Context, node *models.Node) (*modelOrder: node.Order,Content: node.Content,ContentCompiled: &escapedHTMLContent,- Size: node.Size,+ Size: getNodeSize(node),Metadata: node.Metadata,CreatedTimestamp: time.Now().UnixMilli(),UpdatedTimestamp: time.Now().UnixMilli(),@@ -247,6 +247,7 @@ func (s *nodeService) UpdateNode(ctx context.Context, nodeId types.Snowflake, noOrder: node.Order,Content: node.Content,ContentCompiled: &escapedHTMLContent,+ Size: getNodeSize(node),Metadata: node.Metadata,UpdatedTimestamp: time.Now().UnixMilli(),}@@ -299,3 +300,13 @@ func (s *nodeService) SearchNodes(ctx context.Context, query string, includeCont}return s.nodeRepo.SearchFulltext(actor.UserID, query, includeContent, limit)}++// ******************* Helper functions *******************++func getNodeSize(node *models.Node) *int64 {+ if node.Role == 4 && node.Size != nil {+ return node.Size+ }+ size := int64(len(*node.ContentCompiled) + len(*node.Content))+ return &size+}diff --git a/backend/services/stats.service.go b/backend/services/stats.service.gonew file mode 100644index 00000000..02d2acf1--- /dev/null+++ b/backend/services/stats.service.go@@ -0,0 +1,126 @@+package services++import (+ "alexandrie/models"+ "alexandrie/repositories"+ "time"+)++type StatsService interface {+ GetOverviewStats() (*models.OverviewStats, error)+ GetUserStats() (*models.UserStats, error)+ GetNodeStats(topLimit int) (*models.NodeStats, error)+}++type statsService struct {+ statsRepo repositories.StatsRepository+}++func NewStatsService(statsRepo repositories.StatsRepository) StatsService {+ return &statsService{statsRepo: statsRepo}+}++func (s *statsService) GetOverviewStats() (*models.OverviewStats, error) {+ totalUsers, err := s.statsRepo.GetUsersTotal()+ if err != nil {+ return nil, err+ }++ totalNodes, err := s.statsRepo.GetNodesTotal()+ if err != nil {+ return nil, err+ }++ totalSize, err := s.statsRepo.GetNodesTotalSize()+ if err != nil {+ return nil, err+ }++ return &models.OverviewStats{+ TotalUsers: totalUsers,+ TotalNodes: totalNodes,+ TotalSize: totalSize,+ }, nil+}++func (s *statsService) GetUserStats() (*models.UserStats, error) {+ totalUsers, err := s.statsRepo.GetUsersTotal()+ if err != nil {+ return nil, err+ }++ since := startOfMonthUTC(time.Now().UTC()).AddDate(0, -11, 0).UnixMilli()+ monthlyGrowth, err := s.statsRepo.GetUsersMonthlyGrowth(since)+ if err != nil {+ return nil, err+ }++ return &models.UserStats{+ TotalUsers: totalUsers,+ GrowthLast12Months: fillMissingMonths(monthlyGrowth, 12),+ }, nil+}++func (s *statsService) GetNodeStats(topLimit int) (*models.NodeStats, error) {+ totalNodes, err := s.statsRepo.GetNodesTotal()+ if err != nil {+ return nil, err+ }++ totalSize, err := s.statsRepo.GetNodesTotalSize()+ if err != nil {+ return nil, err+ }++ since := startOfMonthUTC(time.Now().UTC()).AddDate(0, -11, 0).UnixMilli()+ monthlyGrowth, err := s.statsRepo.GetNodesMonthlyGrowth(since)+ if err != nil {+ return nil, err+ }++ topByNodes, err := s.statsRepo.GetTopUsersByNodeCount(topLimit)+ if err != nil {+ return nil, err+ }++ topBySize, err := s.statsRepo.GetTopUsersByNodeSize(topLimit)+ if err != nil {+ return nil, err+ }++ return &models.NodeStats{+ TotalNodes: totalNodes,+ TotalSize: totalSize,+ GrowthLast12Months: fillMissingMonths(monthlyGrowth, 12),+ TopUsersByNodes: topByNodes,+ TopUsersBySize: topBySize,+ }, nil+}++func fillMissingMonths(series []models.MonthlyCount, months int) []models.MonthlyCount {+ if months <= 0 {+ return []models.MonthlyCount{}+ }++ lookup := make(map[string]int64, len(series))+ for _, row := range series {+ lookup[row.Month] = row.Count+ }++ now := startOfMonthUTC(time.Now().UTC())+ result := make([]models.MonthlyCount, 0, months)+ for i := months - 1; i >= 0; i-- {+ month := now.AddDate(0, -i, 0).Format("2006-01")+ result = append(result, models.MonthlyCount{+ Month: month,+ Count: lookup[month],+ })+ }++ return result+}++func startOfMonthUTC(t time.Time) time.Time {+ utc := t.UTC()+ return time.Date(utc.Year(), utc.Month(), 1, 0, 0, 0, 0, time.UTC)+}diff --git a/backend/services/user.service.go b/backend/services/user.service.goindex 4cf3ec08..e037e80a 100644--- a/backend/services/user.service.go+++ b/backend/services/user.service.go@@ -3,6 +3,7 @@ package servicesimport ("alexandrie/models""alexandrie/permissions"+ "alexandrie/pkg/logger""alexandrie/pkg/snowflake""alexandrie/repositories""alexandrie/types"@@ -12,6 +13,7 @@ import ("errors""fmt""regexp"+ "slices""strings""time"@@ -28,6 +30,7 @@ type UserService interface {UpdatePassword(ctx context.Context, id types.Snowflake, newPassword string) errorDeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) errorGenerateUniqueUsername(givenName *string, userID types.Snowflake) string+ LoadAppAdmins()}type userService struct {@@ -38,12 +41,14 @@ type userService struct {}func NewUserService(userRepo repositories.UserRepository, logRepo repositories.LogRepository, snowflake *snowflake.Snowflake, access permissions.AccessGuard) UserService {- return &userService{+ userService := &userService{userRepo: userRepo,logRepo: logRepo,snowflake: snowflake,access: access,}+ userService.LoadAppAdmins() // On startup, ensure admin users are loaded and updated+ return userService}func (s *userService) GetAllUsers() ([]*models.User, error) {@@ -223,3 +228,51 @@ func (s *userService) GenerateUniqueUsername(givenName *string, userID types.Snoreturn fmt.Sprintf("%s-%s", baseUsername, idSuffix)}++func (s *userService) LoadAppAdmins() {+ adminIDs := utils.GetEnvAsSlice("ADMIN_ACCOUNTS", ",")++ // Remove admin role from all users not in the current admin list+ existingAdmins, err := s.userRepo.GetAppAdmins()++ if err != nil {+ logger.Warn("app-admins", "Failed to load existing admin users: "+err.Error())+ return+ }++ for _, admin := range existingAdmins {+ if !slices.Contains(adminIDs, admin.Id.String()) {+ err := s.userRepo.UpdateRole(admin.Id, int(permissions.RoleNone))+ if err != nil {+ logger.Error("app-admins", "Failed to update user "+admin.Username+" to regular role: "+err.Error())+ } else {+ logger.Info("app-admins", "User "+admin.Username+" has been set to regular role.")+ }+ }+ }++ // Add new admins from the environment variable+ for _, idStr := range adminIDs {+ id, err := types.SnowflakeFromString(idStr)+ if err != nil {+ logger.Warn("app-admins", "Invalid admin user ID: "+idStr)+ continue+ }+ user, err := s.userRepo.GetByID(*id)+ if err != nil || user == nil {+ logger.Warn("app-admins", "Failed to load admin user with ID "+idStr+"\nCheck if the ID is correct and if the user exists.")+ continue+ }+ if user.Role != int(permissions.RoleAdministrator) {+ err := s.userRepo.UpdateRole(user.Id, int(permissions.RoleAdministrator))+ if err != nil {+ logger.Warn("app-admins", "Failed to update user "+user.Username+" to admin role: "+err.Error())+ } else {+ logger.Info("app-admins", "User "+user.Username+" has been granted admin role.")+ }+ } else {+ logger.Info("app-admins", "User "+user.Username+" is already an admin.")+ }+ }++}diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex 55244a35..dd5097f6 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -1,6 +1,9 @@package utils-import "os"+import (+ "os"+ "strings"+)func IfNotNilPointer[T any](newValue, defaultValue *T) *T {if newValue != nil {@@ -28,3 +31,11 @@ func GetBackupBucketName() string {func PtrString(s string) *string {return &s}++func GetEnvAsSlice(name string, sep string) []string {+ value := os.Getenv(name)+ if value == "" {+ return []string{}+ }+ return strings.Split(value, sep)+}diff --git a/docs/.env.example b/docs/.env.exampleindex 1fde582d..410d4e32 100644--- a/docs/.env.example+++ b/docs/.env.example@@ -31,6 +31,8 @@ COOKIE_DOMAIN=localhost:8200 # Common domain for cookies (e.g., yourdomALLOW_UNSECURE=true # true = HTTP allowed (local dev / local machine), false = HTTPS onlyJWT_SECRET=your-secure-jwt # Change this in production to a secure random string, used to sign JWT tokens for authentication+ADMIN_ACCOUNTS=id1,id2,id3 # Comma-separated list of user IDs that should have admin privileges (e.g., 1,2,3). Optional.+# OIDC (OpenID Connect) Configuration - Optional, only required if you want to enable OIDC authentication (e.g., Google, Keycloak, etc.). Replace {i} with a number between 1 to 9#OIDC_{i}_CONFIG_URL = # The URL to fetch the OIDC provider's configuration (e.g., https://accounts.google.com/.well-known/openid-configuration)#OIDC_{i}_CLIENT_ID = # The Client ID obtained from the OIDC provider for your applicationdiff --git a/docs/FAQ.md b/docs/FAQ.mdindex ee7c4fdb..66a69249 100644--- a/docs/FAQ.md+++ b/docs/FAQ.md@@ -87,3 +87,18 @@ This is usually caused by a misconfiguration of the `MINIO_SECURE` environment v- If your RustFS S3 server is running with HTTP (not HTTPS), then set: `MINIO_SECURE=false`- If your RustFS S3 server is running with HTTPS, then set: `MINIO_SECURE=true`++## Admins account not working or I don't see admin features++**Symptoms**++- You have set `ADMIN_ACCOUNTS` but you don't see admin features in the dashboard or you are not recognized as admin.++**Cause**+This is usually caused by an incorrect value in the `ADMIN_ACCOUNTS` environment variable or by not including your user ID in the list. This also be caused if you did not restart the backend service after changing the environment variable and logging out and back in.++**Correct configuration examples**++- If your user ID is `1` and you want to give admin privileges to users with IDs `2` and `3`, then set: `ADMIN_ACCOUNTS=1,2,3`+- Restart the backend service+- Wait for a few minutes to see changes in frontend (you may need to log out and log back in to see changes)diff --git a/docs/README.md b/docs/README.mdindex 52f2a917..c1965f7f 100644--- a/docs/README.md+++ b/docs/README.md@@ -101,6 +101,7 @@ These variables configure the backend API service.- If misconfigured, login will appear to work but users will be instantly logged out- `ALLOW_UNSECURE`: If set to `true`, HTTP connections are allowed (useful for local and dev). In production, it is recommended to set this to `false` to enforce HTTPS.- `JWT_SECRET`: Secret key used to sign JWT tokens. You should change this to a random long string correcly generated (with openssl or similar) in production for security. Changing this value will invalidate all existing sessions.+- `ADMIN_ACCOUNTS`: Comma-separated list of user IDs that should have admin privileges (e.g., `1,2,3`). Optional.### 4. Database β MySQLdiff --git a/docs/env.md b/docs/env.mdindex c46158d9..1925c1cf 100644--- a/docs/env.md+++ b/docs/env.md@@ -35,6 +35,7 @@ Only variables documented here and in `.env.example` are officially supported.| `COOKIE_DOMAIN` | Domain (no protocol) | Domain scope for authentication cookies. Must match the highest common domain between frontend and backend. || `ALLOW_UNSECURE` | `true` / `false` | Allows HTTP connections (recommended `false` in production). || `JWT_SECRET` | String | Secret key used to sign JWT tokens. Changing it invalidates all sessions. |+| `ADMIN_ACCOUNTS` | Comma-separated IDs | List of user IDs with admin privileges. |---diff --git a/ecosystem.config.js b/ecosystem.config.jsindex e6147f39..6af1b601 100644--- a/ecosystem.config.js+++ b/ecosystem.config.js@@ -1,33 +1,34 @@module.exports = {apps: [{- name: 'alexandrie-backend',- script: './backend_app',- cwd: './backend',+ name: "alexandrie-backend",+ script: "./backend_app",+ cwd: "./backend",env: {PORT: 8201,- FRONTEND_URL: 'https://alexandrie-hub.fr',- COOKIE_DOMAIN: 'alexandrie-hub.fr',+ FRONTEND_URL: "https://alexandrie-hub.fr",+ COOKIE_DOMAIN: "alexandrie-hub.fr",+ ADMIN_ACCOUNTS: "152981937240150016",- MINIO_ENDPOINT: 'cdn.alexandrie-hub.fr',- MINIO_PUBLIC_URL: 'https://cdn.alexandrie-hub.fr',- MINIO_BUCKET: 'alexandrie',- MINIO_SECURE: 'true',+ MINIO_ENDPOINT: "cdn.alexandrie-hub.fr",+ MINIO_PUBLIC_URL: "https://cdn.alexandrie-hub.fr",+ MINIO_BUCKET: "alexandrie",+ MINIO_SECURE: "true",- DATABASE_HOST: 'localhost',+ DATABASE_HOST: "localhost",DATABASE_PORT: 3306,- DATABASE_NAME: 'alexandrie',+ DATABASE_NAME: "alexandrie",- CPWD: './backend/',- GIN_MODE: 'release',+ CPWD: "./backend/",+ GIN_MODE: "release",},},{- name: 'alexandrie-frontend',- cwd: './frontend',- script: 'bun .output/server/index.mjs',+ name: "alexandrie-frontend",+ cwd: "./frontend",+ script: "bun .output/server/index.mjs",env: {- NODE_ENV: 'production',+ NODE_ENV: "production",PORT: 8200,},},diff --git a/frontend/app/pages/dashboard/admin/index.vue b/frontend/app/pages/dashboard/admin/index.vueindex 8dddf7a8..cbaddb07 100644--- a/frontend/app/pages/dashboard/admin/index.vue+++ b/frontend/app/pages/dashboard/admin/index.vue@@ -1,12 +1,251 @@<template>- <div class="page-card">- <h1>{{ t('admin.dashboard.title') }}</h1>- <p>{{ t('admin.dashboard.description') }}</p>- <AppButton type="primary" @click="router.push('/dashboard/admin/users')">{{ t('admin.dashboard.manageUsers') }}</AppButton>+ <div class="admin-dashboard page-card">+ <header class="admin-header">+ <div>+ <h1>{{ t('admin.dashboard.title') }}</h1>+ <p>{{ t('admin.dashboard.description') }}</p>+ </div>+ <AppButton type="primary" @click="router.push('/dashboard/admin/users')">{{ t('admin.dashboard.manageUsers') }}</AppButton>+ </header>++ <div v-if="store.loadingStats" class="stats-loading">+ <Loader />+ <span>{{ t('admin.dashboard.loading') }}</span>+ </div>++ <div v-else-if="store.statsError" class="stats-error">{{ t('admin.dashboard.error') }}: {{ store.statsError }}</div>++ <template v-else>+ <section class="kpi-grid">+ <article class="kpi-card">+ <p class="kpi-label">{{ t('admin.dashboard.cards.totalUsers') }}</p>+ <p class="kpi-value">{{ formatNumber(store.stats.overview.total_users) }}</p>+ </article>+ <article class="kpi-card">+ <p class="kpi-label">{{ t('admin.dashboard.cards.totalNodes') }}</p>+ <p class="kpi-value">{{ formatNumber(store.stats.overview.total_nodes) }}</p>+ </article>+ <article class="kpi-card">+ <p class="kpi-label">{{ t('admin.dashboard.cards.totalStorage') }}</p>+ <p class="kpi-value">{{ readableFileSize(store.stats.overview.total_size) }}</p>+ </article>+ </section>++ <section class="chart-grid">+ <article class="chart-card">+ <h2>{{ t('admin.dashboard.charts.usersGrowth') }}</h2>+ <svg viewBox="0 0 100 40" preserveAspectRatio="none" class="sparkline" role="img" aria-label="Users monthly growth chart">+ <polyline :points="usersPoints" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" vector-effect="non-scaling-stroke" />+ </svg>+ <ul class="month-row">+ <li v-for="item in store.stats.users.growth_last_12_months" :key="`users-${item.month}`">{{ formatMonth(item.month) }}</li>+ </ul>+ </article>++ <article class="chart-card">+ <h2>{{ t('admin.dashboard.charts.nodesGrowth') }}</h2>+ <svg viewBox="0 0 100 40" preserveAspectRatio="none" class="sparkline" role="img" aria-label="Nodes monthly growth chart">+ <polyline :points="nodesPoints" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" vector-effect="non-scaling-stroke" />+ </svg>+ <ul class="month-row">+ <li v-for="item in store.stats.nodes.growth_last_12_months" :key="`nodes-${item.month}`">{{ formatMonth(item.month) }}</li>+ </ul>+ </article>+ </section>++ <section class="top-grid">+ <article class="top-card">+ <h2>{{ t('admin.dashboard.top.byNodes') }}</h2>+ <table>+ <thead>+ <tr>+ <th>{{ t('admin.dashboard.top.user') }}</th>+ <th>{{ t('admin.dashboard.top.nodes') }}</th>+ <th>{{ t('admin.dashboard.top.storage') }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="row in store.stats.nodes.top_users_by_nodes" :key="`n-${row.user_id}`">+ <td>+ <NuxtLink :to="`/dashboard/admin/users/${row.user_id}`">{{ row.username }}</NuxtLink>+ </td>+ <td>{{ formatNumber(row.node_count) }}</td>+ <td>{{ readableFileSize(row.total_size) }}</td>+ </tr>+ </tbody>+ </table>+ </article>++ <article class="top-card">+ <h2>{{ t('admin.dashboard.top.byStorage') }}</h2>+ <table>+ <thead>+ <tr>+ <th>{{ t('admin.dashboard.top.user') }}</th>+ <th>{{ t('admin.dashboard.top.nodes') }}</th>+ <th>{{ t('admin.dashboard.top.storage') }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="row in store.stats.nodes.top_users_by_size" :key="`s-${row.user_id}`">+ <td>+ <NuxtLink :to="`/dashboard/admin/users/${row.user_id}`">{{ row.username }}</NuxtLink>+ </td>+ <td>{{ formatNumber(row.node_count) }}</td>+ <td>{{ readableFileSize(row.total_size) }}</td>+ </tr>+ </tbody>+ </table>+ </article>+ </section>+ </template></div></template><script setup lang="ts">+import { readableFileSize } from '~/helpers/resources';+import type { MonthlyCount } from '~/stores';+const router = useRouter();const { t } = useI18nT();++const store = useAdminStore();++void store.fetchAll();+void store.fetchStats().catch(() => undefined);++const usersPoints = computed(() => toPolyline(store.stats.users.growth_last_12_months));+const nodesPoints = computed(() => toPolyline(store.stats.nodes.growth_last_12_months));++function formatNumber(value: number): string {+ return new Intl.NumberFormat().format(value || 0);+}++function formatMonth(month: string): string {+ const [year, rawMonth] = month.split('-');+ const monthIndex = Number(rawMonth) - 1;+ const parsed = new Date(Date.UTC(Number(year), monthIndex, 1));+ return parsed.toLocaleDateString(undefined, { month: 'short' });+}++function toPolyline(series: MonthlyCount[]): string {+ if (!series?.length) return '0,40 100,40';+ const values = series.map(item => Math.max(0, item.count ?? 0));+ const max = Math.max(...values, 1);+ return values+ .map((value, index) => {+ const x = (index / Math.max(values.length - 1, 1)) * 100;+ const y = 40 - (value / max) * 34 - 3;+ return `${x.toFixed(2)},${y.toFixed(2)}`;+ })+ .join(' ');+}</script>++<style scoped lang="scss">+a:hover {+ color: var(--primary);+}+.admin-dashboard {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.admin-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 1rem;+}++.stats-loading,+.stats-error {+ display: flex;+ align-items: center;+ gap: 0.6rem;+}++.stats-error {+ color: var(--red);+}++.kpi-grid,+.chart-grid,+.top-grid {+ display: grid;+ gap: 0.9rem;+}++.kpi-grid {+ grid-template-columns: repeat(3, minmax(0, 1fr));+}++.chart-grid,+.top-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+}++.kpi-card,+.chart-card,+.top-card {+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ padding: 1rem;+ background: radial-gradient(circle at top right, color-mix(in srgb, var(--primary) 11%, transparent), transparent 54%), var(--background-100);+}++.kpi-label {+ margin: 0;+ color: var(--text-muted);+ font-size: 0.9rem;+}++.kpi-value {+ margin: 0.35rem 0 0;+ font-weight: 700;+ font-size: clamp(1.2rem, 2vw, 1.8rem);+}++.sparkline {+ width: 100%;+ height: 120px;+ color: var(--primary);+}++.month-row {+ list-style: none;+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ padding: 0;+ margin: 0;+ color: var(--text-muted);+ font-size: 0.72rem;+ gap: 0.2rem;+ text-align: center;+}++table {+ width: 100%;+}++@media screen and (width <= 900px) {+ .admin-header {+ align-items: flex-start;+ flex-direction: column;+ }++ .kpi-grid {+ grid-template-columns: 1fr;+ }++ .chart-grid,+ .top-grid {+ grid-template-columns: 1fr;+ }++ .month-row {+ font-size: 0.65rem;+ }+}+</style>diff --git a/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vue b/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vueindex 7bae6963..3ddf7449 100644--- a/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vue+++ b/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vue@@ -1,39 +1,79 @@<template>- <div class="page-card" style="height: 100%; padding: 35px 25px; overflow: auto">+ <div class="page-card" style="height: 100%; overflow: auto"><h1>Node advanced view</h1>- <div v-if="document" style="display: flex; height: 100%; min-height: 0; flex-direction: column">- <label for="id">ID</label>- <input id="id" v-model="document.id" disabled />- <label for="user_id">User ID</label>- <input id="user_id" v-model="document.user_id" disabled />- <label for="parent_id">Parent ID</label>- <input id="parent_id" v-model="document.parent_id" disabled />+ <div v-if="document">+ <div class="columns">+ <div class="column">+ <label for="id">ID</label>+ <input id="id" v-model="document.id" disabled />+ </div>+ <div class="column">+ <label for="user_id">User ID</label>+ <input id="user_id" v-model="document.user_id" disabled />+ </div>+ <div class="column">+ <label for="parent_id">Parent ID</label>+ <input id="parent_id" v-model="document.parent_id" disabled />+ </div>+ <div class="column">+ <label for="size">Size</label>+ <input id="size" v-model="document.size" disabled />+ </div>+ </div><label for="name">Name</label><input id="name" v-model="document.name" />+<label for="description">Description</label><input id="description" v-model="document.description" />- <label for="tags">Tags</label>- <input id="tags" v-model="document.tags" />- <label for="role">Role</label>- <input id="role" v-model="document.role" type="number" />- <label for="color">Color</label>- <input id="color" v-model="document.color" />- <label for="icon">Icon</label>- <input id="icon" v-model="document.icon" />- <label for="thumbnail">Thumbnail</label>- <input id="thumbnail" v-model="document.thumbnail" />- <label for="theme">Theme</label>- <input id="theme" v-model="document.theme" />- <label for="accessibility">Accessibility</label>- <input id="accessibility" v-model="document.accessibility" />- <label for="access">Access</label>- <input id="access" v-model="document.access" />- <label for="display">Display</label>- <input id="display" v-model="document.display" />- <label for="order">Order</label>- <input id="order" v-model="document.order" />- <label for="size">Size</label>- <input id="size" v-model="document.size" />+ <div class="columns">+ <div class="column">+ <label for="tags">Tags</label>+ <input id="tags" v-model="document.tags" />+ </div>+ <div class="column">+ <label for="theme">Theme</label>+ <input id="theme" v-model="document.theme" />+ </div>+ <div class="column">+ <label for="order">Order</label>+ <input id="order" v-model="document.order" />+ </div>+ </div>+ <div class="columns">+ <div class="column">+ <label for="role">Role</label>+ <input id="role" v-model="document.role" type="number" />+ </div>+ <div class="column">+ <label for="color">Color</label>+ <input id="color" v-model="document.color" />+ </div>+ <div class="column">+ <label for="accessibility">Accessibility</label>+ <input id="accessibility" v-model="document.accessibility" />+ </div>+ </div>+ <div class="columns">+ <div class="column">+ <label for="access">Access</label>+ <input id="access" v-model="document.access" />+ </div>+ <div class="column">+ <label for="display">Display</label>+ <input id="display" v-model="document.display" />+ </div>+ </div>+ <div class="columns">+ <div class="column">+ <label for="icon">Icon</label>+ <input id="icon" v-model="document.icon" />+ </div>+ <div class="column">+ <label for="thumbnail">Thumbnail</label>+ <input id="thumbnail" v-model="document.thumbnail" />+ </div>+ </div>+<label for="content">Content</label><div style="display: flex; width: 100%; height: 500px; flex: 1; gap: 10px"><textarea v-model="document.content" style="height: 500px; flex: 1; overflow: auto"></textarea>@@ -68,4 +108,10 @@ label {button {margin-top: 1rem;}+.columns {+ gap: 10px;+}+.column {+ margin: 0;+}</style>diff --git a/frontend/app/pages/dashboard/admin/users/index.vue b/frontend/app/pages/dashboard/admin/users/index.vueindex 4ed8646d..f1c219d3 100644--- a/frontend/app/pages/dashboard/admin/users/index.vue+++ b/frontend/app/pages/dashboard/admin/users/index.vue@@ -21,8 +21,6 @@ const { t } = useI18nT();const { avatarURL } = useApi();const { numericDate } = useDateFormatters();-adminStore.fetchAll();-const headers = computed(() => [{ label: t('admin.users.headers.name'), key: 'username' },{ label: t('admin.users.headers.firstname'), key: 'firstname' },diff --git a/frontend/app/pages/dashboard/settings/_views/profile.vue b/frontend/app/pages/dashboard/settings/_views/profile.vueindex 2238cca3..d5591c0f 100644--- a/frontend/app/pages/dashboard/settings/_views/profile.vue+++ b/frontend/app/pages/dashboard/settings/_views/profile.vue@@ -3,6 +3,10 @@<h2 class="page-title">{{ t('settings.profile.title') }}</h2><p class="page-subtitle">{{ t('settings.profile.subtitle') }}</p><form v-if="userStore.user" @submit.prevent="updateUser">+ <div v-if="devMode" class="form-group">+ <label for="id">{{ t('common.labels.id') }}</label>+ <input id="id" v-model="userStore.user.id" type="text" disabled />+ </div><div class="form-group"><label for="username">{{ t('settings.profile.username') }}</label><input id="username" v-model="userStore.user.username" type="text" disabled required />@@ -39,6 +43,7 @@<script setup lang="ts">const userStore = useUserStore();const resourcesStore = useResourcesStore();+const preferencesStore = usePreferencesStore();const { avatarURL } = useApi();const { shortDate } = useDateFormatters();@@ -47,6 +52,7 @@ const { t } = useI18nT();const avatarInput = ref<HTMLInputElement | null>(null);const avatarPreview = ref('');const avatarDisplayed = computed(() => avatarPreview.value || avatarURL(userStore.user));+const devMode = preferencesStore.get('developerMode');const selectAvatar = () => avatarInput.value?.click();diff --git a/frontend/app/pages/dashboard/settings/index.vue b/frontend/app/pages/dashboard/settings/index.vueindex 600cdf13..7ce6a164 100644--- a/frontend/app/pages/dashboard/settings/index.vue+++ b/frontend/app/pages/dashboard/settings/index.vue@@ -218,6 +218,7 @@ watchEffect(() => {}.modal {+ height: 100%;nav {width: 270px;border: none;diff --git a/frontend/app/stores/admin.store.ts b/frontend/app/stores/admin.store.tsindex 8f617ab7..370ee417 100644--- a/frontend/app/stores/admin.store.ts+++ b/frontend/app/stores/admin.store.ts@@ -1,4 +1,4 @@-import type { User, Node } from './db_strustures';+import type { User, Node, OverviewStats, UserStats, NodeStats } from './db_strustures';interface UserData extends User {nodes?: Node[];@@ -7,6 +7,26 @@ interface UserData extends User {export const useAdminStore = defineStore('admin', {state: () => ({users: ref<UserData[]>(),+ loadingStats: false,+ statsError: '',+ stats: {+ overview: {+ total_users: 0,+ total_nodes: 0,+ total_size: 0,+ } as OverviewStats,+ users: {+ total_users: 0,+ growth_last_12_months: [],+ } as UserStats,+ nodes: {+ total_nodes: 0,+ total_size: 0,+ growth_last_12_months: [],+ top_users_by_nodes: [],+ top_users_by_size: [],+ } as NodeStats,+ },}),actions: {async fetchAll(): Promise<UserData[] | undefined> {@@ -47,5 +67,41 @@ export const useAdminStore = defineStore('admin', {return responce.result?.node;} else throw responce.message;},+ async fetchOverviewStats() {+ const response = await makeRequest<OverviewStats>('stats/overview', 'GET', {});+ if (response.status === 'success' && response.result) {+ this.stats.overview = response.result;+ return response.result;+ }+ throw response.message;+ },+ async fetchUsersStats() {+ const response = await makeRequest<UserStats>('stats/users', 'GET', {});+ if (response.status === 'success' && response.result) {+ this.stats.users = response.result;+ return response.result;+ }+ throw response.message;+ },+ async fetchNodesStats(top = 5) {+ const response = await makeRequest<NodeStats>(`stats/nodes?top=${top}`, 'GET', {});+ if (response.status === 'success' && response.result) {+ this.stats.nodes = response.result;+ return response.result;+ }+ throw response.message;+ },+ async fetchStats(top = 5) {+ this.loadingStats = true;+ this.statsError = '';+ try {+ await Promise.all([this.fetchOverviewStats(), this.fetchUsersStats(), this.fetchNodesStats(top)]);+ } catch (error) {+ this.statsError = String(error);+ throw error;+ } finally {+ this.loadingStats = false;+ }+ },},});diff --git a/frontend/app/stores/db_strustures.d.ts b/frontend/app/stores/db_strustures.d.tsindex f7a2111e..a1fc4fc9 100644--- a/frontend/app/stores/db_strustures.d.ts+++ b/frontend/app/stores/db_strustures.d.ts@@ -103,6 +103,37 @@ export interface Session {logout_timestamp?: number;}+export interface MonthlyCount {+ month: string; // Format: YYYY-MM+ count: number;+}++export interface UserStats {+ total_users: number;+ growth_last_12_months: MonthlyCount[];+}++export interface NodeOwnerStats {+ user_id: string;+ username: string;+ node_count: number;+ total_size: number;+}++export interface NodeStats {+ total_nodes: number;+ total_size: number;+ growth_last_12_months: MonthlyCount[];+ top_users_by_nodes: NodeOwnerStats[];+ top_users_by_size: NodeOwnerStats[];+}++export interface OverviewStats {+ total_users: number;+ total_nodes: number;+ total_size: number;+}+// Internal structuresexport interface ImportJob {diff --git a/frontend/i18n/locales/en/admin.ts b/frontend/i18n/locales/en/admin.tsindex e4931422..e2fcc34d 100644--- a/frontend/i18n/locales/en/admin.ts+++ b/frontend/i18n/locales/en/admin.ts@@ -1,7 +1,25 @@export default {dashboard: {+ cards: {+ totalNodes: 'Total nodes',+ totalStorage: 'Total storage',+ totalUsers: 'Total users',+ },+ charts: {+ nodesGrowth: 'Nodes growth (12 months)',+ usersGrowth: 'Users growth (12 months)',+ },description: 'From this dashboard you can manage site users and settings.',+ error: 'Unable to load stats',+ loading: 'Loading stats...',manageUsers: 'Manage users',+ top: {+ byNodes: 'Top users by number of nodes',+ byStorage: 'Top users by storage usage',+ nodes: 'Nodes',+ storage: 'Storage',+ user: 'User',+ },title: 'Admin dashboard',},diff --git a/frontend/i18n/locales/fr/admin.ts b/frontend/i18n/locales/fr/admin.tsindex 2d2e2901..effa5a65 100644--- a/frontend/i18n/locales/fr/admin.ts+++ b/frontend/i18n/locales/fr/admin.ts@@ -1,7 +1,25 @@export default {dashboard: {+ cards: {+ totalNodes: 'Total de nodes',+ totalStorage: 'Stockage total',+ totalUsers: 'Total utilisateurs',+ },+ charts: {+ nodesGrowth: 'Evolution des nodes (12 mois)',+ usersGrowth: 'Evolution des utilisateurs (12 mois)',+ },description: 'Depuis ce tableau de bord, vous pouvez gΓ©rer les utilisateurs et les paramΓ¨tres du site.',+ error: 'Impossible de charger les statistiques',+ loading: 'Chargement des statistiques...',manageUsers: 'GΓ©rer les utilisateurs',+ top: {+ byNodes: 'Top utilisateurs par nombre de nodes',+ byStorage: 'Top utilisateurs par usage de stockage',+ nodes: 'Nodes',+ storage: 'Stockage',+ user: 'Utilisateur',+ },title: 'Tableau de bord admin',},