mirror of
https://github.com/serty2005/rmser.git
synced 2026-02-04 19:02:33 -06:00
сложно поддерживать однояйцевых близнецов - desktop и TMA, подготовил к рефакторингу структуры
173 lines
8.0 KiB
Go
173 lines
8.0 KiB
Go
package account
|
||
|
||
import (
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
// Роли пользователей
|
||
type Role string
|
||
|
||
const (
|
||
RoleOwner Role = "OWNER" // Создатель: Полный доступ + удаление сервера
|
||
RoleAdmin Role = "ADMIN" // Администратор: Редактирование, настройки, приглашение
|
||
RoleOperator Role = "OPERATOR" // Оператор: Только загрузка фото
|
||
)
|
||
|
||
// User - Пользователь системы (Telegram аккаунт)
|
||
type User struct {
|
||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||
TelegramID int64 `gorm:"uniqueIndex;not null" json:"telegram_id"`
|
||
Username string `gorm:"type:varchar(100)" json:"username"`
|
||
FirstName string `gorm:"type:varchar(100)" json:"first_name"`
|
||
LastName string `gorm:"type:varchar(100)" json:"last_name"`
|
||
PhotoURL string `gorm:"type:text" json:"photo_url"`
|
||
|
||
IsSystemAdmin bool `gorm:"default:false" json:"is_system_admin"`
|
||
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
}
|
||
|
||
// ServerUser - Связь пользователя с сервером (здесь храним личные креды)
|
||
type ServerUser struct {
|
||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
|
||
ServerID uuid.UUID `gorm:"type:uuid;not null;index:idx_user_server,unique"`
|
||
UserID uuid.UUID `gorm:"type:uuid;not null;index:idx_user_server,unique"`
|
||
|
||
Role Role `gorm:"type:varchar(20);default:'OPERATOR'"`
|
||
IsActive bool `gorm:"default:false"` // Выбран ли этот сервер сейчас
|
||
|
||
// === Настройки уведомлений ===
|
||
MuteDraftNotifications bool `gorm:"default:false" json:"mute_draft_notifications"` // Не получать уведомления о новых черновиках
|
||
|
||
// Персональные данные для подключения (могут быть null у операторов)
|
||
Login string `gorm:"type:varchar(100)"`
|
||
EncryptedPassword string `gorm:"type:text"`
|
||
|
||
Server RMSServer `gorm:"foreignKey:ServerID"`
|
||
User User `gorm:"foreignKey:UserID"`
|
||
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
}
|
||
|
||
// RMSServer - Инстанс сервера iiko
|
||
type RMSServer struct {
|
||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()" json:"id"`
|
||
|
||
// Уникальный URL (очищенный), определяет инстанс
|
||
BaseURL string `gorm:"type:varchar(255);not null;uniqueIndex" json:"base_url"`
|
||
|
||
Name string `gorm:"type:varchar(100);not null" json:"name"`
|
||
MaxUsers int `gorm:"default:5" json:"max_users"` // Лимит пользователей
|
||
|
||
// Глобальные настройки сервера (общие для всех)
|
||
DefaultStoreID *uuid.UUID `gorm:"type:uuid" json:"default_store_id"`
|
||
RootGroupGUID *uuid.UUID `gorm:"type:uuid" json:"root_group_guid"`
|
||
AutoProcess bool `gorm:"default:false" json:"auto_process"`
|
||
|
||
// Billing
|
||
Balance int `gorm:"default:0" json:"balance"`
|
||
PaidUntil *time.Time `json:"paid_until"`
|
||
|
||
// Stats
|
||
InvoiceCount int `gorm:"default:0" json:"invoice_count"`
|
||
|
||
// Sync settings
|
||
SyncInterval int `gorm:"default:360" json:"sync_interval"` // Интервал синхронизации в минутах (default: 6 часов)
|
||
LastSyncAt *time.Time `json:"last_sync_at"` // Время последней успешной синхронизации
|
||
LastActivityAt *time.Time `json:"last_activity_at"` // Время последнего действия пользователя
|
||
|
||
// Soft delete
|
||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
}
|
||
|
||
// Session - Сессия пользователя для аутентификации
|
||
type Session struct {
|
||
ID uuid.UUID `gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
|
||
UserID uuid.UUID `gorm:"type:uuid;not null;index"`
|
||
RefreshToken string `gorm:"type:varchar(255);not null;index"` // Уникальный токен сессии
|
||
UserAgent string `gorm:"type:varchar(255)"`
|
||
IP string `gorm:"type:varchar(50)"`
|
||
ExpiresAt time.Time `gorm:"index"`
|
||
CreatedAt time.Time
|
||
UpdatedAt time.Time // Для отслеживания sliding expiration
|
||
}
|
||
|
||
// Repository интерфейс
|
||
type Repository interface {
|
||
// Users
|
||
GetOrCreateUser(telegramID int64, username, first, last string) (*User, error)
|
||
GetUserByTelegramID(telegramID int64) (*User, error)
|
||
GetUserByID(id uuid.UUID) (*User, error)
|
||
|
||
// ConnectServer - Основной метод подключения.
|
||
ConnectServer(userID uuid.UUID, url, login, encryptedPass, name string) (*RMSServer, error)
|
||
GetServerByURL(url string) (*RMSServer, error)
|
||
GetServerByID(id uuid.UUID) (*RMSServer, error)
|
||
|
||
SaveServerSettings(server *RMSServer) error
|
||
|
||
// SetActiveServer переключает активность в таблице ServerUser
|
||
SetActiveServer(userID, serverID uuid.UUID) error
|
||
|
||
// GetActiveServer ищет сервер, где у UserID стоит флаг IsActive=true
|
||
GetActiveServer(userID uuid.UUID) (*RMSServer, error)
|
||
|
||
// GetActiveConnectionCredentials возвращает актуальные логин/пароль для текущего юзера (личные или общие)
|
||
GetActiveConnectionCredentials(userID uuid.UUID) (url, login, passHash string, err error)
|
||
|
||
// GetAllAvailableServers возвращает все серверы, доступные пользователю (в любом статусе)
|
||
GetAllAvailableServers(userID uuid.UUID) ([]RMSServer, error)
|
||
DeleteServer(serverID uuid.UUID) error
|
||
|
||
// GetUserRole возвращает роль пользователя на сервере (или ошибку доступа)
|
||
GetUserRole(userID, serverID uuid.UUID) (Role, error)
|
||
SetUserRole(serverID, targetUserID uuid.UUID, newRole Role) error
|
||
GetServerUsers(serverID uuid.UUID) ([]ServerUser, error)
|
||
|
||
// Invite System
|
||
AddUserToServer(serverID, userID uuid.UUID, role Role) error
|
||
RemoveUserFromServer(serverID, userID uuid.UUID) error
|
||
|
||
// Billing & Stats
|
||
IncrementInvoiceCount(serverID uuid.UUID) error
|
||
UpdateBalance(serverID uuid.UUID, amountChange int, newPaidUntil *time.Time) error
|
||
DecrementBalance(serverID uuid.UUID) error
|
||
|
||
// Super Admin Functions
|
||
GetAllServersSystemWide() ([]RMSServer, error)
|
||
TransferOwnership(serverID, newOwnerID uuid.UUID) error
|
||
|
||
// GetConnectionByID получает связь ServerUser по её ID (нужно для админки, чтобы сократить callback_data)
|
||
GetConnectionByID(id uuid.UUID) (*ServerUser, error)
|
||
|
||
// === Уведомления о черновиках ===
|
||
// GetServerUsersForDraftNotification возвращает Admin/Owner пользователей,
|
||
// которым нужно отправить уведомление о новом черновике
|
||
GetServerUsersForDraftNotification(serverID uuid.UUID, excludeUserID uuid.UUID) ([]ServerUser, error)
|
||
|
||
// SetMuteDraftNotifications включает/выключает уведомления для пользователя
|
||
SetMuteDraftNotifications(userID, serverID uuid.UUID, mute bool) error
|
||
|
||
// === Синхронизация и активность ===
|
||
// UpdateLastActivity обновляет время последней активности пользователя на сервере
|
||
UpdateLastActivity(serverID uuid.UUID) error
|
||
// UpdateLastSync обновляет время последней успешной синхронизации
|
||
UpdateLastSync(serverID uuid.UUID) error
|
||
// GetServersForSync возвращает серверы, готовые для синхронизации
|
||
GetServersForSync(idleThreshold time.Duration) ([]RMSServer, error)
|
||
|
||
// === Session Management ===
|
||
CreateSession(session *Session) error
|
||
GetSessionByToken(token string) (*Session, error)
|
||
UpdateSessionExpiry(sessionID uuid.UUID, newExpiry time.Time) error
|
||
DeleteSession(token string) error
|
||
}
|