* fix(database): correct name entry for SingBox in initialization script

* fix(purchase): update gift amount deduction logic and handle zero-amount order status

* feat: add type and default fields to rule group requests and update related logic

* feat(rule): implement logic to set a default rule group during creation and update

* fix(rule): add type and default fields to rule group model and update related logic

* feat(proxy): enhance proxy group handling and sorting logic

* refactor(proxy): replace hardcoded group names with constants for better maintainability

* fix(proxy): update group selection logic to skip empty and default names

* feat(proxy): enhance proxy and group handling with new configuration options

* feat(surge): add Surge adapter support and enhance subscription URL handling

* feat(traffic): implement traffic reset logic for subscription cycles

* feat(auth): improve email and mobile config unmarshalling with default values

* fix(auth) upbind email not update

* fix(order) discount set default 1

* fix(order) discount set default 1

* fix: refactor surfboard proxy handling and enhance configuration template

* fix(renewal) discount set default 1

* feat(loon): add Loon configuration template and enhance proxy handling

* feat(subscription): update user subscription status based on expiration time

* fix(renewal): update subscription retrieval method to use token instead of order ID

* feat(order): enhance order processing logic with improved error handling and user subscription management

* fix(order): improve code quality and fix critical bugs in order processing logic

- Fix inconsistent logging calls across all order logic files
- Fix critical gift amount deduction logic bug in renewal process
- Fix variable shadowing errors in database transactions
- Add comprehensive Go-standard documentation comments
- Improve log prefix consistency for better debugging
- Remove redundant discount validation code

* fix(docker): add build argument for version in Docker image build process

* feat(version): add endpoint to retrieve application version information

* fix(auth): improve user authentication method logic and update user cache

* feat(user): add ordering functionality to user list retrieval

* fix(RevenueStatistics) fill list

* fix(UserStatistics) fill list

* fix(user): implement user cache clearing after auth method operations

* fix(auth): enhance OAuth login logic with improved request handling and user registration flow

* fix(user): implement sorting for authentication methods based on priority

* fix(user): correct ordering clause for user retrieval based on filter

* refactor(user): streamline cache management and enhance cache clearing logic

* feat(logs) set logs volume in develop

* fix(handler): implement browser interception to deny access for specific user agents

* fix(resetTraffic) reset daily server

* refactor(trojan): remove unused parameter and clean up logging in slice

* fix(middleware): add domain length check and improve user-agent handling

* fix(middleware): reorder domain processing and enhance user-agent handling

* fix(resetTraffic): update subscription reset logic to use expire_time for monthly and yearly checks

* fix(scheduler): update reset traffic task schedule to run daily at 00:30

* fix(traffic): enhance traffic reset logic for subscriptions and adjust status checks

* fix(activateOrder): update traffic reset logic to include reset day check

* feat(marketing): add batch email task management API and logic

* feat(application): implement CRUD operations for subscribe applications

* feat(types): add user agent limit and list to subscription configuration

* feat(application): update subscription application requests to include structured download links

* feat(application): add scheme field and download link handling to subscribe application

* feat(application): add endpoint to retrieve client information

* feat(application): move DownloadLink and SubscribeApplication types to types.api

* feat(application): add DownloadLink and SubscribeClient types, update client response structure

* feat(application): remove ProxyTemplate field from application API

* feat(application): implement adapter for client configuration and add preview template functionality

* feat(application): move DownloadLink type to types.api and remove from common.api

* feat(application): update PreviewSubscribeTemplate to return structured response

* feat(application): remove ProxyTemplate field from application API

* feat(application): enhance cache key generation for user list and server data

* feat(subscribe): add ClearCache method to manage subscription cache invalidation

* feat(payment): add Description field to PaymentMethodDetail response

* feat(subscribe): update next reset time calculation to use ExpireTime

* feat(purchase): include handling fee in total amount calculation

* feat(subscribe): add V2SubscribeHandler and logic for enhanced subscription management

* feat(subscribe): add output format configuration to subscription adapter

* feat(application): default data

---------

