feat: enhance plan validation, traffic system and email verification

- feat: add plan price validation
- feat: make traffic packages stackable
- feat: add commission and invite info to admin order details
- feat: apply email whitelist to verification code API
- fix: subscription link copy compatibility for non-HTTPS
- fix: resolve route editing 500 error in certain cases
- refactor: restructure traffic reset logic
This commit is contained in:
xboard
2025-06-22 01:18:38 +08:00
parent 7bab761db6
commit 4fe2f35183
34 changed files with 2176 additions and 539 deletions
+178 -149
View File
@@ -2,175 +2,204 @@
namespace App\Console\Commands;
use App\Models\Plan;
use App\Services\TrafficResetService;
use App\Utils\Helper;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ResetTraffic extends Command
{
/**
* @var Builder
* The name and signature of the console command.
*/
protected $builder;
protected $signature = 'reset:traffic {--batch-size=100 : 分批处理的批次大小} {--dry-run : 预演模式,不实际执行重置} {--max-time=300 : 最大执行时间(秒)}';
/**
* @var string
* The console command description.
*/
protected $signature = 'reset:traffic';
protected $description = '流量重置 - 分批处理所有需要重置的用户';
/**
* @var string
* 流量重置服务
*/
protected $description = '流量清空';
private TrafficResetService $trafficResetService;
public function __construct()
/**
* Create a new command instance.
*/
public function __construct(TrafficResetService $trafficResetService)
{
parent::__construct();
$this->builder = User::where('expired_at', '!=', NULL)
->where('expired_at', '>', time());
$this->trafficResetService = $trafficResetService;
}
/**
* Execute the console command.
*/
public function handle(): int
{
$batchSize = (int) $this->option('batch-size');
$dryRun = $this->option('dry-run');
$maxTime = (int) $this->option('max-time');
$this->info('🚀 开始执行流量重置任务...');
$this->info("批次大小: {$batchSize} 用户/批");
$this->info("最大执行时间: {$maxTime}");
if ($dryRun) {
$this->warn('⚠️ 预演模式 - 不会实际执行重置操作');
}
/**
* 执行流量重置命令
*/
public function handle()
{
ini_set('memory_limit', -1);
// 设置最大执行时间
set_time_limit($maxTime);
// 按重置方法分组查询所有套餐
$resetMethods = Plan::select(
DB::raw("GROUP_CONCAT(`id`) as plan_ids"),
DB::raw("reset_traffic_method as method")
)
->groupBy('reset_traffic_method')
->get()
->toArray();
$startTime = microtime(true);
// 使用闭包直接引用方法
$resetHandlers = [
Plan::RESET_TRAFFIC_FIRST_DAY_MONTH => fn($builder) => $this->resetByMonthFirstDay($builder),
Plan::RESET_TRAFFIC_MONTHLY => fn($builder) => $this->resetByExpireDay($builder),
Plan::RESET_TRAFFIC_NEVER => null,
Plan::RESET_TRAFFIC_FIRST_DAY_YEAR => fn($builder) => $this->resetByYearFirstDay($builder),
Plan::RESET_TRAFFIC_YEARLY => fn($builder) => $this->resetByExpireYear($builder),
try {
if ($dryRun) {
$result = $this->performDryRun($batchSize);
} else {
// 使用游标分页和进度回调
$result = $this->trafficResetService->batchCheckReset($batchSize, function ($progress) {
$this->info("📦 处理第 {$progress['batch_number']} 批 ({$progress['batch_size']} 用户) - 已处理: {$progress['total_processed']}");
});
}
$this->displayResults($result, $dryRun);
return self::SUCCESS;
} catch (\Exception $e) {
$this->error("❌ 任务执行失败: {$e->getMessage()}");
Log::error('流量重置命令执行失败', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'options' => [
'batch_size' => $batchSize,
'dry_run' => $dryRun,
'max_time' => $maxTime,
],
]);
return self::FAILURE;
}
}
/**
* 显示执行结果
*/
private function displayResults(array $result, bool $dryRun): void
{
$this->info("✅ 任务完成!");
$this->line('');
if ($dryRun) {
$this->info("📊 预演结果统计:");
$this->info("📋 待处理用户数: {$result['total_found']}");
$this->info("⏱️ 预计处理时间: ~{$result['estimated_duration']}");
$this->info("🗂️ 预计批次数: {$result['estimated_batches']}");
} else {
$this->info("📊 执行结果统计:");
$this->info("👥 处理用户总数: {$result['total_processed']}");
$this->info("🔄 重置用户数量: {$result['total_reset']}");
$this->info("📦 处理批次数量: {$result['total_batches']}");
$this->info("⏱️ 总执行时间: {$result['duration']}");
if ($result['error_count'] > 0) {
$this->warn("⚠️ 错误数量: {$result['error_count']}");
$this->warn("详细错误信息请查看日志");
} else {
$this->info("✨ 无错误发生");
}
// 显示性能指标
if ($result['total_processed'] > 0) {
$avgTime = round($result['duration'] / $result['total_processed'], 4);
$this->info("⚡ 平均处理速度: {$avgTime} 秒/用户");
}
}
}
/**
* 执行预演模式
*/
private function performDryRun(int $batchSize): array
{
$this->info("🔍 扫描需要重置的用户...");
$totalUsers = \App\Models\User::where('next_reset_at', '<=', time())
->whereNotNull('next_reset_at')
->where(function ($query) {
$query->where('expired_at', '>', time())
->orWhereNull('expired_at');
})
->where('banned', 0)
->whereNotNull('plan_id')
->count();
if ($totalUsers === 0) {
$this->info("😴 当前没有需要重置的用户");
return [
'total_found' => 0,
'estimated_duration' => 0,
'estimated_batches' => 0,
];
}
$this->info("找到 {$totalUsers} 个需要重置的用户");
// 预计批次数
$estimatedBatches = ceil($totalUsers / $batchSize);
// 预计执行时间(基于经验值:每个用户平均0.1秒)
$estimatedDuration = round($totalUsers * 0.1, 1);
$this->info("将分 {$estimatedBatches} 个批次处理(每批 {$batchSize} 用户)");
// 显示前几个用户的详情作为示例
if ($this->option('verbose') || $totalUsers <= 20) {
$sampleUsers = \App\Models\User::where('next_reset_at', '<=', time())
->whereNotNull('next_reset_at')
->where(function ($query) {
$query->where('expired_at', '>', time())
->orWhereNull('expired_at');
})
->where('banned', 0)
->whereNotNull('plan_id')
->with('plan')
->limit(min(20, $totalUsers))
->get();
$table = [];
foreach ($sampleUsers as $user) {
$table[] = [
'ID' => $user->id,
'邮箱' => substr($user->email, 0, 20) . (strlen($user->email) > 20 ? '...' : ''),
'套餐' => $user->plan->name ?? 'N/A',
'下次重置' => $user->next_reset_at->format('m-d H:i'),
'当前流量' => Helper::trafficConvert(($user->u ?? 0) + ($user->d ?? 0)),
'重置次数' => $user->reset_count,
];
}
// 处理每种重置方法
foreach ($resetMethods as $resetMethod) {
$planIds = explode(',', $resetMethod['plan_ids']);
// 获取重置方法
$method = $resetMethod['method'];
if ($method === NULL) {
$method = (int) admin_setting('reset_traffic_method', 0);
}
// 跳过不重置的方法
if ($method === 2) {
continue;
}
// 获取该方法的处理器
$handler = $resetHandlers[$method] ?? null;
if (!$handler) {
continue;
}
// 创建查询构建器并执行重置
$userQuery = (clone $this->builder)->whereIn('plan_id', $planIds);
$handler($userQuery);
}
if (!empty($table)) {
$this->info("📋 示例用户列表" . ($totalUsers > 20 ? "(显示前20个):" : ""));
$this->table([
'ID',
'邮箱',
'套餐',
'下次重置',
'当前流量',
'重置次数'
], $table);
}
}
/**
* 按用户年度到期日重置流量
*/
private function resetByExpireYear(Builder $builder): void
{
$today = date('m-d');
$this->resetUsersByDateCondition($builder, function ($user) use ($today) {
return date('m-d', $user->expired_at) === $today;
});
}
/**
* 按新年第一天重置流量
*/
private function resetByYearFirstDay(Builder $builder): void
{
$isNewYear = date('md') === '0101';
if (!$isNewYear) {
return;
}
$this->resetAllUsers($builder);
}
/**
* 按月初第一天重置流量
*/
private function resetByMonthFirstDay(Builder $builder): void
{
$isFirstDayOfMonth = date('d') === '01';
if (!$isFirstDayOfMonth) {
return;
}
$this->resetAllUsers($builder);
}
/**
* 按用户到期日重置流量
*/
private function resetByExpireDay(Builder $builder): void
{
$today = date('d');
$lastDay = date('d', strtotime('last day of +0 months'));
$this->resetUsersByDateCondition($builder, function ($user) use ($today, $lastDay) {
$expireDay = date('d', $user->expired_at);
return $expireDay === $today || ($today === $lastDay && $expireDay >= $today);
});
}
/**
* 重置所有符合条件的用户流量
*/
private function resetAllUsers(Builder $builder): void
{
$this->resetUsersByDateCondition($builder, function () {
return true;
});
}
/**
* 根据日期条件重置用户流量
* @param Builder $builder 用户查询构建器
* @param callable $condition 日期条件回调
*/
private function resetUsersByDateCondition(Builder $builder, callable $condition): void
{
/** @var \App\Models\User[] $users */
$users = $builder->with('plan')->get();
$usersToUpdate = [];
foreach ($users as $user) {
if ($condition($user)) {
$usersToUpdate[] = [
'id' => $user->id,
'transfer_enable' => $user->plan->transfer_enable
];
}
}
foreach ($usersToUpdate as $userData) {
User::where('id', $userData['id'])->update([
'transfer_enable' => (intval($userData['transfer_enable']) * 1073741824),
'u' => 0,
'd' => 0
]);
}
}
}
return [
'total_found' => $totalUsers,
'estimated_duration' => $estimatedDuration,
'estimated_batches' => $estimatedBatches,
];
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ class Kernel extends ConsoleKernel
$schedule->command('check:commission')->everyMinute()->onOneServer();
$schedule->command('check:ticket')->everyMinute()->onOneServer();
// reset
$schedule->command('reset:traffic')->daily()->onOneServer();
$schedule->command('reset:traffic')->everyMinute()->onOneServer();
$schedule->command('reset:log')->daily()->onOneServer();
// send
$schedule->command('send:remindMail', ['--force'])->dailyAt('11:30')->onOneServer();
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\V1\Guest;
use App\Http\Controllers\Controller;
use App\Utils\Dict;
use App\Utils\Helper;
use Illuminate\Support\Facades\Http;
class CommController extends Controller
@@ -12,12 +13,12 @@ class CommController extends Controller
{
$data = [
'tos_url' => admin_setting('tos_url'),
'is_email_verify' => (int)admin_setting('email_verify', 0) ? 1 : 0,
'is_invite_force' => (int)admin_setting('invite_force', 0) ? 1 : 0,
'email_whitelist_suffix' => (int)admin_setting('email_whitelist_enable', 0)
? $this->getEmailSuffix()
'is_email_verify' => (int) admin_setting('email_verify', 0) ? 1 : 0,
'is_invite_force' => (int) admin_setting('invite_force', 0) ? 1 : 0,
'email_whitelist_suffix' => (int) admin_setting('email_whitelist_enable', 0)
? Helper::getEmailSuffix()
: 0,
'is_recaptcha' => (int)admin_setting('recaptcha_enable', 0) ? 1 : 0,
'is_recaptcha' => (int) admin_setting('recaptcha_enable', 0) ? 1 : 0,
'recaptcha_site_key' => admin_setting('recaptcha_site_key'),
'app_description' => admin_setting('app_description'),
'app_url' => admin_setting('app_url'),
@@ -25,13 +26,4 @@ class CommController extends Controller
];
return $this->success($data);
}
private function getEmailSuffix()
{
$suffix = admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT);
if (!is_array($suffix)) {
return preg_split('/,/', $suffix);
}
return $suffix;
}
}
@@ -2,13 +2,13 @@
namespace App\Http\Controllers\V1\Passport;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Passport\CommSendEmailVerify;
use App\Jobs\SendEmailJob;
use App\Models\InviteCode;
use App\Models\User;
use App\Utils\CacheKey;
use App\Utils\Dict;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use ReCaptcha\ReCaptcha;
@@ -25,7 +25,22 @@ class CommController extends Controller
return $this->fail([400, __('Invalid code is incorrect')]);
}
}
$email = $request->input('email');
// 检查白名单后缀限制
if ((int) admin_setting('email_whitelist_enable', 0)) {
$isRegisteredEmail = User::where('email', $email)->exists();
if (!$isRegisteredEmail) {
$allowedSuffixes = Helper::getEmailSuffix();
$emailSuffix = substr(strrchr($email, '@'), 1);
if (!in_array($emailSuffix, $allowedSuffixes)) {
return $this->fail([400, __('Email suffix is not in whitelist')]);
}
}
}
if (Cache::get(CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP', $email))) {
return $this->fail([400, __('Email verification code has been sent, please request again later')]);
}
@@ -2,7 +2,6 @@
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\UserChangePassword;
use App\Http\Requests\User\UserTransfer;
@@ -15,7 +14,6 @@ use App\Services\AuthService;
use App\Services\UserService;
use App\Utils\CacheKey;
use App\Utils\Helper;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
@@ -22,7 +22,7 @@ class OrderController extends Controller
public function detail(Request $request)
{
$order = Order::with(['user', 'plan', 'commission_log'])->find($request->input('id'));
$order = Order::with(['user', 'plan', 'commission_log', 'invite_user'])->find($request->input('id'));
if (!$order)
return $this->fail([400202, '订单不存在']);
if ($order->surplus_order_ids) {
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\PlanSave;
use App\Models\Order;
use App\Models\Plan;
use App\Models\User;
@@ -32,27 +33,17 @@ class PlanController extends Controller
return $this->success($plans);
}
public function save(Request $request)
public function save(PlanSave $request)
{
$params = $request->validate([
'id' => 'nullable|integer',
'name' => 'required|string',
'content' => 'nullable|string',
'reset_traffic_method' => 'integer|nullable',
'transfer_enable' => 'integer|required',
'prices' => 'array|nullable',
'group_id' => 'integer|nullable',
'speed_limit' => 'integer|nullable',
'device_limit' => 'integer|nullable',
'capacity_limit' => 'integer|nullable',
]);
$params = $request->validated();
if ($request->input('id')) {
$plan = Plan::find($request->input('id'));
if (!$plan) {
return $this->fail([400202, '该订阅不存在']);
}
DB::beginTransaction();
// update user group id and transfer
try {
if ($request->input('force_update')) {
User::where('plan_id', $plan->id)->update([
@@ -6,18 +6,13 @@ use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\ServerRoute;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class RouteController extends Controller
{
public function fetch(Request $request)
{
$routes = ServerRoute::get();
// TODO: remove on 1.8.0
foreach ($routes as $k => $route) {
$array = json_decode($route->match, true);
if (is_array($array)) $routes[$k]['match'] = $array;
}
// TODO: remove on 1.8.0
return [
'data' => $routes
];
@@ -38,15 +33,13 @@ class RouteController extends Controller
]);
$params['match'] = array_filter($params['match']);
// TODO: remove on 1.8.0
$params['match'] = json_encode($params['match']);
// TODO: remove on 1.8.0
if ($request->input('id')) {
try {
$route = ServerRoute::find($request->input('id'));
$route->update($params);
return $this->success(true);
} catch (\Exception $e) {
\Log::error($e);
Log::error($e);
return $this->fail([500,'保存失败']);
}
}
@@ -54,7 +47,7 @@ class RouteController extends Controller
ServerRoute::create($params);
return $this->success(true);
}catch(\Exception $e){
\Log::error($e);
Log::error($e);
return $this->fail([500,'创建失败']);
}
}
@@ -0,0 +1,234 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\TrafficResetLog;
use App\Services\TrafficResetService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
/**
* 流量重置管理控制器
*/
class TrafficResetController extends Controller
{
private TrafficResetService $trafficResetService;
public function __construct(TrafficResetService $trafficResetService)
{
$this->trafficResetService = $trafficResetService;
}
/**
* 获取流量重置日志列表
*/
public function logs(Request $request): JsonResponse
{
$request->validate([
'user_id' => 'nullable|integer',
'user_email' => 'nullable|string',
'reset_type' => 'nullable|string|in:' . implode(',', array_keys(TrafficResetLog::getResetTypeNames())),
'trigger_source' => 'nullable|string|in:' . implode(',', array_keys(TrafficResetLog::getSourceNames())),
'start_date' => 'nullable|date',
'end_date' => 'nullable|date|after_or_equal:start_date',
'per_page' => 'nullable|integer|min:1|max:10000',
'page' => 'nullable|integer|min:1',
]);
$query = TrafficResetLog::with(['user:id,email'])
->orderBy('reset_time', 'desc');
// 筛选条件
if ($request->filled('user_id')) {
$query->where('user_id', $request->user_id);
}
if ($request->filled('user_email')) {
$query->whereHas('user', function ($query) use ($request) {
$query->where('email', 'like', '%' . $request->user_email . '%');
});
}
if ($request->filled('reset_type')) {
$query->where('reset_type', $request->reset_type);
}
if ($request->filled('trigger_source')) {
$query->where('trigger_source', $request->trigger_source);
}
if ($request->filled('start_date')) {
$query->where('reset_time', '>=', $request->start_date);
}
if ($request->filled('end_date')) {
$query->where('reset_time', '<=', $request->end_date . ' 23:59:59');
}
$perPage = $request->get('per_page', 20);
$logs = $query->paginate($perPage);
// 格式化数据
$logs->getCollection()->transform(function ($log) {
return [
'id' => $log->id,
'user_id' => $log->user_id,
'user_email' => $log->user->email ?? 'N/A',
'reset_type' => $log->reset_type,
'reset_type_name' => $log->getResetTypeName(),
'reset_time' => $log->reset_time,
'old_traffic' => [
'upload' => $log->old_upload,
'download' => $log->old_download,
'total' => $log->old_total,
'formatted' => $log->formatTraffic($log->old_total),
],
'new_traffic' => [
'upload' => $log->new_upload,
'download' => $log->new_download,
'total' => $log->new_total,
'formatted' => $log->formatTraffic($log->new_total),
],
'trigger_source' => $log->trigger_source,
'trigger_source_name' => $log->getSourceName(),
'metadata' => $log->metadata,
'created_at' => $log->created_at,
];
});
return response()->json([
'data' => $logs->items(),
'pagination' => [
'current_page' => $logs->currentPage(),
'last_page' => $logs->lastPage(),
'per_page' => $logs->perPage(),
'total' => $logs->total(),
],
]);
}
/**
* 获取流量重置统计信息
*/
public function stats(Request $request): JsonResponse
{
$request->validate([
'days' => 'nullable|integer|min:1|max:365',
]);
$days = $request->get('days', 30);
$startDate = now()->subDays($days)->startOfDay();
$stats = [
'total_resets' => TrafficResetLog::where('reset_time', '>=', $startDate)->count(),
'auto_resets' => TrafficResetLog::where('reset_time', '>=', $startDate)
->where('trigger_source', TrafficResetLog::SOURCE_AUTO)
->count(),
'manual_resets' => TrafficResetLog::where('reset_time', '>=', $startDate)
->where('trigger_source', TrafficResetLog::SOURCE_MANUAL)
->count(),
'cron_resets' => TrafficResetLog::where('reset_time', '>=', $startDate)
->where('trigger_source', TrafficResetLog::SOURCE_CRON)
->count(),
];
return response()->json([
'data' => $stats
]);
}
/**
* 手动重置用户流量
*/
public function resetUser(Request $request): JsonResponse
{
$request->validate([
'user_id' => 'required|integer|exists:v2_user,id',
'reason' => 'nullable|string|max:255',
]);
$user = User::find($request->user_id);
if (!$this->trafficResetService->canReset($user)) {
return response()->json([
'message' => __('traffic_reset.user_cannot_reset')
], 400);
}
$metadata = [];
if ($request->filled('reason')) {
$metadata['reason'] = $request->reason;
$metadata['admin_id'] = auth()->user()?->id;
}
$success = $this->trafficResetService->manualReset($user, $metadata);
if (!$success) {
return response()->json([
'message' => __('traffic_reset.reset_failed')
], 500);
}
return response()->json([
'message' => __('traffic_reset.reset_success'),
'data' => [
'user_id' => $user->id,
'email' => $user->email,
'reset_time' => now(),
'next_reset_at' => $user->fresh()->next_reset_at,
]
]);
}
/**
* 获取用户重置历史
*/
public function userHistory(Request $request, int $userId): JsonResponse
{
$request->validate([
'limit' => 'nullable|integer|min:1|max:50',
]);
$user = User::findOrFail($userId);
$limit = $request->get('limit', 10);
$history = $this->trafficResetService->getUserResetHistory($user, $limit);
$data = $history->map(function ($log) {
return [
'id' => $log->id,
'reset_type' => $log->reset_type,
'reset_type_name' => $log->getResetTypeName(),
'reset_time' => $log->reset_time,
'old_traffic' => [
'upload' => $log->old_upload,
'download' => $log->old_download,
'total' => $log->old_total,
'formatted' => $log->formatTraffic($log->old_total),
],
'trigger_source' => $log->trigger_source,
'trigger_source_name' => $log->getSourceName(),
'metadata' => $log->metadata,
];
});
return response()->json([
"data" => [
'user' => [
'id' => $user->id,
'email' => $user->email,
'reset_count' => $user->reset_count,
'last_reset_at' => $user->last_reset_at,
'next_reset_at' => $user->next_reset_at,
],
'history' => $data,
]
]);
}
}
+134 -36
View File
@@ -2,56 +2,154 @@
namespace App\Http\Requests\Admin;
use App\Models\Plan;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class PlanSave extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
* Determine if the user is authorized to make this request.
*/
public function rules()
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'name' => 'required',
'content' => '',
'group_id' => 'required',
'transfer_enable' => 'required',
'month_price' => 'nullable|integer',
'quarter_price' => 'nullable|integer',
'half_year_price' => 'nullable|integer',
'year_price' => 'nullable|integer',
'two_year_price' => 'nullable|integer',
'three_year_price' => 'nullable|integer',
'onetime_price' => 'nullable|integer',
'reset_price' => 'nullable|integer',
'reset_traffic_method' => 'nullable|integer|in:0,1,2,3,4',
'capacity_limit' => 'nullable|integer',
'speed_limit' => 'nullable|integer'
'id' => 'nullable|integer',
'name' => 'required|string|max:255',
'content' => 'nullable|string',
'reset_traffic_method' => 'integer|nullable',
'transfer_enable' => 'integer|required|min:1',
'prices' => 'nullable|array',
'prices.*' => 'nullable|numeric|min:0',
'group_id' => 'integer|nullable',
'speed_limit' => 'integer|nullable|min:0',
'device_limit' => 'integer|nullable|min:0',
'capacity_limit' => 'integer|nullable|min:0',
];
}
public function messages()
/**
* Configure the validator instance.
*/
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator) {
$this->validatePrices($validator);
});
}
/**
* 验证价格配置
*/
protected function validatePrices(Validator $validator): void
{
$prices = $this->input('prices', []);
if (empty($prices)) {
return;
}
// 获取所有有效的周期
$validPeriods = array_keys(Plan::getAvailablePeriods());
foreach ($prices as $period => $price) {
// 验证周期是否有效
if (!in_array($period, $validPeriods)) {
$validator->errors()->add(
"prices.{$period}",
"不支持的订阅周期: {$period}"
);
continue;
}
// 价格可以为 null、空字符串或大于 0 的数字
if ($price !== null && $price !== '') {
// 转换为数字进行验证
$numericPrice = is_numeric($price) ? (float) $price : null;
if ($numericPrice === null) {
$validator->errors()->add(
"prices.{$period}",
"价格必须是数字格式"
);
} elseif ($numericPrice <= 0) {
$validator->errors()->add(
"prices.{$period}",
"价格必须大于 0(如不需要此周期请留空或设为 null)"
);
}
}
}
}
/**
* 处理验证后的数据
*/
protected function passedValidation(): void
{
// 清理和格式化价格数据
$prices = $this->input('prices', []);
$cleanedPrices = [];
foreach ($prices as $period => $price) {
// 只保留有效的正数价格
if ($price !== null && $price !== '' && is_numeric($price)) {
$numericPrice = (float) $price;
if ($numericPrice > 0) {
// 转换为浮点数并保留两位小数
$cleanedPrices[$period] = round($numericPrice, 2);
}
}
}
// 更新请求中的价格数据
$this->merge(['prices' => $cleanedPrices]);
}
/**
* Get custom error messages for validator errors.
*/
public function messages(): array
{
return [
'name.required' => '套餐名称不能为空',
'type.required' => '套餐类型不能为空',
'type.in' => '套餐类型格式有误',
'group_id.required' => '权限组不能为空',
'transfer_enable.required' => '流量不能为空',
'month_price.integer' => '月付金额格式误',
'quarter_price.integer' => '季付金额格式有误',
'half_year_price.integer' => '半年付金额格式有误',
'year_price.integer' => '年付金额格式有误',
'two_year_price.integer' => '两年付金额格式有误',
'three_year_price.integer' => '三年付金额格式有误',
'onetime_price.integer' => '一次性金额有误',
'reset_price.integer' => '流量重置包金额有误',
'reset_traffic_method.integer' => '流量重置方式格式有误',
'reset_traffic_method.in' => '流量重置方式格式有误',
'capacity_limit.integer' => '容纳用户量限制格式有误',
'speed_limit.integer' => '限速格式有误'
'name.max' => '套餐名称不能超过 255 个字符',
'transfer_enable.required' => '流量配额不能为空',
'transfer_enable.integer' => '流量配额必须是整数',
'transfer_enable.min' => '流量配额必须大于 0',
'prices.array' => '价格配置格式误',
'prices.*.numeric' => '价格必须是数字',
'prices.*.min' => '价格不能为负数',
'group_id.integer' => '权限组ID必须是整数',
'speed_limit.integer' => '速度限制必须是整数',
'speed_limit.min' => '速度限制不能为负数',
'device_limit.integer' => '设备限制必须是整数',
'device_limit.min' => '设备限制不能为负数',
'capacity_limit.integer' => '容量限制必须是整数',
'capacity_limit.min' => '容量限制不能为负数',
];
}
/**
* Handle a failed validation attempt.
*/
protected function failedValidation(Validator $validator): void
{
throw new HttpResponseException(
response()->json([
'data' => false,
'message' => $validator->errors()->first(),
'errors' => $validator->errors()->toArray()
], 422)
);
}
}
+11
View File
@@ -16,6 +16,7 @@ use App\Http\Controllers\V2\Admin\KnowledgeController;
use App\Http\Controllers\V2\Admin\PaymentController;
use App\Http\Controllers\V2\Admin\SystemController;
use App\Http\Controllers\V2\Admin\ThemeController;
use App\Http\Controllers\V2\Admin\TrafficResetController;
use Illuminate\Contracts\Routing\Registrar;
class AdminRoute
@@ -229,6 +230,16 @@ class AdminRoute
$router->get('config', [\App\Http\Controllers\V2\Admin\PluginController::class, 'getConfig']);
$router->post('config', [\App\Http\Controllers\V2\Admin\PluginController::class, 'updateConfig']);
});
// 流量重置管理
$router->group([
'prefix' => 'traffic-reset'
], function ($router) {
$router->get('logs', [TrafficResetController::class, 'logs']);
$router->get('stats', [TrafficResetController::class, 'stats']);
$router->get('user/{userId}/history', [TrafficResetController::class, 'userHistory']);
$router->post('reset-user', [TrafficResetController::class, 'resetUser']);
});
});
}
+8
View File
@@ -88,6 +88,14 @@ class Order extends Model
return $this->belongsTo(User::class, 'user_id', 'id');
}
/**
* 获取邀请人
*/
public function invite_user(): BelongsTo
{
return $this->belongsTo(User::class, 'invite_user_id', 'id');
}
/**
* 获取与订单关联的套餐
*/
-66
View File
@@ -115,72 +115,6 @@ class Plan extends Model
];
}
/**
* 获取下一次流量重置时间
*
* @param Carbon|null $from 计算起始时间,默认为当前时间
* @return Carbon|null 下次重置时间,如果不重置则返回null
*/
public function getNextResetTime(?Carbon $from = null): ?Carbon
{
$from = $from ?? Carbon::now();
switch ($this->reset_traffic_method) {
case self::RESET_TRAFFIC_FIRST_DAY_MONTH:
return $from->copy()->addMonth()->startOfMonth();
case self::RESET_TRAFFIC_MONTHLY:
return $from->copy()->addMonth()->startOfDay();
case self::RESET_TRAFFIC_FIRST_DAY_YEAR:
return $from->copy()->addYear()->startOfYear();
case self::RESET_TRAFFIC_YEARLY:
return $from->copy()->addYear()->startOfDay();
case self::RESET_TRAFFIC_NEVER:
return null;
case self::RESET_TRAFFIC_FOLLOW_SYSTEM:
default:
// 这里需要实现获取系统设置的逻辑
// 可以通过系统配置或其他方式获取
return null;
}
}
/**
* 检查是否需要重置流量
*
* @param Carbon|null $checkTime 检查时间点,默认为当前时间
* @return bool
*/
public function shouldResetTraffic(?Carbon $checkTime = null): bool
{
if ($this->reset_traffic_method === self::RESET_TRAFFIC_NEVER) {
return false;
}
$checkTime = $checkTime ?? Carbon::now();
$nextResetTime = $this->getNextResetTime($checkTime);
if ($nextResetTime === null) {
return false;
}
return $checkTime->greaterThanOrEqualTo($nextResetTime);
}
/**
* 获取流量重置方式的描述
*
* @return string
*/
public function getResetTrafficMethodName(): string
{
return self::getResetTrafficMethods()[$this->reset_traffic_method] ?? '未知';
}
/**
* 获取所有可用的订阅周期
*
+1
View File
@@ -12,5 +12,6 @@ class ServerRoute extends Model
protected $casts = [
'created_at' => 'timestamp',
'updated_at' => 'timestamp',
'match' => 'array'
];
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* 流量重置记录模型
*
* @property int $id
* @property int $user_id 用户ID
* @property string $reset_type 重置类型
* @property \Carbon\Carbon $reset_time 重置时间
* @property int $old_upload 重置前上传流量
* @property int $old_download 重置前下载流量
* @property int $old_total 重置前总流量
* @property int $new_upload 重置后上传流量
* @property int $new_download 重置后下载流量
* @property int $new_total 重置后总流量
* @property string $trigger_source 触发来源
* @property array|null $metadata 额外元数据
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*
* @property-read User $user 关联用户
*/
class TrafficResetLog extends Model
{
protected $table = 'v2_traffic_reset_logs';
protected $fillable = [
'user_id',
'reset_type',
'reset_time',
'old_upload',
'old_download',
'old_total',
'new_upload',
'new_download',
'new_total',
'trigger_source',
'metadata',
];
protected $casts = [
'reset_time' => 'datetime',
'metadata' => 'array',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
// 重置类型常量
public const TYPE_MONTHLY = 'monthly';
public const TYPE_FIRST_DAY_MONTH = 'first_day_month';
public const TYPE_YEARLY = 'yearly';
public const TYPE_FIRST_DAY_YEAR = 'first_day_year';
public const TYPE_MANUAL = 'manual';
public const TYPE_PURCHASE = 'purchase';
// 触发来源常量
public const SOURCE_AUTO = 'auto';
public const SOURCE_MANUAL = 'manual';
public const SOURCE_API = 'api';
public const SOURCE_CRON = 'cron';
public const SOURCE_USER_ACCESS = 'user_access';
/**
* 获取重置类型的多语言名称
*/
public static function getResetTypeNames(): array
{
return [
self::TYPE_MONTHLY => __('traffic_reset.reset_type.monthly'),
self::TYPE_FIRST_DAY_MONTH => __('traffic_reset.reset_type.first_day_month'),
self::TYPE_YEARLY => __('traffic_reset.reset_type.yearly'),
self::TYPE_FIRST_DAY_YEAR => __('traffic_reset.reset_type.first_day_year'),
self::TYPE_MANUAL => __('traffic_reset.reset_type.manual'),
self::TYPE_PURCHASE => __('traffic_reset.reset_type.purchase'),
];
}
/**
* 获取触发来源的多语言名称
*/
public static function getSourceNames(): array
{
return [
self::SOURCE_AUTO => __('traffic_reset.source.auto'),
self::SOURCE_MANUAL => __('traffic_reset.source.manual'),
self::SOURCE_API => __('traffic_reset.source.api'),
self::SOURCE_CRON => __('traffic_reset.source.cron'),
self::SOURCE_USER_ACCESS => __('traffic_reset.source.user_access'),
];
}
/**
* 关联用户
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
/**
* 获取重置类型名称
*/
public function getResetTypeName(): string
{
return self::getResetTypeNames()[$this->reset_type] ?? $this->reset_type;
}
/**
* 获取触发来源名称
*/
public function getSourceName(): string
{
return self::getSourceNames()[$this->trigger_source] ?? $this->trigger_source;
}
/**
* 获取重置的流量差值
*/
public function getTrafficDiff(): array
{
return [
'upload_diff' => $this->new_upload - $this->old_upload,
'download_diff' => $this->new_download - $this->old_download,
'total_diff' => $this->new_total - $this->old_total,
];
}
/**
* 格式化流量大小
*/
public function formatTraffic(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2) . ' ' . $units[$pow];
}
}
+67 -2
View File
@@ -37,6 +37,9 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property int|null $last_login_at 最后登录时间
* @property int|null $parent_id 父账户ID
* @property int|null $is_admin 是否管理员
* @property \Carbon\Carbon|null $next_reset_at 下次流量重置时间
* @property \Carbon\Carbon|null $last_reset_at 上次流量重置时间
* @property int $reset_count 流量重置次数
* @property int $created_at
* @property int $updated_at
* @property bool $commission_auto_check 是否自动计算佣金
@@ -48,6 +51,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property-read \Illuminate\Database\Eloquent\Collection<int, Order> $orders 订单列表
* @property-read \Illuminate\Database\Eloquent\Collection<int, StatUser> $stat 统计信息
* @property-read \Illuminate\Database\Eloquent\Collection<int, Ticket> $tickets 工单列表
* @property-read \Illuminate\Database\Eloquent\Collection<int, TrafficResetLog> $trafficResetLogs 流量重置记录
* @property-read User|null $parent 父账户
* @property-read string $subscribe_url 订阅链接(动态生成)
*/
@@ -64,7 +68,9 @@ class User extends Authenticatable
'remind_expire' => 'boolean',
'remind_traffic' => 'boolean',
'commission_auto_check' => 'boolean',
'commission_rate' => 'float'
'commission_rate' => 'float',
'next_reset_at' => 'timestamp',
'last_reset_at' => 'timestamp',
];
protected $hidden = ['password'];
@@ -72,7 +78,6 @@ class User extends Authenticatable
public const COMMISSION_TYPE_PERIOD = 1;
public const COMMISSION_TYPE_ONETIME = 2;
// 获取邀请人信息
public function invite_user(): BelongsTo
{
@@ -120,6 +125,14 @@ class User extends Authenticatable
return $this->belongsTo(self::class, 'parent_id', 'id');
}
/**
* 关联流量重置记录
*/
public function trafficResetLogs(): HasMany
{
return $this->hasMany(TrafficResetLog::class, 'user_id', 'id');
}
/**
* 获取订阅链接属性
*/
@@ -127,4 +140,56 @@ class User extends Authenticatable
{
return Helper::getSubscribeUrl($this->token);
}
/**
* 检查用户是否处于活跃状态
*/
public function isActive(): bool
{
return !$this->banned &&
($this->expired_at === null || $this->expired_at > time()) &&
$this->plan_id !== null;
}
/**
* 检查是否需要重置流量
*/
public function shouldResetTraffic(): bool
{
return $this->isActive() &&
$this->next_reset_at !== null &&
$this->next_reset_at <= time();
}
/**
* 获取总使用流量
*/
public function getTotalUsedTraffic(): int
{
return ($this->u ?? 0) + ($this->d ?? 0);
}
/**
* 获取剩余流量
*/
public function getRemainingTraffic(): int
{
$used = $this->getTotalUsedTraffic();
$total = $this->transfer_enable ?? 0;
return max(0, $total - $used);
}
/**
* 获取流量使用百分比
*/
public function getTrafficUsagePercentage(): float
{
$total = $this->transfer_enable ?? 0;
if ($total <= 0) {
return 0;
}
$used = $this->getTotalUsedTraffic();
return min(100, ($used / $total) * 100);
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace App\Observers;
use App\Models\User;
use App\Services\TrafficResetService;
use Illuminate\Support\Facades\Log;
/**
* 用户模型观察者
* 主要用于监听用户到期时间变化,自动更新流量重置时间
*/
class UserObserver
{
/**
* 流量重置服务
*/
private TrafficResetService $trafficResetService;
public function __construct(TrafficResetService $trafficResetService)
{
$this->trafficResetService = $trafficResetService;
}
/**
* 监听用户更新事件
* 当 expired_at 或 plan_id 发生变化时,重新计算下次重置时间
*/
public function updating(User $user): void
{
// 检查是否有相关字段发生变化
$relevantFields = ['expired_at', 'plan_id'];
$hasRelevantChanges = false;
foreach ($relevantFields as $field) {
if ($user->isDirty($field)) {
$hasRelevantChanges = true;
break;
}
}
if (!$hasRelevantChanges) {
return; // 没有相关字段变化,直接返回
}
try {
if (!$user->plan_id) {
$user->next_reset_at = null;
return;
}
// 重新计算下次重置时间
$nextResetTime = $this->trafficResetService->calculateNextResetTime($user);
if ($nextResetTime) {
$user->next_reset_at = $nextResetTime->timestamp;
} else {
// 如果计算结果为空,清除重置时间
$user->next_reset_at = null;
}
} catch (\Exception $e) {
Log::error('更新用户流量重置时间失败', [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
// 不阻止用户更新操作,只记录错误
}
}
/**
* 监听用户创建事件
* 为新用户设置初始的重置时间
*/
public function created(User $user): void
{
// 如果用户有套餐和到期时间,设置初始重置时间
if ($user->plan_id && $user->expired_at) {
try {
$this->trafficResetService->setInitialResetTime($user);
} catch (\Exception $e) {
Log::error('设置新用户流量重置时间失败', [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
]);
}
}
}
}
+4 -1
View File
@@ -2,6 +2,8 @@
namespace App\Providers;
use App\Models\User;
use App\Observers\UserObserver;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
@@ -22,6 +24,7 @@ class EventServiceProvider extends ServiceProvider
{
parent::boot();
//
// 注册用户模型观察者
User::observe(UserObserver::class);
}
}
+5 -4
View File
@@ -8,6 +8,7 @@ use App\Models\Order;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class OrderService
{
@@ -67,7 +68,7 @@ class OrderService
}
$this->setSpeedLimit($plan->speed_limit);
$this->setDeviceLimit($plan->device_limit);
$this->setDeviceLimit($plan->device_limit);
if (!$this->user->save()) {
throw new \Exception('用户信息保存失败');
@@ -79,7 +80,7 @@ class OrderService
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
\Log::error($e);
Log::error($e);
throw new ApiException('开通失败');
}
}
@@ -238,7 +239,7 @@ class OrderService
try {
OrderHandleJob::dispatchSync($order->trade_no);
} catch (\Exception $e) {
\Log::error($e);
Log::error($e);
return false;
}
return true;
@@ -305,7 +306,7 @@ class OrderService
private function buyByOneTime(Plan $plan)
{
$this->buyByResetTraffic();
$this->user->transfer_enable = $plan->transfer_enable * 1073741824;
$this->user->transfer_enable += $plan->transfer_enable * 1073741824;
$this->user->plan_id = $plan->id;
$this->user->group_id = $plan->group_id;
$this->user->expired_at = NULL;
+461
View File
@@ -0,0 +1,461 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Models\Plan;
use App\Models\TrafficResetLog;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
/**
* Service for handling traffic reset.
*/
class TrafficResetService
{
/**
* Check if a user's traffic should be reset and perform the reset.
*/
public function checkAndReset(User $user, string $triggerSource = TrafficResetLog::SOURCE_AUTO): bool
{
if (!$user->shouldResetTraffic()) {
return false;
}
return $this->performReset($user, $triggerSource);
}
/**
* Perform the traffic reset for a user.
*/
public function performReset(User $user, string $triggerSource = TrafficResetLog::SOURCE_MANUAL): bool
{
try {
return DB::transaction(function () use ($user, $triggerSource) {
$oldUpload = $user->u ?? 0;
$oldDownload = $user->d ?? 0;
$oldTotal = $oldUpload + $oldDownload;
$nextResetTime = $this->calculateNextResetTime($user);
$user->update([
'u' => 0,
'd' => 0,
'last_reset_at' => time(),
'reset_count' => $user->reset_count + 1,
'next_reset_at' => $nextResetTime ? $nextResetTime->timestamp : null,
]);
$this->recordResetLog($user, [
'reset_type' => $this->getResetTypeFromPlan($user->plan),
'trigger_source' => $triggerSource,
'old_upload' => $oldUpload,
'old_download' => $oldDownload,
'old_total' => $oldTotal,
'new_upload' => 0,
'new_download' => 0,
'new_total' => 0,
]);
$this->clearUserCache($user);
Log::info(__('traffic_reset.reset_success'), [
'user_id' => $user->id,
'email' => $user->email,
'old_traffic' => $oldTotal,
'trigger_source' => $triggerSource,
]);
return true;
});
} catch (\Exception $e) {
Log::error(__('traffic_reset.reset_failed'), [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
'trigger_source' => $triggerSource,
]);
return false;
}
}
/**
* Calculate the next traffic reset time for a user.
*/
public function calculateNextResetTime(User $user): ?Carbon
{
if (
!$user->plan
|| $user->plan->reset_traffic_method === Plan::RESET_TRAFFIC_NEVER
|| ($user->plan->reset_traffic_method === Plan::RESET_TRAFFIC_FOLLOW_SYSTEM && (int) admin_setting('reset_traffic_method', Plan::RESET_TRAFFIC_MONTHLY) === Plan::RESET_TRAFFIC_NEVER)
|| $user->expired_at === NULL
) {
return null;
}
$resetMethod = $user->plan->reset_traffic_method;
if ($resetMethod === Plan::RESET_TRAFFIC_FOLLOW_SYSTEM) {
$resetMethod = (int) admin_setting('reset_traffic_method', Plan::RESET_TRAFFIC_MONTHLY);
}
$now = Carbon::now();
return match ($resetMethod) {
Plan::RESET_TRAFFIC_FIRST_DAY_MONTH => $this->getNextMonthFirstDay($now),
Plan::RESET_TRAFFIC_MONTHLY => $this->getNextMonthlyReset($user, $now),
Plan::RESET_TRAFFIC_FIRST_DAY_YEAR => $this->getNextYearFirstDay($now),
Plan::RESET_TRAFFIC_YEARLY => $this->getNextYearlyReset($user, $now),
Plan::RESET_TRAFFIC_NEVER => null,
default => null,
};
}
/**
* Get the first day of the next month.
*/
private function getNextMonthFirstDay(Carbon $from): Carbon
{
return $from->copy()->addMonth()->startOfMonth();
}
/**
* Get the next monthly reset time based on the user's expiration date.
*
* Logic:
* 1. If the user has no expiration date, reset on the 1st of each month.
* 2. If the user has an expiration date, use the day of that date as the monthly reset day.
* 3. Prioritize the reset day in the current month if it has not passed yet.
* 4. Handle cases where the day does not exist in a month (e.g., 31st in February).
*/
private function getNextMonthlyReset(User $user, Carbon $from): Carbon
{
$expiredAt = Carbon::createFromTimestamp($user->expired_at);
$resetDay = $expiredAt->day;
return $this->getNextResetByDay($from, $resetDay);
}
/**
* Get the next reset time based on a specific day of the month.
*/
private function getNextResetByDay(Carbon $from, int $targetDay): Carbon
{
$currentMonthTarget = $this->getValidDayInMonth($from->copy(), $targetDay);
if ($currentMonthTarget->timestamp > $from->timestamp) {
return $currentMonthTarget;
}
$nextMonth = $from->copy()->addMonth();
return $this->getValidDayInMonth($nextMonth, $targetDay);
}
/**
* Get a valid day in a given month, handling non-existent dates.
*/
private function getValidDayInMonth(Carbon $month, int $targetDay): Carbon
{
$lastDayOfMonth = $month->copy()->endOfMonth()->day;
if ($targetDay > $lastDayOfMonth) {
return $month->endOfMonth()->startOfDay();
}
return $month->day($targetDay)->startOfDay();
}
/**
* Get the first day of the next year.
*/
private function getNextYearFirstDay(Carbon $from): Carbon
{
return $from->copy()->addYear()->startOfYear();
}
/**
* Get the next yearly reset time based on the user's expiration date.
*
* Logic:
* 1. If the user has no expiration date, reset on January 1st of each year.
* 2. If the user has an expiration date, use the month and day of that date as the yearly reset date.
* 3. Prioritize the reset date in the current year if it has not passed yet.
* 4. Handle the case of February 29th in a leap year.
*/
private function getNextYearlyReset(User $user, Carbon $from): Carbon
{
$expiredAt = Carbon::createFromTimestamp($user->expired_at);
$currentYearTarget = $this->getValidYearDate($from->copy(), $expiredAt);
if ($currentYearTarget->timestamp > $from->timestamp) {
return $currentYearTarget;
}
return $this->getValidYearDate($from->copy()->addYear(), $expiredAt);
}
/**
* Get a valid date in a given year, handling leap year cases for Feb 29th.
*/
private function getValidYearDate(Carbon $year, Carbon $expiredAt): Carbon
{
$target = $year->month($expiredAt->month)->day($expiredAt->day)->startOfDay();
if ($expiredAt->month === 2 && $expiredAt->day === 29 && !$target->isLeapYear()) {
$target->day(28);
}
return $target;
}
/**
* Record the traffic reset log.
*/
private function recordResetLog(User $user, array $data): void
{
TrafficResetLog::create([
'user_id' => $user->id,
'reset_type' => $data['reset_type'],
'reset_time' => now(),
'old_upload' => $data['old_upload'],
'old_download' => $data['old_download'],
'old_total' => $data['old_total'],
'new_upload' => $data['new_upload'],
'new_download' => $data['new_download'],
'new_total' => $data['new_total'],
'trigger_source' => $data['trigger_source'],
'metadata' => $data['metadata'] ?? null,
]);
}
/**
* Get the reset type from the user's plan.
*/
private function getResetTypeFromPlan(?Plan $plan): string
{
if (!$plan) {
return TrafficResetLog::TYPE_MANUAL;
}
$resetMethod = $plan->reset_traffic_method;
if ($resetMethod === Plan::RESET_TRAFFIC_FOLLOW_SYSTEM) {
$resetMethod = (int) admin_setting('reset_traffic_method', Plan::RESET_TRAFFIC_MONTHLY);
}
return match ($resetMethod) {
Plan::RESET_TRAFFIC_FIRST_DAY_MONTH => TrafficResetLog::TYPE_FIRST_DAY_MONTH,
Plan::RESET_TRAFFIC_MONTHLY => TrafficResetLog::TYPE_MONTHLY,
Plan::RESET_TRAFFIC_FIRST_DAY_YEAR => TrafficResetLog::TYPE_FIRST_DAY_YEAR,
Plan::RESET_TRAFFIC_YEARLY => TrafficResetLog::TYPE_YEARLY,
default => TrafficResetLog::TYPE_MANUAL,
};
}
/**
* Clear user-related cache.
*/
private function clearUserCache(User $user): void
{
$cacheKeys = [
"user_traffic_{$user->id}",
"user_reset_status_{$user->id}",
"user_subscription_{$user->token}",
];
foreach ($cacheKeys as $key) {
Cache::forget($key);
}
}
/**
* Batch check and reset users. Processes all eligible users in batches.
*/
public function batchCheckReset(int $batchSize = 100, callable $progressCallback = null): array
{
$startTime = microtime(true);
$totalResetCount = 0;
$totalProcessedCount = 0;
$batchNumber = 1;
$errors = [];
$lastProcessedId = 0;
Log::info('Starting batch traffic reset task.', [
'batch_size' => $batchSize,
'start_time' => now()->toDateTimeString(),
]);
try {
do {
$users = User::where('next_reset_at', '<=', time())
->whereNotNull('next_reset_at')
->where('id', '>', $lastProcessedId)
->where(function ($query) {
$query->where('expired_at', '>', time())
->orWhereNull('expired_at');
})
->where('banned', 0)
->whereNotNull('plan_id')
->orderBy('id')
->limit($batchSize)
->get();
if ($users->isEmpty()) {
break;
}
$batchStartTime = microtime(true);
$batchResetCount = 0;
$batchErrors = [];
if ($progressCallback) {
$progressCallback([
'batch_number' => $batchNumber,
'batch_size' => $users->count(),
'total_processed' => $totalProcessedCount,
]);
}
Log::info("Processing batch #{$batchNumber}", [
'batch_number' => $batchNumber,
'batch_size' => $users->count(),
'total_processed' => $totalProcessedCount,
'id_range' => $users->first()->id . '-' . $users->last()->id,
]);
foreach ($users as $user) {
try {
if ($this->checkAndReset($user, TrafficResetLog::SOURCE_CRON)) {
$batchResetCount++;
$totalResetCount++;
}
$totalProcessedCount++;
$lastProcessedId = $user->id;
} catch (\Exception $e) {
$error = [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
'batch' => $batchNumber,
'timestamp' => now()->toDateTimeString(),
];
$batchErrors[] = $error;
$errors[] = $error;
Log::error('User traffic reset failed', $error);
$totalProcessedCount++;
$lastProcessedId = $user->id;
}
}
$batchDuration = round(microtime(true) - $batchStartTime, 2);
Log::info("Batch #{$batchNumber} processing complete", [
'batch_number' => $batchNumber,
'processed_count' => $users->count(),
'reset_count' => $batchResetCount,
'error_count' => count($batchErrors),
'duration' => $batchDuration,
'last_processed_id' => $lastProcessedId,
]);
$batchNumber++;
if ($batchNumber % 10 === 0) {
gc_collect_cycles();
}
if ($batchNumber % 5 === 0) {
usleep(100000);
}
} while (true);
} catch (\Exception $e) {
Log::error('Batch traffic reset task failed with an exception', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
'total_processed' => $totalProcessedCount,
'total_reset' => $totalResetCount,
'last_processed_id' => $lastProcessedId,
]);
$errors[] = [
'type' => 'system_error',
'error' => $e->getMessage(),
'batch' => $batchNumber,
'last_processed_id' => $lastProcessedId,
'timestamp' => now()->toDateTimeString(),
];
}
$totalDuration = round(microtime(true) - $startTime, 2);
$result = [
'total_processed' => $totalProcessedCount,
'total_reset' => $totalResetCount,
'total_batches' => $batchNumber - 1,
'error_count' => count($errors),
'errors' => $errors,
'duration' => $totalDuration,
'batch_size' => $batchSize,
'last_processed_id' => $lastProcessedId,
'completed_at' => now()->toDateTimeString(),
];
Log::info('Batch traffic reset task completed', $result);
return $result;
}
/**
* Set the initial reset time for a new user.
*/
public function setInitialResetTime(User $user): void
{
if ($user->next_reset_at !== null) {
return;
}
$nextResetTime = $this->calculateNextResetTime($user);
if ($nextResetTime) {
$user->update(['next_reset_at' => $nextResetTime->timestamp]);
}
}
/**
* Get the user's traffic reset history.
*/
public function getUserResetHistory(User $user, int $limit = 10): \Illuminate\Database\Eloquent\Collection
{
return $user->trafficResetLogs()
->orderBy('reset_time', 'desc')
->limit($limit)
->get();
}
/**
* Check if the user is eligible for traffic reset.
*/
public function canReset(User $user): bool
{
return $user->isActive() && $user->plan !== null;
}
/**
* Manually reset a user's traffic (Admin function).
*/
public function manualReset(User $user, array $metadata = []): bool
{
if (!$this->canReset($user)) {
return false;
}
return $this->performReset($user, TrafficResetLog::SOURCE_MANUAL);
}
}
+49 -64
View File
@@ -9,76 +9,37 @@ use App\Models\Order;
use App\Models\Plan;
use App\Models\User;
use App\Services\Plugin\HookManager;
use App\Services\TrafficResetService;
use App\Models\TrafficResetLog;
class UserService
{
private function calcResetDayByMonthFirstDay(): int
{
$today = (int) date('d');
$lastDay = (int) date('d', strtotime('last day of +0 months'));
return $lastDay - $today;
}
private function calcResetDayByExpireDay(int $expiredAt)
{
$day = (int) date('d', $expiredAt);
$today = (int) date('d');
$lastDay = (int) date('d', strtotime('last day of +0 months'));
if ($day >= $today && $day >= $lastDay) {
return $lastDay - $today;
}
if ($day >= $today) {
return $day - $today;
}
return $lastDay - $today + $day;
}
private function calcResetDayByYearFirstDay(): int
{
$nextYear = strtotime(date("Y-01-01", strtotime('+1 year')));
return (int) (($nextYear - time()) / 86400);
}
private function calcResetDayByYearExpiredAt(int $expiredAt): int
{
$md = date('m-d', $expiredAt);
$nowYear = strtotime(date("Y-{$md}"));
$nextYear = strtotime('+1 year', $nowYear);
if ($nowYear > time()) {
return (int) (($nowYear - time()) / 86400);
}
return (int) (($nextYear - time()) / 86400);
}
/**
* Get the remaining days until the next traffic reset for a user.
* This method reuses the TrafficResetService logic for consistency.
*/
public function getResetDay(User $user): ?int
{
// 前置条件检查
if ($user->expired_at <= time() || $user->expired_at === null) {
return null;
}
// 获取重置方式逻辑统一
$resetMethod = $user->plan->reset_traffic_method === Plan::RESET_TRAFFIC_FOLLOW_SYSTEM
? (int)admin_setting('reset_traffic_method', 0)
: $user->plan->reset_traffic_method;
// 验证重置方式有效性
if (!in_array($resetMethod, array_keys(Plan::getResetTrafficMethods()), true)) {
return null;
}
// 方法映射表
$methodHandlers = [
Plan::RESET_TRAFFIC_FIRST_DAY_MONTH => fn() => $this->calcResetDayByMonthFirstDay(),
Plan::RESET_TRAFFIC_MONTHLY => fn() => $this->calcResetDayByExpireDay($user->expired_at),
Plan::RESET_TRAFFIC_FIRST_DAY_YEAR => fn() => $this->calcResetDayByYearFirstDay(),
Plan::RESET_TRAFFIC_YEARLY => fn() => $this->calcResetDayByYearExpiredAt($user->expired_at),
];
$handler = $methodHandlers[$resetMethod] ?? null;
// Use TrafficResetService to calculate the next reset time
$trafficResetService = app(TrafficResetService::class);
$nextResetTime = $trafficResetService->calculateNextResetTime($user);
return $handler ? $handler() : null;
if (!$nextResetTime) {
return null;
}
// Calculate the remaining days from now to the next reset time
$now = time();
$resetTimestamp = $nextResetTime->timestamp;
if ($resetTimestamp <= $now) {
return 0; // Reset time has passed or is now
}
// Calculate the difference in days (rounded up)
$daysDifference = ceil(($resetTimestamp - $now) / 86400);
return (int) $daysDifference;
}
public function isAvailable(User $user)
@@ -165,4 +126,28 @@ class UserService
StatServerJob::dispatch($server, $chunk->toArray(), $protocol, 'd');
});
}
/**
* 获取用户流量信息(增加重置检查)
*/
public function getUserTrafficInfo(User $user): array
{
// 检查是否需要重置流量
app(TrafficResetService::class)->checkAndReset($user, TrafficResetLog::SOURCE_USER_ACCESS);
// 重新获取用户数据(可能已被重置)
$user->refresh();
return [
'upload' => $user->u ?? 0,
'download' => $user->d ?? 0,
'total_used' => $user->getTotalUsedTraffic(),
'total_available' => $user->transfer_enable ?? 0,
'remaining' => $user->getRemainingTraffic(),
'usage_percentage' => $user->getTrafficUsagePercentage(),
'next_reset_at' => $user->next_reset_at?->timestamp,
'last_reset_at' => $user->last_reset_at?->timestamp,
'reset_count' => $user->reset_count,
];
}
}
+1 -1
View File
@@ -132,7 +132,7 @@ class Setting
CASE_LOWER
);
});
// 处理JSON格式的值
foreach ($settings as $key => $value) {
if (is_string($value) && $value !== null) {
+9
View File
@@ -202,4 +202,13 @@ class Helper
$revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
return strtr(rawurlencode($str), $revert);
}
public static function getEmailSuffix(): array|bool
{
$suffix = admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT);
if (!is_array($suffix)) {
return preg_split('/,/', $suffix);
}
return $suffix;
}
}