Merge remote-tracking branch 'origin/master' into internal

This commit is contained in:
2026-03-19 01:55:01 -07:00
101 changed files with 6910 additions and 330 deletions
+54
View File
@@ -0,0 +1,54 @@
package group
import (
"time"
"gorm.io/gorm"
)
// GroupHistory 分组历史记录模型
type GroupHistory struct {
Id int64 `gorm:"primaryKey"`
GroupMode string `gorm:"type:varchar(50);not null;index:idx_group_mode;comment:Group Mode: average/subscribe/traffic"`
TriggerType string `gorm:"type:varchar(50);not null;index:idx_trigger_type;comment:Trigger Type: manual/auto/schedule"`
State string `gorm:"type:varchar(50);not null;index:idx_state;comment:State: pending/running/completed/failed"`
TotalUsers int `gorm:"default:0;not null;comment:Total Users"`
SuccessCount int `gorm:"default:0;not null;comment:Success Count"`
FailedCount int `gorm:"default:0;not null;comment:Failed Count"`
StartTime *time.Time `gorm:"comment:Start Time"`
EndTime *time.Time `gorm:"comment:End Time"`
Operator string `gorm:"type:varchar(100);comment:Operator"`
ErrorMessage string `gorm:"type:TEXT;comment:Error Message"`
CreatedAt time.Time `gorm:"<-:create;index:idx_created_at;comment:Create Time"`
}
// TableName 指定表名
func (*GroupHistory) TableName() string {
return "group_history"
}
// BeforeCreate GORM hook - 创建前回调
func (gh *GroupHistory) BeforeCreate(tx *gorm.DB) error {
return nil
}
// GroupHistoryDetail 分组历史详情模型
type GroupHistoryDetail struct {
Id int64 `gorm:"primaryKey"`
HistoryId int64 `gorm:"not null;index:idx_history_id;comment:History ID"`
NodeGroupId int64 `gorm:"not null;index:idx_node_group_id;comment:Node Group ID"`
UserCount int `gorm:"default:0;not null;comment:User Count"`
NodeCount int `gorm:"default:0;not null;comment:Node Count"`
UserData string `gorm:"type:text;comment:User data JSON (id and email/phone)"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
}
// TableName 指定表名
func (*GroupHistoryDetail) TableName() string {
return "group_history_detail"
}
// BeforeCreate GORM hook - 创建前回调
func (ghd *GroupHistoryDetail) BeforeCreate(tx *gorm.DB) error {
return nil
}
+14
View File
@@ -0,0 +1,14 @@
package group
import (
"gorm.io/gorm"
)
// AutoMigrate 自动迁移数据库表
func AutoMigrate(db *gorm.DB) error {
return db.AutoMigrate(
&NodeGroup{},
&GroupHistory{},
&GroupHistoryDetail{},
)
}
+34
View File
@@ -0,0 +1,34 @@
package group
import (
"time"
"gorm.io/gorm"
)
// NodeGroup 节点组模型
type NodeGroup struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;comment:Name"`
Description string `gorm:"type:varchar(500);comment:Description"`
Sort int `gorm:"default:0;index:idx_sort;comment:Sort Order"`
ForCalculation *bool `gorm:"default:true;not null;comment:For Calculation: whether this node group participates in grouping calculation"`
IsExpiredGroup *bool `gorm:"default:false;not null;index:idx_is_expired_group;comment:Is Expired Group"`
ExpiredDaysLimit int `gorm:"default:7;not null;comment:Expired days limit (days)"`
MaxTrafficGBExpired *int64 `gorm:"default:0;comment:Max traffic for expired users (GB)"`
SpeedLimit int `gorm:"default:0;not null;comment:Speed limit (KB/s)"`
MinTrafficGB *int64 `gorm:"default:0;comment:Minimum Traffic (GB) for this node group"`
MaxTrafficGB *int64 `gorm:"default:0;comment:Maximum Traffic (GB) for this node group"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
// TableName 指定表名
func (*NodeGroup) TableName() string {
return "node_group"
}
// BeforeCreate GORM hook - 创建前回调
func (ng *NodeGroup) BeforeCreate(tx *gorm.DB) error {
return nil
}
+22 -9
View File
@@ -34,15 +34,16 @@ type FilterParams struct {
}
type FilterNodeParams struct {
Page int // Page Number
Size int // Page Size
NodeId []int64 // Node IDs
ServerId []int64 // Server IDs
Tag []string // Tags
Search string // Search Address or Name
Protocol string // Protocol
Preload bool // Preload Server
Enabled *bool // Enabled
Page int // Page Number
Size int // Page Size
NodeId []int64 // Node IDs
ServerId []int64 // Server IDs
Tag []string // Tags
NodeGroupIds []int64 // Node Group IDs
Search string // Search Address or Name
Protocol string // Protocol
Preload bool // Preload Server
Enabled *bool // Enabled
}
// FilterServerList Filter Server List
@@ -97,6 +98,18 @@ func (m *customServerModel) FilterNodeList(ctx context.Context, params *FilterNo
if len(params.Tag) > 0 {
query = query.Scopes(InSet("tags", params.Tag))
}
if len(params.NodeGroupIds) > 0 {
// Filter by node_group_ids using JSON_CONTAINS for each group ID
// Multiple group IDs: node must belong to at least one of the groups
var conditions []string
for _, gid := range params.NodeGroupIds {
conditions = append(conditions, fmt.Sprintf("JSON_CONTAINS(node_group_ids, %d)", gid))
}
if len(conditions) > 0 {
query = query.Where("(" + strings.Join(conditions, " OR ") + ")")
}
}
// If no NodeGroupIds specified, return all nodes (including public nodes)
if params.Protocol != "" {
query = query.Where("protocol = ?", params.Protocol)
}
+60 -12
View File
@@ -1,25 +1,73 @@
package node
import (
"database/sql/driver"
"encoding/json"
"time"
"github.com/perfect-panel/server/pkg/logger"
"gorm.io/gorm"
)
// JSONInt64Slice is a custom type for handling []int64 as JSON in database
type JSONInt64Slice []int64
// Scan implements sql.Scanner interface
func (j *JSONInt64Slice) Scan(value interface{}) error {
if value == nil {
*j = []int64{}
return nil
}
// Handle []byte
bytes, ok := value.([]byte)
if !ok {
// Try to handle string
str, ok := value.(string)
if !ok {
*j = []int64{}
return nil
}
bytes = []byte(str)
}
if len(bytes) == 0 {
*j = []int64{}
return nil
}
// Check if it's a JSON array
if bytes[0] != '[' {
// Not a JSON array, return empty slice
*j = []int64{}
return nil
}
return json.Unmarshal(bytes, j)
}
// Value implements driver.Valuer interface
func (j JSONInt64Slice) Value() (driver.Value, error) {
if len(j) == 0 {
return "[]", nil
}
return json.Marshal(j)
}
type Node struct {
Id int64 `gorm:"primary_key"`
Name string `gorm:"type:varchar(100);not null;default:'';comment:Node Name"`
Tags string `gorm:"type:varchar(255);not null;default:'';comment:Tags"`
Port uint16 `gorm:"not null;default:0;comment:Connect Port"`
Address string `gorm:"type:varchar(255);not null;default:'';comment:Connect Address"`
ServerId int64 `gorm:"not null;default:0;comment:Server ID"`
Server *Server `gorm:"foreignKey:ServerId;references:Id"`
Protocol string `gorm:"type:varchar(100);not null;default:'';comment:Protocol"`
Enabled *bool `gorm:"type:boolean;not null;default:true;comment:Enabled"`
Sort int `gorm:"uniqueIndex;not null;default:0;comment:Sort"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
Id int64 `gorm:"primary_key"`
Name string `gorm:"type:varchar(100);not null;default:'';comment:Node Name"`
Tags string `gorm:"type:varchar(255);not null;default:'';comment:Tags"`
Port uint16 `gorm:"not null;default:0;comment:Connect Port"`
Address string `gorm:"type:varchar(255);not null;default:'';comment:Connect Address"`
ServerId int64 `gorm:"not null;default:0;comment:Server ID"`
Server *Server `gorm:"foreignKey:ServerId;references:Id"`
Protocol string `gorm:"type:varchar(100);not null;default:'';comment:Protocol"`
Enabled *bool `gorm:"type:boolean;not null;default:true;comment:Enabled"`
Sort int `gorm:"uniqueIndex;not null;default:0;comment:Sort"`
NodeGroupIds JSONInt64Slice `gorm:"type:json;comment:Node Group IDs (JSON array, multiple groups)"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (n *Node) TableName() string {
+77
View File
@@ -2,6 +2,7 @@ package subscribe
import (
"context"
"strings"
"github.com/perfect-panel/server/pkg/tool"
"github.com/redis/go-redis/v9"
@@ -19,6 +20,13 @@ type FilterParams struct {
Language string // Language
DefaultLanguage bool // Default Subscribe Language Data
Search string // Search Keywords
NodeGroupId *int64 // Node Group ID
}
type FilterByNodeGroupsParams struct {
Page int // Page Number
Size int // Page Size
NodeGroupIds []int64 // Node Group IDs (multiple)
}
func (p *FilterParams) Normalize() {
@@ -32,6 +40,7 @@ func (p *FilterParams) Normalize() {
type customSubscribeLogicModel interface {
FilterList(ctx context.Context, params *FilterParams) (int64, []*Subscribe, error)
FilterListByNodeGroups(ctx context.Context, params *FilterByNodeGroupsParams) (int64, []*Subscribe, error)
ClearCache(ctx context.Context, id ...int64) error
QuerySubscribeMinSortByIds(ctx context.Context, ids []int64) (int64, error)
}
@@ -102,6 +111,10 @@ func (m *customSubscribeModel) FilterList(ctx context.Context, params *FilterPar
if len(params.Tags) > 0 {
query = query.Scopes(InSet("node_tags", params.Tags))
}
if params.NodeGroupId != nil {
// Filter by node_group_ids using JSON_CONTAINS
query = query.Where("JSON_CONTAINS(node_group_ids, ?)", *params.NodeGroupId)
}
if lang != "" {
query = query.Where("language = ?", lang)
} else if params.DefaultLanguage {
@@ -154,3 +167,67 @@ func InSet(field string, values []string) func(db *gorm.DB) *gorm.DB {
return query
}
}
// FilterListByNodeGroups Filter subscribes by node groups
// Match if subscribe's node_group_id OR node_group_ids contains any of the provided node group IDs
func (m *customSubscribeModel) FilterListByNodeGroups(ctx context.Context, params *FilterByNodeGroupsParams) (int64, []*Subscribe, error) {
if params == nil {
params = &FilterByNodeGroupsParams{
Page: 1,
Size: 10,
}
}
if params.Page <= 0 {
params.Page = 1
}
if params.Size <= 0 {
params.Size = 10
}
var list []*Subscribe
var total int64
err := m.QueryNoCacheCtx(ctx, &list, func(conn *gorm.DB, v interface{}) error {
query := conn.Model(&Subscribe{})
// Filter by node groups: match if node_group_id or node_group_ids contains any of the provided IDs
if len(params.NodeGroupIds) > 0 {
var conditions []string
var args []interface{}
// Condition 1: node_group_id IN (...)
placeholders := make([]string, len(params.NodeGroupIds))
for i, id := range params.NodeGroupIds {
placeholders[i] = "?"
args = append(args, id)
}
conditions = append(conditions, "node_group_id IN ("+strings.Join(placeholders, ",")+")")
// Condition 2: JSON_CONTAINS(node_group_ids, id) for each id
for _, id := range params.NodeGroupIds {
conditions = append(conditions, "JSON_CONTAINS(node_group_ids, ?)")
args = append(args, id)
}
// Combine with OR: (node_group_id IN (...) OR JSON_CONTAINS(node_group_ids, id1) OR ...)
query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
}
// Count total
if err := query.Count(&total).Error; err != nil {
return err
}
// Find with pagination
return query.Order("sort ASC").
Limit(params.Size).
Offset((params.Page - 1) * params.Size).
Find(v).Error
})
if err != nil {
return 0, nil, err
}
return total, list, nil
}
+47
View File
@@ -1,11 +1,58 @@
package subscribe
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// JSONInt64Slice is a custom type for handling []int64 as JSON in database
type JSONInt64Slice []int64
// Scan implements sql.Scanner interface
func (j *JSONInt64Slice) Scan(value interface{}) error {
if value == nil {
*j = []int64{}
return nil
}
// Handle []byte
bytes, ok := value.([]byte)
if !ok {
// Try to handle string
str, ok := value.(string)
if !ok {
*j = []int64{}
return nil
}
bytes = []byte(str)
}
if len(bytes) == 0 {
*j = []int64{}
return nil
}
// Check if it's a JSON array
if bytes[0] != '[' {
// Not a JSON array, return empty slice
*j = []int64{}
return nil
}
return json.Unmarshal(bytes, j)
}
// Value implements driver.Valuer interface
func (j JSONInt64Slice) Value() (driver.Value, error) {
if len(j) == 0 {
return "[]", nil
}
return json.Marshal(j)
}
type Subscribe struct {
Id int64 `gorm:"primaryKey"`
Name string `gorm:"type:varchar(255);not null;default:'';comment:Subscribe Name"`
+18 -6
View File
@@ -29,6 +29,7 @@ type SubscribeDetails struct {
OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
Subscribe *subscribe.Subscribe `gorm:"foreignKey:SubscribeId;references:Id"`
NodeGroupId int64 `gorm:"index:idx_node_group_id;not null;default:0;comment:Node Group ID (single ID)"`
StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"`
ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"`
FinishedAt *time.Time `gorm:"default:NULL;comment:Finished Time"`
@@ -89,7 +90,7 @@ type customUserLogicModel interface {
FindOneSubscribeDetailsById(ctx context.Context, id int64) (*SubscribeDetails, error)
FindOneUserSubscribe(ctx context.Context, id int64) (*SubscribeDetails, error)
FindUsersSubscribeBySubscribeId(ctx context.Context, subscribeId int64) ([]*Subscribe, error)
UpdateUserSubscribeWithTraffic(ctx context.Context, id, download, upload int64, tx ...*gorm.DB) error
UpdateUserSubscribeWithTraffic(ctx context.Context, id, download, upload int64, isExpired bool, tx ...*gorm.DB) error
QueryResisterUserTotalByDate(ctx context.Context, date time.Time) (int64, error)
QueryResisterUserTotalByMonthly(ctx context.Context, date time.Time) (int64, error)
QueryResisterUserTotal(ctx context.Context) (int64, error)
@@ -276,7 +277,7 @@ func (m *customUserModel) BatchDeleteUser(ctx context.Context, ids []int64, tx .
}, m.batchGetCacheKeys(users...)...)
}
func (m *customUserModel) UpdateUserSubscribeWithTraffic(ctx context.Context, id, download, upload int64, tx ...*gorm.DB) error {
func (m *customUserModel) UpdateUserSubscribeWithTraffic(ctx context.Context, id, download, upload int64, isExpired bool, tx ...*gorm.DB) error {
sub, err := m.FindOneSubscribe(ctx, id)
if err != nil {
return err
@@ -293,10 +294,21 @@ func (m *customUserModel) UpdateUserSubscribeWithTraffic(ctx context.Context, id
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&Subscribe{}).Where("id = ?", id).Updates(map[string]interface{}{
"download": gorm.Expr("download + ?", download),
"upload": gorm.Expr("upload + ?", upload),
}).Error
// 根据订阅状态更新对应的流量字段
if isExpired {
// 过期期间,更新过期流量字段
return conn.Model(&Subscribe{}).Where("id = ?", id).Updates(map[string]interface{}{
"expired_download": gorm.Expr("expired_download + ?", download),
"expired_upload": gorm.Expr("expired_upload + ?", upload),
}).Error
} else {
// 正常期间,更新正常流量字段
return conn.Model(&Subscribe{}).Where("id = ?", id).Updates(map[string]interface{}{
"download": gorm.Expr("download + ?", download),
"upload": gorm.Expr("upload + ?", upload),
}).Error
}
})
}
+68 -17
View File
@@ -1,11 +1,58 @@
package user
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// JSONInt64Slice is a custom type for handling []int64 as JSON in database
type JSONInt64Slice []int64
// Scan implements sql.Scanner interface
func (j *JSONInt64Slice) Scan(value interface{}) error {
if value == nil {
*j = []int64{}
return nil
}
// Handle []byte
bytes, ok := value.([]byte)
if !ok {
// Try to handle string
str, ok := value.(string)
if !ok {
*j = []int64{}
return nil
}
bytes = []byte(str)
}
if len(bytes) == 0 {
*j = []int64{}
return nil
}
// Check if it's a JSON array
if bytes[0] != '[' {
// Not a JSON array, return empty slice
*j = []int64{}
return nil
}
return json.Unmarshal(bytes, j)
}
// Value implements driver.Valuer interface
func (j JSONInt64Slice) Value() (driver.Value, error) {
if len(j) == 0 {
return "[]", nil
}
return json.Marshal(j)
}
type User struct {
Id int64 `gorm:"primaryKey"`
Password string `gorm:"type:varchar(100);not null;comment:User Password"`
@@ -41,23 +88,27 @@ func (*User) TableName() string {
}
type Subscribe struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
User User `gorm:"foreignKey:UserId;references:Id"`
OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"`
ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"`
FinishedAt *time.Time `gorm:"default:NULL;comment:Finished Time"`
Traffic int64 `gorm:"default:0;comment:Traffic"`
Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"`
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired 4: Deducted 5: stopped"`
Note string `gorm:"type:varchar(500);default:'';comment:User note for subscription"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
User User `gorm:"foreignKey:UserId;references:Id"`
OrderId int64 `gorm:"index:idx_order_id;not null;comment:Order ID"`
SubscribeId int64 `gorm:"index:idx_subscribe_id;not null;comment:Subscription ID"`
NodeGroupId int64 `gorm:"index:idx_node_group_id;not null;default:0;comment:Node Group ID (single ID)"`
GroupLocked *bool `gorm:"type:tinyint(1);not null;default:0;comment:Group Locked"`
StartTime time.Time `gorm:"default:CURRENT_TIMESTAMP(3);not null;comment:Subscription Start Time"`
ExpireTime time.Time `gorm:"default:NULL;comment:Subscription Expire Time"`
FinishedAt *time.Time `gorm:"default:NULL;comment:Finished Time"`
Traffic int64 `gorm:"default:0;comment:Traffic"`
Download int64 `gorm:"default:0;comment:Download Traffic"`
Upload int64 `gorm:"default:0;comment:Upload Traffic"`
ExpiredDownload int64 `gorm:"default:0;comment:Expired period download traffic (bytes)"`
ExpiredUpload int64 `gorm:"default:0;comment:Expired period upload traffic (bytes)"`
Token string `gorm:"index:idx_token;unique;type:varchar(255);default:'';comment:Token"`
UUID string `gorm:"type:varchar(255);unique;index:idx_uuid;default:'';comment:UUID"`
Status uint8 `gorm:"type:tinyint(1);default:0;comment:Subscription Status: 0: Pending 1: Active 2: Finished 3: Expired 4: Deducted 5: stopped"`
Note string `gorm:"type:varchar(500);default:'';comment:User note for subscription"`
CreatedAt time.Time `gorm:"<-:create;comment:Creation Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (*Subscribe) TableName() string {