Co-authored-by: Chang lue Tsen <tension@ppanel.dev>
Co-authored-by: NoWay <Bob455668@hotmail.com>
This commit is contained in:
Leif Draven
2025-08-16 01:30:21 +09:00
committed by GitHub
parent c8de30f78c
commit 41d660bb9e
89 changed files with 4542 additions and 523 deletions
+3
View File
@@ -36,4 +36,7 @@ func RegisterHandlers(mux *asynq.ServeMux, serverCtx *svc.ServiceContext) {
// Schedule reset traffic
mux.Handle(types.SchedulerResetTraffic, traffic.NewResetTrafficLogic(serverCtx))
// ScheduledBatchSendEmail
mux.Handle(types.ScheduledBatchSendEmail, emailLogic.NewBatchEmailLogic(serverCtx))
}
+78
View File
@@ -0,0 +1,78 @@
package emailLogic
import (
"context"
"strconv"
"github.com/hibiken/asynq"
taskModel "github.com/perfect-panel/server/internal/model/task"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/email"
"github.com/perfect-panel/server/pkg/logger"
)
type BatchEmailLogic struct {
svcCtx *svc.ServiceContext
}
type ErrorInfo struct {
Error string `json:"error"`
Email string `json:"email"`
Time int64 `json:"time"`
}
func NewBatchEmailLogic(svcCtx *svc.ServiceContext) *BatchEmailLogic {
return &BatchEmailLogic{
svcCtx: svcCtx,
}
}
func (l *BatchEmailLogic) ProcessTask(ctx context.Context, task *asynq.Task) error {
// 解析任务负载
payload := task.Payload()
if len(payload) == 0 {
logger.Error("[BatchEmailLogic] ProcessTask failed: empty payload")
return asynq.SkipRetry
}
// 转换获取任务id
taskID, err := strconv.ParseInt(string(payload), 10, 64)
if err != nil {
logger.WithContext(ctx).Error("[BatchEmailLogic] ProcessTask failed: invalid task ID",
logger.Field("error", err.Error()),
logger.Field("payload", string(payload)),
)
return asynq.SkipRetry
}
tx := l.svcCtx.DB.WithContext(ctx)
var taskInfo taskModel.EmailTask
if err = tx.Model(&taskModel.EmailTask{}).Where("id = ?", taskID).First(&taskInfo).Error; err != nil {
logger.WithContext(ctx).Error("[BatchEmailLogic] ProcessTask failed",
logger.Field("error", err.Error()),
logger.Field("taskID", taskID),
)
return asynq.SkipRetry
}
if taskInfo.Status != 0 {
logger.WithContext(ctx).Info("[BatchEmailLogic] ProcessTask skipped: task already processed",
logger.Field("taskID", taskID),
logger.Field("status", taskInfo.Status),
)
return nil
}
sender, err := email.NewSender(l.svcCtx.Config.Email.Platform, l.svcCtx.Config.Email.PlatformConfig, l.svcCtx.Config.Site.SiteName)
if err != nil {
logger.WithContext(ctx).Error("[BatchEmailLogic] NewSender failed", logger.Field("error", err.Error()))
return nil
}
manager := email.NewWorkerManager(l.svcCtx.DB, sender)
if manager == nil {
logger.WithContext(ctx).Error("[BatchEmailLogic] ProcessTask failed: worker manager is nil")
return asynq.SkipRetry
}
// 添加或获取 Worker 实例
manager.AddWorker(taskID)
return nil
}
+9 -1
View File
@@ -490,14 +490,22 @@ func (l *ActivateOrderLogic) updateSubscriptionForRenewal(ctx context.Context, u
if userSub.ExpireTime.Before(now) {
userSub.ExpireTime = now
}
today := time.Now().Day()
resetDay := userSub.ExpireTime.Day()
// Reset traffic if enabled
if sub.RenewalReset != nil && *sub.RenewalReset {
if (sub.RenewalReset != nil && *sub.RenewalReset) || today == resetDay {
userSub.Download = 0
userSub.Upload = 0
}
if userSub.FinishedAt != nil {
if userSub.FinishedAt.Before(now) && today > resetDay {
// reset user traffic if finished at is before now
userSub.Download = 0
userSub.Upload = 0
}
userSub.FinishedAt = nil
}
+41 -31
View File
@@ -2,17 +2,19 @@ package traffic
import (
"context"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/subscribe"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/queue/types"
"github.com/hibiken/asynq"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
@@ -114,9 +116,16 @@ func (l *ResetTrafficLogic) ProcessTask(ctx context.Context, _ *asynq.Task) erro
}
}()
// Reset today's traffic data
err = l.svc.NodeCache.ResetTodayTrafficData(ctx)
if err != nil {
logger.Errorw("[ResetTodayTraffic] Failed to reset today traffic data",
logger.Field("error", err.Error()))
}
// Load last reset time from cache
var cache resetTrafficCache
err = l.svc.Redis.Get(ctx, cacheKey).Scan(&cache)
cacheData, err := l.svc.Redis.Get(ctx, cacheKey).Result()
if err != nil {
if !errors.Is(err, redis.Nil) {
logger.Errorw("[ResetTraffic] Failed to get cache", logger.Field("error", err.Error()))
@@ -127,7 +136,15 @@ func (l *ResetTrafficLogic) ProcessTask(ctx context.Context, _ *asynq.Task) erro
}
logger.Infow("[ResetTraffic] Using default cache value", logger.Field("lastResetTime", cache.LastResetTime))
} else {
logger.Infow("[ResetTraffic] Cache loaded successfully", logger.Field("lastResetTime", cache.LastResetTime))
// Parse JSON data
if err := json.Unmarshal([]byte(cacheData), &cache); err != nil {
logger.Errorw("[ResetTraffic] Failed to unmarshal cache", logger.Field("error", err.Error()))
cache = resetTrafficCache{
LastResetTime: time.Now().Add(-10 * time.Minute),
}
} else {
logger.Infow("[ResetTraffic] Cache loaded successfully", logger.Field("lastResetTime", cache.LastResetTime))
}
}
// Execute reset operations in order: yearly -> monthly (1st) -> monthly (cycle)
@@ -153,12 +170,17 @@ func (l *ResetTrafficLogic) ProcessTask(ctx context.Context, _ *asynq.Task) erro
updatedCache := resetTrafficCache{
LastResetTime: startTime,
}
cacheErr := l.svc.Redis.Set(ctx, cacheKey, updatedCache, 0).Err()
if cacheErr != nil {
logger.Errorw("[ResetTraffic] Failed to update cache", logger.Field("error", cacheErr.Error()))
// Don't return error here as the main task completed successfully
cacheDataBytes, marshalErr := json.Marshal(updatedCache)
if marshalErr != nil {
logger.Errorw("[ResetTraffic] Failed to marshal cache", logger.Field("error", marshalErr.Error()))
} else {
logger.Infow("[ResetTraffic] Cache updated successfully", logger.Field("newLastResetTime", startTime))
cacheErr := l.svc.Redis.Set(ctx, cacheKey, cacheDataBytes, 0).Err()
if cacheErr != nil {
logger.Errorw("[ResetTraffic] Failed to update cache", logger.Field("error", cacheErr.Error()))
// Don't return error here as the main task completed successfully
} else {
logger.Infow("[ResetTraffic] Cache updated successfully", logger.Field("newLastResetTime", startTime))
}
}
return nil
@@ -187,22 +209,19 @@ func (l *ResetTrafficLogic) resetMonth(ctx context.Context) error {
var monthlyResetUsers []int64
// Check if today is the last day of current month
nextMonth := now.AddDate(0, 1, 0)
isLastDayOfMonth := nextMonth.Month() != now.Month()
isLastDayOfMonth := now.AddDate(0, 0, 1).Month() != now.Month()
query := db.Model(&user.Subscribe{}).Select("`id`").
Where("`subscribe_id` IN ?", resetMonthSubIds).
Where("`status` = ?", 1). // Only active subscriptions
Where("PERIOD_DIFF(DATE_FORMAT(CURDATE(), '%Y%m'), DATE_FORMAT(start_time, '%Y%m')) > 0"). // At least one month passed
Where("MOD(PERIOD_DIFF(DATE_FORMAT(CURDATE(), '%Y%m'), DATE_FORMAT(start_time, '%Y%m')), 1) = 0"). // Monthly cycle
Where("DATE(start_time) < CURDATE()") // Only reset subscriptions that have started
Where("`status` IN ?", []int64{1, 2}). // Only active subscriptions
Where("TIMESTAMPDIFF(MONTH, CURDATE(),DATE(expire_time)) >= 1") // At least 1 month passed
if isLastDayOfMonth {
// Last day of month: handle subscription start dates >= today
query = query.Where("DAY(start_time) >= ?", now.Day())
query = query.Where("DAY(`expire_time`) >= ?", now.Day())
} else {
// Normal case: exact day match
query = query.Where("DAY(start_time) = ?", now.Day())
query = query.Where("DAY(`expire_time`) = ?", now.Day())
}
err = query.Find(&monthlyResetUsers).Error
@@ -279,7 +298,7 @@ func (l *ResetTrafficLogic) reset1st(ctx context.Context, cache resetTrafficCach
var users1stReset []int64
err = db.Model(&user.Subscribe{}).Select("`id`").
Where("`subscribe_id` IN ?", reset1stSubIds).
Where("`status` = ?", 1). // Only active subscriptions
Where("`status` IN ?", []int64{1, 2}). // Only active subscriptions
Find(&users1stReset).Error
if err != nil {
logger.Errorw("[ResetTraffic] Failed to query 1st reset users", logger.Field("error", err.Error()))
@@ -341,29 +360,20 @@ func (l *ResetTrafficLogic) resetYear(ctx context.Context) error {
// Query users for yearly reset based on subscription start date anniversary
var usersYearReset []int64
// Check if today is the last day of current month
nextMonth := now.AddDate(0, 1, 0)
isLastDayOfMonth := nextMonth.Month() != now.Month()
// Check if today is February 28th (handle leap year case)
isLeapYearCase := now.Month() == 2 && now.Day() == 28
query := db.Model(&user.Subscribe{}).Select("`id`").
Where("`subscribe_id` IN ?", resetYearSubIds).
Where("MONTH(start_time) = ?", now.Month()). // Same month
Where("`status` = ?", 1). // Only active subscriptions
Where("TIMESTAMPDIFF(YEAR, DATE(start_time), CURDATE()) >= 1"). // At least 1 year passed
Where("DATE(start_time) < CURDATE()") // Only reset subscriptions that have started
Where("MONTH(expire_time) = ?", now.Month()). // Same month
Where("`status` IN ?", []int64{1, 2}). // Only active subscriptions
Where("TIMESTAMPDIFF(YEAR, CURDATE(),DATE(expire_time)) >= 1") // At least 1 year passed
if isLeapYearCase {
// February 28th: handle both Feb 28 and Feb 29 subscriptions
query = query.Where("DAY(start_time) IN (28, 29)")
} else if isLastDayOfMonth {
// Last day of month: handle subscription start dates >= today
query = query.Where("DAY(start_time) >= ?", now.Day())
query = query.Where("DAY(expire_time) IN (28, 29)")
} else {
// Normal case: exact day match
query = query.Where("DAY(start_time) = ?", now.Day())
query = query.Where("DAY(expire_time) = ?", now.Day())
}
err = query.Find(&usersYearReset).Error
+3
View File
@@ -3,10 +3,13 @@ package types
const (
// ForthwithSendEmail forthwith send email
ForthwithSendEmail = "forthwith:email:send"
// ScheduledBatchSendEmail scheduled batch send email
ScheduledBatchSendEmail = "scheduled:email:batch"
)
type (
SendEmailPayload struct {
Type string `json:"type"`
Email string `json:"to"`
Subject string `json:"subject"`
Content string `json:"content"`