From 97e7ffccae54d4845c364686c1d87cfa0ee66203 Mon Sep 17 00:00:00 2001 From: xboard Date: Wed, 7 May 2025 19:48:19 +0800 Subject: [PATCH] fix: resolve PHPStan static analysis warnings --- .github/workflows/docker-publish.yml | 15 +- app/Console/Commands/CheckCommission.php | 7 +- app/Console/Commands/ExportV2Log.php | 24 +- app/Console/Commands/ResetTraffic.php | 217 ++++++------- app/Console/Commands/XboardInstall.php | 8 +- app/Console/Commands/XboardStatistics.php | 67 +--- app/Console/Kernel.php | 6 +- app/Exceptions/Handler.php | 4 +- .../V1/Passport/AuthController.php | 289 +++++------------- .../V1/Passport/CommController.php | 14 +- .../V1/Server/UniProxyController.php | 16 +- .../Controllers/V1/Staff/NoticeController.php | 58 ---- .../Controllers/V1/Staff/PlanController.php | 35 --- .../Controllers/V1/Staff/TicketController.php | 82 ----- .../Controllers/V1/Staff/UserController.php | 102 ------- .../Controllers/V1/User/OrderController.php | 12 +- .../Controllers/V1/User/UserController.php | 12 +- .../Controllers/V2/Admin/ConfigController.php | 6 - .../Controllers/V2/Admin/OrderController.php | 40 +-- .../Controllers/V2/Admin/PlanController.php | 17 +- .../V2/Admin/Server/GroupController.php | 12 +- .../V2/Admin/Server/ManageController.php | 11 +- .../Controllers/V2/Admin/StatController.php | 6 +- .../Controllers/V2/Admin/TicketController.php | 38 ++- .../Controllers/V2/Admin/UserController.php | 42 +-- app/Http/Kernel.php | 8 +- app/Http/Middleware/Admin.php | 13 +- .../Middleware/CheckForMaintenanceMode.php | 13 +- app/Http/Middleware/EncryptCookies.php | 5 +- app/Http/Middleware/TrimStrings.php | 7 +- app/Http/Middleware/TrustProxies.php | 8 +- app/Http/Middleware/VerifyCsrfToken.php | 8 +- app/Http/Requests/Admin/ServerSave.php | 14 +- app/Http/Resources/OrderResource.php | 8 +- app/Http/Routes/V1/ClientRoute.php | 8 +- app/Http/Routes/V1/PassportRoute.php | 18 +- app/Http/Routes/V1/StaffRoute.php | 32 -- app/Http/Routes/V1/UserRoute.php | 84 ++--- app/Http/Routes/V2/PassportRoute.php | 18 +- app/Http/Routes/V2/UserRoute.php | 5 +- app/Logging/MysqlLoggerHandler.php | 24 +- app/Models/Order.php | 57 +++- app/Models/Payment.php | 3 +- app/Models/Plan.php | 43 ++- app/Models/Server.php | 204 ++++++++++--- app/Models/ServerGroup.php | 20 ++ app/Models/StatServer.php | 12 + app/Models/StatUser.php | 12 + app/Models/Ticket.php | 29 +- app/Models/TicketMessage.php | 31 ++ app/Models/User.php | 87 +++++- app/Payments/BTCPay.php | 5 +- app/Payments/BinancePay.php | 118 +++++++ app/Payments/Coinbase.php | 4 +- app/Payments/EPayWxpay.php | 71 +++++ app/Payments/HiiCashPayment.php | 113 +++++++ app/Payments/PayPal.php | 132 ++++++++ app/Protocols/Clash.php | 69 ++++- app/Protocols/ClashMeta.php | 97 +++++- app/Protocols/General.php | 19 +- app/Protocols/QuantumultX.php | 1 - app/Protocols/Shadowrocket.php | 14 +- app/Protocols/Shadowsocks.php | 2 +- app/Protocols/SingBox.php | 64 +++- app/Protocols/Stash.php | 93 +++++- app/Protocols/Surfboard.php | 11 +- app/Protocols/Surge.php | 4 +- app/Providers/AuthServiceProvider.php | 8 +- app/Providers/EventServiceProvider.php | 8 +- app/Services/Auth/LoginService.php | 111 +++++++ app/Services/Auth/MailLinkService.php | 122 ++++++++ app/Services/Auth/RegisterService.php | 209 +++++++++++++ app/Services/AuthService.php | 30 +- app/Services/OrderService.php | 18 +- app/Services/PlanService.php | 5 +- app/Services/Plugin/HookManager.php | 17 +- app/Services/ServerService.php | 47 +-- app/Services/StatisticalService.php | 60 ++-- app/Services/UserOnlineService.php | 17 +- app/Services/UserService.php | 73 ++--- app/Support/Setting.php | 33 +- app/Utils/CacheKey.php | 16 + app/Utils/Helper.php | 2 +- composer.json | 2 + phpstan.neon | 17 ++ public/assets/admin/assets/index.js | 18 +- 86 files changed, 2335 insertions(+), 1206 deletions(-) delete mode 100644 app/Http/Controllers/V1/Staff/NoticeController.php delete mode 100755 app/Http/Controllers/V1/Staff/PlanController.php delete mode 100644 app/Http/Controllers/V1/Staff/TicketController.php delete mode 100644 app/Http/Controllers/V1/Staff/UserController.php delete mode 100644 app/Http/Routes/V1/StaffRoute.php create mode 100644 app/Payments/BinancePay.php create mode 100644 app/Payments/EPayWxpay.php create mode 100644 app/Payments/HiiCashPayment.php create mode 100644 app/Payments/PayPal.php create mode 100644 app/Services/Auth/LoginService.php create mode 100644 app/Services/Auth/MailLinkService.php create mode 100644 app/Services/Auth/RegisterService.php create mode 100644 phpstan.neon diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 2afec8d..ccef8c3 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -2,7 +2,7 @@ name: Docker Build and Publish on: push: - branches: ["master"] + branches: ["master", "new-dev"] workflow_dispatch: env: @@ -59,7 +59,12 @@ jobs: tags: | type=ref,event=branch type=sha,format=long - type=raw,value=new + type=raw,value=new,enable=${{ github.ref == 'refs/heads/master' }} + type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }} + type=raw,value=${{ steps.get_version.outputs.version }} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.revision=${{ github.sha }} - name: Get version id: get_version @@ -80,10 +85,8 @@ jobs: platforms: linux/amd64,linux/arm64 cache-from: type=gha cache-to: type=gha,mode=max - tags: | - ${{ env.REGISTRY }}/${{ github.repository_owner }}/xboard:master - ${{ env.REGISTRY }}/${{ github.repository_owner }}/xboard:new - ${{ env.REGISTRY }}/${{ github.repository_owner }}/xboard:${{ steps.get_version.outputs.version }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} build-args: | BUILDKIT_INLINE_CACHE=1 BUILDKIT_MULTI_PLATFORM=1 diff --git a/app/Console/Commands/CheckCommission.php b/app/Console/Commands/CheckCommission.php index 3c3589b..f9e5518 100644 --- a/app/Console/Commands/CheckCommission.php +++ b/app/Console/Commands/CheckCommission.php @@ -112,16 +112,13 @@ class CheckCommission extends Command DB::rollBack(); return false; } - if (!CommissionLog::create([ + CommissionLog::create([ 'invite_user_id' => $inviteUserId, 'user_id' => $order->user_id, 'trade_no' => $order->trade_no, 'order_amount' => $order->total_amount, 'get_amount' => $commissionBalance - ])) { - DB::rollBack(); - return false; - } + ]); $inviteUserId = $inviter->invite_user_id; // update order actual commission balance $order->actual_commission_balance = $order->actual_commission_balance + $commissionBalance; diff --git a/app/Console/Commands/ExportV2Log.php b/app/Console/Commands/ExportV2Log.php index ec2ccbe..1bc1fa3 100644 --- a/app/Console/Commands/ExportV2Log.php +++ b/app/Console/Commands/ExportV2Log.php @@ -19,11 +19,11 @@ class ExportV2Log extends Command public function handle() { $days = $this->argument('days'); - $date = Carbon::now()->subDays($days)->startOfDay(); + $date = Carbon::now()->subDays((float) $days)->startOfDay(); $logs = DB::table('v2_log') - ->where('created_at', '>=', $date->timestamp) - ->get(); + ->where('created_at', '>=', $date->timestamp) + ->get(); $fileName = "v2_logs_" . Carbon::now()->format('Y_m_d_His') . ".csv"; $handle = fopen(storage_path("logs/$fileName"), 'w'); @@ -35,19 +35,19 @@ class ExportV2Log extends Command fputcsv($handle, [ $log->level, $log->id, - $log->title, - $log->host, - $log->uri, - $log->method, - $log->data, - $log->ip, - $log->context, - Carbon::createFromTimestamp($log->created_at)->toDateTimeString(), + $log->title, + $log->host, + $log->uri, + $log->method, + $log->data, + $log->ip, + $log->context, + Carbon::createFromTimestamp($log->created_at)->toDateTimeString(), Carbon::createFromTimestamp($log->updated_at)->toDateTimeString() ]); } fclose($handle); - $this->info("日志成功导出到: ". storage_path("logs/$fileName")); + $this->info("日志成功导出到: " . storage_path("logs/$fileName")); } } diff --git a/app/Console/Commands/ResetTraffic.php b/app/Console/Commands/ResetTraffic.php index 4c90b1a..60ee4a1 100644 --- a/app/Console/Commands/ResetTraffic.php +++ b/app/Console/Commands/ResetTraffic.php @@ -5,30 +5,26 @@ namespace App\Console\Commands; use App\Models\Plan; use Illuminate\Console\Command; use App\Models\User; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\DB; class ResetTraffic extends Command { - protected $builder; /** - * The name and signature of the console command. - * + * @var Builder + */ + protected $builder; + + /** * @var string */ protected $signature = 'reset:traffic'; /** - * The console command description. - * * @var string */ protected $description = '流量清空'; - /** - * Create a new command instance. - * - * @return void - */ public function __construct() { parent::__construct(); @@ -37,13 +33,13 @@ class ResetTraffic extends Command } /** - * Execute the console command. - * - * @return mixed + * 执行流量重置命令 */ public function handle() { ini_set('memory_limit', -1); + + // 按重置方法分组查询所有套餐 $resetMethods = Plan::select( DB::raw("GROUP_CONCAT(`id`) as plan_ids"), DB::raw("reset_traffic_method as method") @@ -51,138 +47,117 @@ class ResetTraffic extends Command ->groupBy('reset_traffic_method') ->get() ->toArray(); + + // 使用闭包直接引用方法 + $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), + ]; + + // 处理每种重置方法 foreach ($resetMethods as $resetMethod) { $planIds = explode(',', $resetMethod['plan_ids']); - switch (true) { - case ($resetMethod['method'] === NULL): { - $resetTrafficMethod = admin_setting('reset_traffic_method', 0); - $builder = with(clone ($this->builder))->whereIn('plan_id', $planIds); - switch ((int) $resetTrafficMethod) { - // month first day - case 0: - $this->resetByMonthFirstDay($builder); - break; - // expire day - case 1: - $this->resetByExpireDay($builder); - break; - // no action - case 2: - break; - // year first day - case 3: - $this->resetByYearFirstDay($builder); - // year expire day - case 4: - $this->resetByExpireYear($builder); - } - break; - } - case ($resetMethod['method'] === 0): { - $builder = with(clone ($this->builder))->whereIn('plan_id', $planIds); - $this->resetByMonthFirstDay($builder); - break; - } - case ($resetMethod['method'] === 1): { - $builder = with(clone ($this->builder))->whereIn('plan_id', $planIds); - $this->resetByExpireDay($builder); - break; - } - case ($resetMethod['method'] === 2): { - break; - } - case ($resetMethod['method'] === 3): { - $builder = with(clone ($this->builder))->whereIn('plan_id', $planIds); - $this->resetByYearFirstDay($builder); - break; - } - case ($resetMethod['method'] === 4): { - $builder = with(clone ($this->builder))->whereIn('plan_id', $planIds); - $this->resetByExpireYear($builder); - break; - } + + // 获取重置方法 + $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); } } - private function resetByExpireYear($builder): void + /** + * 按用户年度到期日重置流量 + */ + private function resetByExpireYear(Builder $builder): void { - - $users = $builder->with('plan')->get(); - $usersToUpdate = []; - foreach ($users as $user) { - $expireDay = date('m-d', $user->expired_at); - $today = date('m-d'); - if ($expireDay === $today) { - $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 - ]); - } + $today = date('m-d'); + $this->resetUsersByDateCondition($builder, function ($user) use ($today) { + return date('m-d', $user->expired_at) === $today; + }); } - private function resetByYearFirstDay($builder): void + /** + * 按新年第一天重置流量 + */ + private function resetByYearFirstDay(Builder $builder): void { - $users = $builder->with('plan')->get(); - $usersToUpdate = []; - foreach ($users as $user) { - if ((string) date('md') === '0101') { - $usersToUpdate[] = [ - 'id' => $user->id, - 'transfer_enable' => $user->plan->transfer_enable - ]; - } + $isNewYear = date('md') === '0101'; + if (!$isNewYear) { + return; } - foreach ($usersToUpdate as $userData) { - User::where('id', $userData['id'])->update([ - 'transfer_enable' => (intval($userData['transfer_enable']) * 1073741824), - 'u' => 0, - 'd' => 0 - ]); - } + $this->resetAllUsers($builder); } - private function resetByMonthFirstDay($builder): void + /** + * 按月初第一天重置流量 + */ + private function resetByMonthFirstDay(Builder $builder): void { - $users = $builder->with('plan')->get(); - $usersToUpdate = []; - foreach ($users as $user) { - if ((string) date('d') === '01') { - $usersToUpdate[] = [ - 'id' => $user->id, - 'transfer_enable' => $user->plan->transfer_enable - ]; - } + $isFirstDayOfMonth = date('d') === '01'; + if (!$isFirstDayOfMonth) { + return; } - foreach ($usersToUpdate as $userData) { - User::where('id', $userData['id'])->update([ - 'transfer_enable' => (intval($userData['transfer_enable']) * 1073741824), - 'u' => 0, - 'd' => 0 - ]); - } + $this->resetAllUsers($builder); } - private function resetByExpireDay($builder): void + + /** + * 按用户到期日重置流量 + */ + private function resetByExpireDay(Builder $builder): void { - $lastDay = date('d', strtotime('last day of +0 months')); $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) { - $expireDay = date('d', $user->expired_at); - if ($expireDay === $today || ($today === $lastDay && $expireDay >= $today)) { + if ($condition($user)) { $usersToUpdate[] = [ 'id' => $user->id, 'transfer_enable' => $user->plan->transfer_enable diff --git a/app/Console/Commands/XboardInstall.php b/app/Console/Commands/XboardInstall.php index 658fd06..a33d2f2 100644 --- a/app/Console/Commands/XboardInstall.php +++ b/app/Console/Commands/XboardInstall.php @@ -50,9 +50,9 @@ class XboardInstall extends Command { try { $isDocker = file_exists('/.dockerenv'); - $enableSqlite = env('ENABLE_SQLITE', false); - $enableRedis = env('ENABLE_REDIS', false); - $adminAccount = env('ADMIN_ACCOUNT', ''); + $enableSqlite = getenv('ENABLE_SQLITE', false); + $enableRedis = getenv('ENABLE_REDIS', false); + $adminAccount = getenv('ADMIN_ACCOUNT', false); $this->info("__ __ ____ _ "); $this->info("\ \ / /| __ ) ___ __ _ _ __ __| | "); $this->info(" \ \/ / | __ \ / _ \ / _` | '__/ _` | "); @@ -60,7 +60,7 @@ class XboardInstall extends Command $this->info("/_/ \_\|____/ \___/ \__,_|_| \__,_| "); if ( (File::exists(base_path() . '/.env') && $this->getEnvValue('INSTALLED')) - || (env('INSTALLED', false) && $isDocker) + || (getenv('INSTALLED', false) && $isDocker) ) { $securePath = admin_setting('secure_path', admin_setting('frontend_admin_path', hash('crc32b', config('app.key')))); $this->info("访问 http(s)://你的站点/{$securePath} 进入管理面板,你可以在用户中心修改你的密码。"); diff --git a/app/Console/Commands/XboardStatistics.php b/app/Console/Commands/XboardStatistics.php index 01c275e..0bd4736 100644 --- a/app/Console/Commands/XboardStatistics.php +++ b/app/Console/Commands/XboardStatistics.php @@ -2,12 +2,10 @@ namespace App\Console\Commands; -use App\Models\StatServer; -use App\Models\StatUser; use App\Services\StatisticalService; use Illuminate\Console\Command; use App\Models\Stat; -use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; class XboardStatistics extends Command { @@ -50,67 +48,6 @@ class XboardStatistics extends Command info('统计任务执行完毕。耗时:' . (microtime(true) - $startAt) / 1000); } - private function statServer() - { - try { - DB::beginTransaction(); - $createdAt = time(); - $recordAt = strtotime('-1 day', strtotime(date('Y-m-d'))); - $statService = new StatisticalService(); - $statService->setStartAt($recordAt); - $stats = $statService->getStatServer(); - foreach ($stats as $stat) { - if (!StatServer::insert([ - 'server_id' => $stat['server_id'], - 'server_type' => $stat['server_type'], - 'u' => $stat['u'], - 'd' => $stat['d'], - 'created_at' => $createdAt, - 'updated_at' => $createdAt, - 'record_type' => 'd', - 'record_at' => $recordAt - ])) { - throw new \Exception('stat server fail'); - } - } - DB::commit(); - $statService->clearStatServer(); - } catch (\Exception $e) { - DB::rollback(); - \Log::error($e->getMessage(), ['exception' => $e]); - } - } - - private function statUser() - { - try { - DB::beginTransaction(); - $createdAt = time(); - $recordAt = strtotime('-1 day', strtotime(date('Y-m-d'))); - $statService = new StatisticalService(); - $statService->setStartAt($recordAt); - $stats = $statService->getStatUser(); - foreach ($stats as $stat) { - if (!StatUser::insert([ - 'user_id' => $stat['user_id'], - 'u' => $stat['u'], - 'd' => $stat['d'], - 'server_rate' => $stat['server_rate'], - 'created_at' => $createdAt, - 'updated_at' => $createdAt, - 'record_type' => 'd', - 'record_at' => $recordAt - ])) { - throw new \Exception('stat user fail'); - } - } - DB::commit(); - $statService->clearStatUser(); - } catch (\Exception $e) { - DB::rollback(); - \Log::error($e->getMessage(), ['exception' => $e]); - } - } private function stat() { @@ -132,7 +69,7 @@ class XboardStatistics extends Command } Stat::create($data); } catch (\Exception $e) { - \Log::error($e->getMessage(), ['exception' => $e]); + Log::error($e->getMessage(), ['exception' => $e]); } } } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 62b2fc7..feb49c3 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -42,9 +42,9 @@ class Kernel extends ConsoleKernel // horizon metrics $schedule->command('horizon:snapshot')->everyFiveMinutes()->onOneServer(); // backup Timing - if (env('ENABLE_AUTO_BACKUP_AND_UPDATE', false)) { - $schedule->command('backup:database', ['true'])->daily()->onOneServer(); - } + // if (env('ENABLE_AUTO_BACKUP_AND_UPDATE', false)) { + // $schedule->command('backup:database', ['true'])->daily()->onOneServer(); + // } // 每分钟清理过期的在线状态 $schedule->call(function () { app(UserOnlineService::class)->cleanExpiredOnlineStatus(); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 7b789aa..f76d9c0 100755 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -16,7 +16,7 @@ class Handler extends ExceptionHandler /** * A list of the exception types that are not reported. * - * @var array + * @var array> */ protected $dontReport = [ ApiException::class, @@ -26,7 +26,7 @@ class Handler extends ExceptionHandler /** * A list of the inputs that are never flashed for validation exceptions. * - * @var array + * @var array */ protected $dontFlash = [ 'password', diff --git a/app/Http/Controllers/V1/Passport/AuthController.php b/app/Http/Controllers/V1/Passport/AuthController.php index cd34e4f..4bea6a6 100644 --- a/app/Http/Controllers/V1/Passport/AuthController.php +++ b/app/Http/Controllers/V1/Passport/AuthController.php @@ -7,227 +7,89 @@ use App\Http\Controllers\Controller; use App\Http\Requests\Passport\AuthForget; use App\Http\Requests\Passport\AuthLogin; use App\Http\Requests\Passport\AuthRegister; -use App\Jobs\SendEmailJob; -use App\Models\InviteCode; -use App\Models\Plan; -use App\Models\User; +use App\Services\Auth\LoginService; +use App\Services\Auth\MailLinkService; +use App\Services\Auth\RegisterService; use App\Services\AuthService; -use App\Utils\CacheKey; -use App\Utils\Dict; -use App\Utils\Helper; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use ReCaptcha\ReCaptcha; class AuthController extends Controller { + protected MailLinkService $mailLinkService; + protected RegisterService $registerService; + protected LoginService $loginService; + + public function __construct( + MailLinkService $mailLinkService, + RegisterService $registerService, + LoginService $loginService + ) { + $this->mailLinkService = $mailLinkService; + $this->registerService = $registerService; + $this->loginService = $loginService; + } + + /** + * 通过邮件链接登录 + */ public function loginWithMailLink(Request $request) { - if (!(int)admin_setting('login_with_mail_link_enable')) { - return $this->fail([404,null]); - } $params = $request->validate([ 'email' => 'required|email:strict', 'redirect' => 'nullable' ]); - if (Cache::get(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $params['email']))) { - return $this->fail([429 ,__('Sending frequently, please try again later')]); + [$success, $result] = $this->mailLinkService->handleMailLink( + $params['email'], + $request->input('redirect') + ); + + if (!$success) { + return $this->fail($result); } - $user = User::where('email', $params['email'])->first(); - if (!$user) { - return $this->success(true); - } - - $code = Helper::guid(); - $key = CacheKey::get('TEMP_TOKEN', $code); - Cache::put($key, $user->id, 300); - Cache::put(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $params['email']), time(), 60); - - - $redirect = '/#/login?verify=' . $code . '&redirect=' . ($request->input('redirect') ? $request->input('redirect') : 'dashboard'); - if (admin_setting('app_url')) { - $link = admin_setting('app_url') . $redirect; - } else { - $link = url($redirect); - } - - SendEmailJob::dispatch([ - 'email' => $user->email, - 'subject' => __('Login to :name', [ - 'name' => admin_setting('app_name', 'XBoard') - ]), - 'template_name' => 'login', - 'template_value' => [ - 'name' => admin_setting('app_name', 'XBoard'), - 'link' => $link, - 'url' => admin_setting('app_url') - ] - ]); - - return $this->success($link); - + return $this->success($result); } + /** + * 用户注册 + */ public function register(AuthRegister $request) { - if ((int)admin_setting('register_limit_by_ip_enable', 0)) { - $registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0; - if ((int)$registerCountByIP >= (int)admin_setting('register_limit_count', 3)) { - return $this->fail([429,__('Register frequently, please try again after :minute minute', [ - 'minute' => admin_setting('register_limit_expire', 60) - ])]); - } - } - if ((int)admin_setting('recaptcha_enable', 0)) { - $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); - $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); - if (!$recaptchaResp->isSuccess()) { - return $this->fail([400,__('Invalid code is incorrect')]); - } - } - if ((int)admin_setting('email_whitelist_enable', 0)) { - if (!Helper::emailSuffixVerify( - $request->input('email'), - admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT)) - ) { - return $this->fail([400,__('Email suffix is not in the Whitelist')]); - } - } - if ((int)admin_setting('email_gmail_limit_enable', 0)) { - $prefix = explode('@', $request->input('email'))[0]; - if (strpos($prefix, '.') !== false || strpos($prefix, '+') !== false) { - return $this->fail([400,__('Gmail alias is not supported')]); - } - } - if ((int)admin_setting('stop_register', 0)) { - return $this->fail([400,__('Registration has closed')]); - } - if ((int)admin_setting('invite_force', 0)) { - if (empty($request->input('invite_code'))) { - return $this->fail([422,__('You must use the invitation code to register')]); - } - } - if ((int)admin_setting('email_verify', 0)) { - if (empty($request->input('email_code'))) { - return $this->fail([422,__('Email verification code cannot be empty')]); - } - if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { - return $this->fail([400,__('Incorrect email verification code')]); - } - } - $email = $request->input('email'); - $password = $request->input('password'); - $exist = User::where('email', $email)->first(); - if ($exist) { - return $this->fail([400201,__('Email already exists')]); - } - $user = new User(); - $user->email = $email; - $user->password = password_hash($password, PASSWORD_DEFAULT); - $user->uuid = Helper::guid(true); - $user->token = Helper::guid(); - // TODO 增加过期默认值、流量告急提醒默认值 - $user->remind_expire = admin_setting('default_remind_expire',1); - $user->remind_traffic = admin_setting('default_remind_traffic',1); - if ($request->input('invite_code')) { - $inviteCode = InviteCode::where('code', $request->input('invite_code')) - ->where('status', 0) - ->first(); - if (!$inviteCode) { - if ((int)admin_setting('invite_force', 0)) { - return $this->fail([400,__('Invalid invitation code')]); - } - } else { - $user->invite_user_id = $inviteCode->user_id ? $inviteCode->user_id : null; - if (!(int)admin_setting('invite_never_expire', 0)) { - $inviteCode->status = 1; - $inviteCode->save(); - } - } + [$success, $result] = $this->registerService->register($request); + + if (!$success) { + return $this->fail($result); } - // try out - if ((int)admin_setting('try_out_plan_id', 0)) { - $plan = Plan::find(admin_setting('try_out_plan_id')); - if ($plan) { - $user->transfer_enable = $plan->transfer_enable * 1073741824; - $user->plan_id = $plan->id; - $user->group_id = $plan->group_id; - $user->expired_at = time() + (admin_setting('try_out_hour', 1) * 3600); - $user->speed_limit = $plan->speed_limit; - } - } - - if (!$user->save()) { - return $this->fail([500,__('Register failed')]); - } - if ((int)admin_setting('email_verify', 0)) { - Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))); - } - - $user->last_login_at = time(); - $user->save(); - - if ((int)admin_setting('register_limit_by_ip_enable', 0)) { - Cache::put( - CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip()), - (int)$registerCountByIP + 1, - (int)admin_setting('register_limit_expire', 60) * 60 - ); - } - - $authService = new AuthService($user); - - $data = $authService->generateAuthData(); - return $this->success($data); + $authService = new AuthService($result); + return $this->success($authService->generateAuthData()); } + /** + * 用户登录 + */ public function login(AuthLogin $request) { $email = $request->input('email'); $password = $request->input('password'); - if ((int)admin_setting('password_limit_enable', 1)) { - $passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0); - if ($passwordErrorCount >= (int)admin_setting('password_limit_count', 5)) { - return $this->fail([429,__('There are too many password errors, please try again after :minute minutes.', [ - 'minute' => admin_setting('password_limit_expire', 60) - ])]); - } + [$success, $result] = $this->loginService->login($email, $password); + + if (!$success) { + return $this->fail($result); } - $user = User::where('email', $email)->first(); - if (!$user) { - return $this->fail([400, __('Incorrect email or password')]); - } - if (!Helper::multiPasswordVerify( - $user->password_algo, - $user->password_salt, - $password, - $user->password) - ) { - if ((int)admin_setting('password_limit_enable')) { - Cache::put( - CacheKey::get('PASSWORD_ERROR_LIMIT', $email), - (int)$passwordErrorCount + 1, - 60 * (int)admin_setting('password_limit_expire', 60) - ); - } - return $this->fail([400, __('Incorrect email or password')]); - } - - if ($user->banned) { - return $this->fail([400, __('Your account has been suspended')]); - } - - $authService = new AuthService($user); + $authService = new AuthService($result); return $this->success($authService->generateAuthData()); } + /** + * 通过token登录 + */ public function token2Login(Request $request) { + // 处理直接通过token重定向 if ($token = $request->input('token')) { $redirect = '/#/login?verify=' . $token . '&redirect=' . ($request->input('redirect', 'dashboard')); @@ -238,9 +100,9 @@ class AuthController extends Controller ); } + // 处理通过验证码登录 if ($verify = $request->input('verify')) { - $key = CacheKey::get('TEMP_TOKEN', $verify); - $userId = Cache::get($key); + $userId = $this->mailLinkService->handleTokenLogin($verify); if (!$userId) { return response()->json([ @@ -248,15 +110,14 @@ class AuthController extends Controller ], 400); } - $user = User::findOrFail($userId); + $user = \App\Models\User::find($userId); - if ($user->banned) { + if (!$user) { return response()->json([ - 'message' => __('Your account has been suspended') + 'message' => __('User not found') ], 400); } - Cache::forget($key); $authService = new AuthService($user); return response()->json([ @@ -269,6 +130,9 @@ class AuthController extends Controller ], 400); } + /** + * 获取快速登录URL + */ public function getQuickLoginUrl(Request $request) { $authorization = $request->input('auth_data') ?? $request->header('authorization'); @@ -287,38 +151,25 @@ class AuthController extends Controller ], 401); } - $code = Helper::guid(); - $key = CacheKey::get('TEMP_TOKEN', $code); - Cache::put($key, $user['id'], 60); - $redirect = '/#/login?verify=' . $code . '&redirect=' . ($request->input('redirect') ? $request->input('redirect') : 'dashboard'); - if (admin_setting('app_url')) { - $url = admin_setting('app_url') . $redirect; - } else { - $url = url($redirect); - } + $url = $this->mailLinkService->getQuickLoginUrl($user, $request->input('redirect')); return $this->success($url); } + /** + * 忘记密码处理 + */ public function forget(AuthForget $request) { - $forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $request->input('email')); - $forgetRequestLimit = (int)Cache::get($forgetRequestLimitKey); - if ($forgetRequestLimit >= 3) return $this->fail([429, __('Reset failed, Please try again later')]); - if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { - Cache::put($forgetRequestLimitKey, $forgetRequestLimit ? $forgetRequestLimit + 1 : 1, 300); - return $this->fail([400,__('Incorrect email verification code')]); + [$success, $result] = $this->loginService->resetPassword( + $request->input('email'), + $request->input('email_code'), + $request->input('password') + ); + + if (!$success) { + return $this->fail($result); } - $user = User::where('email', $request->input('email'))->first(); - if (!$user) { - return $this->fail([400,__('This email is not registered in the system')]); - } - $user->password = password_hash($request->input('password'), PASSWORD_DEFAULT); - $user->password_algo = NULL; - $user->password_salt = NULL; - if (!$user->save()) { - return $this->fail([500,__('Reset failed')]); - } - Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))); + return $this->success(true); } } diff --git a/app/Http/Controllers/V1/Passport/CommController.php b/app/Http/Controllers/V1/Passport/CommController.php index ce135fa..60b2cd7 100644 --- a/app/Http/Controllers/V1/Passport/CommController.php +++ b/app/Http/Controllers/V1/Passport/CommController.php @@ -15,14 +15,10 @@ use ReCaptcha\ReCaptcha; class CommController extends Controller { - private function isEmailVerify() - { - return $this->success((int)admin_setting('email_verify', 0) ? 1 : 0); - } public function sendEmailVerify(CommSendEmailVerify $request) { - if ((int)admin_setting('recaptcha_enable', 0)) { + if ((int) admin_setting('recaptcha_enable', 0)) { $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); if (!$recaptchaResp->isSuccess()) { @@ -63,12 +59,4 @@ class CommController extends Controller return $this->success(true); } - private function getEmailSuffix() - { - $suffix = admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT); - if (!is_array($suffix)) { - return preg_split('/,/', $suffix); - } - return $suffix; - } } diff --git a/app/Http/Controllers/V1/Server/UniProxyController.php b/app/Http/Controllers/V1/Server/UniProxyController.php index 36c358c..860199f 100644 --- a/app/Http/Controllers/V1/Server/UniProxyController.php +++ b/app/Http/Controllers/V1/Server/UniProxyController.php @@ -150,6 +150,20 @@ class UniProxyController extends Controller 'socks' => [ 'server_port' => (int) $serverPort, ], + 'naive' => [ + 'server_port' => (int) $serverPort, + 'tls' => (int) $protocolSettings['tls'], + 'tls_settings' => $protocolSettings['tls_settings'] + ], + 'http' => [ + 'server_port' => (int) $serverPort, + 'tls' => (int) $protocolSettings['tls'], + 'tls_settings' => $protocolSettings['tls_settings'] + ], + 'mieru' => [ + 'server_port' => (string) $serverPort, + 'protocol' => (int) $protocolSettings['protocol'], + ], default => [] }; @@ -163,7 +177,7 @@ class UniProxyController extends Controller } $eTag = sha1(json_encode($response)); - if (strpos($request->header('If-None-Match', '') ?? '', $eTag) !== false) { + if (strpos($request->header('If-None-Match', ''), $eTag) !== false) { return response(null, 304); } return response($response)->header('ETag', "\"{$eTag}\""); diff --git a/app/Http/Controllers/V1/Staff/NoticeController.php b/app/Http/Controllers/V1/Staff/NoticeController.php deleted file mode 100644 index cf30cb3..0000000 --- a/app/Http/Controllers/V1/Staff/NoticeController.php +++ /dev/null @@ -1,58 +0,0 @@ -get(); - return $this->success($data); - } - - public function save(NoticeSave $request) - { - $data = $request->only([ - 'title', - 'content', - 'img_url' - ]); - if (!$request->input('id')) { - if (!Notice::create($data)) { - return $this->fail([500, '创建失败']); - } - } else { - try { - Notice::find($request->input('id'))->update($data); - } catch (\Exception $e) { - \Log::error($e); - return $this->fail([500, '保存失败']); - } - } - return $this->success(true); - } - - public function drop(Request $request) - { - $request->validate([ - 'id' => 'required' - ],[ - 'id.required' => '公告ID不能为空' - ]); - - $notice = Notice::find($request->input('id')); - if (!$notice) { - return $this->fail([400202,'公告不存在']); - } - if (!$notice->delete()) { - return $this->fail([500,'公告删除失败']); - } - return $this->success(true); - } -} diff --git a/app/Http/Controllers/V1/Staff/PlanController.php b/app/Http/Controllers/V1/Staff/PlanController.php deleted file mode 100755 index 96a507e..0000000 --- a/app/Http/Controllers/V1/Staff/PlanController.php +++ /dev/null @@ -1,35 +0,0 @@ -where('plan_id', '!=', NULL) - ->where(function ($query) { - $query->where('expired_at', '>=', time()) - ->orWhere('expired_at', NULL); - }) - ->groupBy("plan_id") - ->get(); - $plans = Plan::orderBy('sort', 'ASC')->get(); - foreach ($plans as $k => $v) { - $plans[$k]->count = 0; - foreach ($counts as $kk => $vv) { - if ($plans[$k]->id === $counts[$kk]->plan_id) $plans[$k]->count = $counts[$kk]->count; - } - } - return $this->success($plans); - } -} diff --git a/app/Http/Controllers/V1/Staff/TicketController.php b/app/Http/Controllers/V1/Staff/TicketController.php deleted file mode 100644 index ae32373..0000000 --- a/app/Http/Controllers/V1/Staff/TicketController.php +++ /dev/null @@ -1,82 +0,0 @@ -input('id')) { - $ticket = Ticket::where('id', $request->input('id')) - ->first(); - if (!$ticket) { - return $this->fail([400,'工单不存在']); - } - $ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get(); - for ($i = 0; $i < count($ticket['message']); $i++) { - if ($ticket['message'][$i]['user_id'] !== $ticket->user_id) { - $ticket['message'][$i]['is_me'] = true; - } else { - $ticket['message'][$i]['is_me'] = false; - } - } - return $this->success($ticket); - } - $current = $request->input('current') ? $request->input('current') : 1; - $pageSize = $request->input('pageSize') >= 10 ? $request->input('pageSize') : 10; - $model = Ticket::orderBy('created_at', 'DESC'); - if ($request->input('status') !== NULL) { - $model->where('status', $request->input('status')); - } - $total = $model->count(); - $res = $model->forPage($current, $pageSize) - ->get(); - return response([ - 'data' => $res, - 'total' => $total - ]); - } - - public function reply(Request $request) - { - $request->validate([ - 'id' => 'required', - 'message' => 'required|string' - ],[ - 'id.required' => '工单ID不能为空', - 'message.required' => '消息不能为空' - ]); - $ticketService = new TicketService(); - $ticketService->replyByAdmin( - $request->input('id'), - $request->input('message'), - $request->user()->id - ); - return $this->success(true); - } - - public function close(Request $request) - { - - if (empty($request->input('id'))) { - return $this->fail([422,'工单ID不能为空']); - } - $ticket = Ticket::where('id', $request->input('id')) - ->first(); - if (!$ticket) { - return $this->fail([400202,'工单不存在']); - } - $ticket->status = Ticket::STATUS_CLOSED; - if (!$ticket->save()) { - return $this->fail([500, '工单关闭失败']); - } - return $this->success(true); - } -} diff --git a/app/Http/Controllers/V1/Staff/UserController.php b/app/Http/Controllers/V1/Staff/UserController.php deleted file mode 100644 index 97bd9df..0000000 --- a/app/Http/Controllers/V1/Staff/UserController.php +++ /dev/null @@ -1,102 +0,0 @@ -input('id'))) { - return $this->fail([422,'用户ID不能为空']); - } - $user = User::where('is_admin', 0) - ->where('id', $request->input('id')) - ->where('is_staff', 0) - ->first(); - if (!$user) return $this->fail([400202,'用户不存在']); - return $this->success($user); - } - - public function update(UserUpdate $request) - { - $params = $request->validated(); - $user = User::find($request->input('id')); - if (!$user) { - return $this->fail([400202,'用户不存在']); - } - if (User::where('email', $params['email'])->first() && $user->email !== $params['email']) { - return $this->fail([400201,'邮箱已被使用']); - } - if (isset($params['password'])) { - $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT); - $params['password_algo'] = NULL; - } else { - unset($params['password']); - } - if (isset($params['plan_id'])) { - $plan = Plan::find($params['plan_id']); - if (!$plan) { - return $this->fail([400202,'订阅不存在']); - } - $params['group_id'] = $plan->group_id; - } - - try { - $user->update($params); - } catch (\Exception $e) { - \Log::error($e); - return $this->fail([500,'更新失败']); - } - return $this->success(true); - } - - public function sendMail(UserSendMail $request) - { - $sortType = in_array($request->input('sort_type'), ['ASC', 'DESC']) ? $request->input('sort_type') : 'DESC'; - $sort = $request->input('sort') ? $request->input('sort') : 'created_at'; - $builder = User::orderBy($sort, $sortType); - $this->filter($request, $builder); - $users = $builder->get(); - foreach ($users as $user) { - SendEmailJob::dispatch([ - 'email' => $user->email, - 'subject' => $request->input('subject'), - 'template_name' => 'notify', - 'template_value' => [ - 'name' => admin_setting('app_name', 'XBoard'), - 'url' => admin_setting('app_url'), - 'content' => $request->input('content') - ] - ]); - } - - return $this->success(true); - } - - public function ban(Request $request) - { - $sortType = in_array($request->input('sort_type'), ['ASC', 'DESC']) ? $request->input('sort_type') : 'DESC'; - $sort = $request->input('sort') ? $request->input('sort') : 'created_at'; - $builder = User::orderBy($sort, $sortType); - $this->filter($request, $builder); - try { - $builder->update([ - 'banned' => 1 - ]); - } catch (\Exception $e) { - \Log::error($e); - return $this->fail([500,'处理上失败']); - } - - return $this->success(true); - } -} diff --git a/app/Http/Controllers/V1/User/OrderController.php b/app/Http/Controllers/V1/User/OrderController.php index 6ad6742..08a925b 100755 --- a/app/Http/Controllers/V1/User/OrderController.php +++ b/app/Http/Controllers/V1/User/OrderController.php @@ -43,16 +43,15 @@ class OrderController extends Controller $request->validate([ 'trade_no' => 'required|string', ]); - $order = Order::with('payment') + $order = Order::with(['payment','plan']) ->where('user_id', $request->user()->id) ->where('trade_no', $request->input('trade_no')) ->first(); if (!$order) { return $this->fail([400, __('Order does not exist or has been paid')]); } - $order['plan'] = Plan::find($order->plan_id); $order['try_out_plan_id'] = (int) admin_setting('try_out_plan_id'); - if (!$order['plan']) { + if (!$order->plan) { return $this->fail([400, __('Subscription plan does not exist')]); } if ($order->surplus_order_ids) { @@ -81,7 +80,7 @@ class OrderController extends Controller // Validate plan purchase $planService->validatePurchase($user, $request->input('period')); - return DB::transaction(function () use ($request, $plan, $user, $userService, $planService) { + return DB::transaction(function () use ($request, $plan, $user, $userService) { $period = $request->input('period'); $newPeriod = PlanService::getPeriodKey($period); @@ -169,12 +168,13 @@ class OrderController extends Controller ]); } $payment = Payment::find($method); - if (!$payment || $payment->enable !== 1) + if (!$payment || !$payment->enable) { return $this->fail([400, __('Payment method is not available')]); + } $paymentService = new PaymentService($payment->payment, $payment->id); $order->handling_amount = NULL; if ($payment->handling_fee_fixed || $payment->handling_fee_percent) { - $order->handling_amount = round(($order->total_amount * ($payment->handling_fee_percent / 100)) + $payment->handling_fee_fixed); + $order->handling_amount = (int) round(($order->total_amount * ($payment->handling_fee_percent / 100)) + $payment->handling_fee_fixed); } $order->payment_id = $method; if (!$order->save()) diff --git a/app/Http/Controllers/V1/User/UserController.php b/app/Http/Controllers/V1/User/UserController.php index c33f00c..5fbc733 100755 --- a/app/Http/Controllers/V1/User/UserController.php +++ b/app/Http/Controllers/V1/User/UserController.php @@ -58,11 +58,13 @@ class UserController extends Controller if (!$user) { return $this->fail([400, __('The user does not exist')]); } - if (!Helper::multiPasswordVerify( - $user->password_algo, - $user->password_salt, - $request->input('old_password'), - $user->password) + if ( + !Helper::multiPasswordVerify( + $user->password_algo, + $user->password_salt, + $request->input('old_password'), + $user->password + ) ) { return $this->fail([400, __('The old password is wrong')]); } diff --git a/app/Http/Controllers/V2/Admin/ConfigController.php b/app/Http/Controllers/V2/Admin/ConfigController.php index 48a9483..e41498d 100644 --- a/app/Http/Controllers/V2/Admin/ConfigController.php +++ b/app/Http/Controllers/V2/Admin/ConfigController.php @@ -64,12 +64,6 @@ class ConfigController extends Controller return $this->success(true); } - private function getTemplateContent(string $filename): string - { - $path = resource_path("rules/{$filename}"); - return File::exists($path) ? File::get($path) : ''; - } - public function fetch(Request $request) { $key = $request->input('key'); diff --git a/app/Http/Controllers/V2/Admin/OrderController.php b/app/Http/Controllers/V2/Admin/OrderController.php index ddc4f50..05ebdb6 100644 --- a/app/Http/Controllers/V2/Admin/OrderController.php +++ b/app/Http/Controllers/V2/Admin/OrderController.php @@ -15,6 +15,7 @@ use App\Utils\Helper; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Support\Facades\Log; class OrderController extends Controller { @@ -27,7 +28,7 @@ class OrderController extends Controller if ($order->surplus_order_ids) { $order['surplus_orders'] = Order::whereIn('id', $order->surplus_order_ids)->get(); } - $order['period'] = PlanService::getLegacyPeriod($order->period); + $order['period'] = PlanService::getLegacyPeriod((string) $order->period); return $this->success($order); } @@ -45,17 +46,21 @@ class OrderController extends Controller $this->applyFiltersAndSorts($request, $orderModel); - return response()->json( - $orderModel - ->latest('created_at') - ->paginate( - perPage: $pageSize, - page: $current - )->through(fn($order) => [ - ...$order->toArray(), - 'period' => PlanService::getLegacyPeriod($order->period) - ]), - ); + /** @var \Illuminate\Pagination\LengthAwarePaginator $paginatedResults */ + $paginatedResults = $orderModel + ->latest('created_at') + ->paginate( + perPage: $pageSize, + page: $current + ); + + $paginatedResults->getCollection()->transform(function($order) { + $orderArray = $order->toArray(); + $orderArray['period'] = PlanService::getLegacyPeriod((string) $order->period); + return $orderArray; + }); + + return response()->json($paginatedResults); } private function applyFiltersAndSorts(Request $request, Builder $builder): void @@ -112,8 +117,8 @@ class OrderController extends Controller 'lte' => '<=', 'like' => 'like', 'notlike' => 'not like', - 'null' => static fn($q) => $q->whereNull($queryField), - 'notnull' => static fn($q) => $q->whereNotNull($queryField), + 'null' => static fn($q) => $q->whereNull($field), + 'notnull' => static fn($q) => $q->whereNotNull($field), default => 'like' }, match (strtolower($operator)) { 'like', 'notlike' => "%{$filterValue}%", @@ -184,7 +189,7 @@ class OrderController extends Controller try { $order->update($params); } catch (\Exception $e) { - \Log::error($e); + Log::error($e); return $this->fail([500, '更新失败']); } @@ -215,11 +220,12 @@ class OrderController extends Controller $orderService = new OrderService($order); $order->user_id = $user->id; $order->plan_id = $plan->id; - $order->period = PlanService::getPeriodKey($request->input('period')); + $period = $request->input('period'); + $order->period = (int) PlanService::getPeriodKey((string) $period); $order->trade_no = Helper::guid(); $order->total_amount = $request->input('total_amount'); - if (PlanService::getPeriodKey($order->period) === Plan::PERIOD_RESET_TRAFFIC) { + if (PlanService::getPeriodKey((string) $order->period) === Plan::PERIOD_RESET_TRAFFIC) { $order->type = Order::TYPE_RESET_TRAFFIC; } else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) { $order->type = Order::TYPE_UPGRADE; diff --git a/app/Http/Controllers/V2/Admin/PlanController.php b/app/Http/Controllers/V2/Admin/PlanController.php index 9d7063a..63c817f 100644 --- a/app/Http/Controllers/V2/Admin/PlanController.php +++ b/app/Http/Controllers/V2/Admin/PlanController.php @@ -8,6 +8,7 @@ use App\Models\Plan; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; class PlanController extends Controller { @@ -58,7 +59,7 @@ class PlanController extends Controller return $this->success(true); } catch (\Exception $e) { DB::rollBack(); - \Log::error($e); + Log::error($e); return $this->fail([500, '保存失败']); } } @@ -76,12 +77,12 @@ class PlanController extends Controller if (User::where('plan_id', $request->input('id'))->first()) { return $this->fail([400201, '该订阅下存在用户无法删除']); } - if ($request->input('id')) { - $plan = Plan::find($request->input('id')); - if (!$plan) { - return $this->fail([400202, '该订阅不存在']); - } + + $plan = Plan::find($request->input('id')); + if (!$plan) { + return $this->fail([400202, '该订阅不存在']); } + return $this->success($plan->delete()); } @@ -101,7 +102,7 @@ class PlanController extends Controller try { $plan->update($updateData); } catch (\Exception $e) { - \Log::error($e); + Log::error($e); return $this->fail([500, '保存失败']); } @@ -124,7 +125,7 @@ class PlanController extends Controller DB::commit(); } catch (\Exception $e) { DB::rollBack(); - \Log::error($e); + Log::error($e); return $this->fail([500, '保存失败']); } return $this->success(true); diff --git a/app/Http/Controllers/V2/Admin/Server/GroupController.php b/app/Http/Controllers/V2/Admin/Server/GroupController.php index a8c96fc..83a53ac 100644 --- a/app/Http/Controllers/V2/Admin/Server/GroupController.php +++ b/app/Http/Controllers/V2/Admin/Server/GroupController.php @@ -14,15 +14,15 @@ class GroupController extends Controller { public function fetch(Request $request): JsonResponse { - $serverGroups = ServerGroup::query() ->orderByDesc('id') ->withCount('users') - ->get() - ->transform(function ($group) { - $group->server_count = $group->servers()->count(); - return $group; - }); + ->get(); + + // 只在需要时手动加载server_count + $serverGroups->each(function ($group) { + $group->setAttribute('server_count', $group->server_count); + }); return $this->success($serverGroups); } diff --git a/app/Http/Controllers/V2/Admin/Server/ManageController.php b/app/Http/Controllers/V2/Admin/Server/ManageController.php index 2def3af..762ecd9 100644 --- a/app/Http/Controllers/V2/Admin/Server/ManageController.php +++ b/app/Http/Controllers/V2/Admin/Server/ManageController.php @@ -10,12 +10,13 @@ use App\Models\ServerGroup; use App\Services\ServerService; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; class ManageController extends Controller { public function getNodes(Request $request) { - $servers = collect(ServerService::getAllServers())->map(function ($item) { + $servers = ServerService::getAllServers()->map(function ($item) { $item['groups'] = ServerGroup::whereIn('id', $item['group_ids'])->get(['name', 'id']); $item['parent'] = $item->parent; return $item; @@ -41,7 +42,7 @@ class ManageController extends Controller DB::commit(); } catch (\Exception $e) { DB::rollBack(); - \Log::error($e); + Log::error($e); return $this->fail([500, '保存失败']); } @@ -60,7 +61,7 @@ class ManageController extends Controller $server->update($params); return $this->success(true); } catch (\Exception $e) { - \Log::error($e); + Log::error($e); return $this->fail([500, '保存失败']); } } @@ -69,7 +70,7 @@ class ManageController extends Controller Server::create($params); return $this->success(true); } catch (\Exception $e) { - \Log::error($e); + Log::error($e); return $this->fail([500, '创建失败']); } @@ -83,7 +84,7 @@ class ManageController extends Controller 'show' => 'integer', ]); - if (Server::where('id', $request->id)->update(['show' => $request->show]) === false) { + if (!Server::where('id', $request->id)->update(['show' => $request->show])) { return $this->fail([500, '保存失败']); } return $this->success(true); diff --git a/app/Http/Controllers/V2/Admin/StatController.php b/app/Http/Controllers/V2/Admin/StatController.php index 5eac168..e7d615c 100644 --- a/app/Http/Controllers/V2/Admin/StatController.php +++ b/app/Http/Controllers/V2/Admin/StatController.php @@ -25,8 +25,7 @@ class StatController extends Controller { // 获取在线节点数 $onlineNodes = Server::all()->filter(function ($server) { - $server->loadServerStatus(); - return $server->is_online; + return !!$server->is_online; })->count(); // 获取在线设备数和在线用户数 $onlineDevices = User::where('t', '>=', time() - 600) @@ -268,8 +267,7 @@ class StatController extends Controller // 获取在线节点数 $onlineNodes = Server::all()->filter(function ($server) { - $server->loadServerStatus(); - return $server->is_online; + return !!$server->is_online; })->count(); // 获取在线设备数和在线用户数 diff --git a/app/Http/Controllers/V2/Admin/TicketController.php b/app/Http/Controllers/V2/Admin/TicketController.php index 039570f..ca6d8c4 100644 --- a/app/Http/Controllers/V2/Admin/TicketController.php +++ b/app/Http/Controllers/V2/Admin/TicketController.php @@ -55,13 +55,10 @@ class TicketController extends Controller if (!$ticket) { return $this->fail([400202, '工单不存在']); } - $ticket->user = UserController::transformUserData($ticket->user); - $ticket->messages->each(function ($message) use ($ticket) { - $message->is_me = $message->user_id !== $ticket->user_id; + $result = $ticket->toArray(); + $result['user'] = UserController::transformUserData($ticket->user); - }); - - return $this->success($ticket); + return $this->success($result); } /** @@ -91,12 +88,16 @@ class TicketController extends Controller perPage: $request->integer('pageSize', 10), page: $request->integer('current', 1) ); - $tickets->getCollection()->transform(function ($ticket) { - $ticket->user = UserController::transformUserData($ticket->user); - return $ticket; - }); + + // 获取items然后映射转换 + $items = collect($tickets->items())->map(function ($ticket) { + $ticketData = $ticket->toArray(); + $ticketData['user'] = UserController::transformUserData($ticket->user); + return $ticketData; + })->all(); + return response([ - 'data' => $tickets->items(), + 'data' => $items, 'total' => $tickets->total() ]); } @@ -137,4 +138,19 @@ class TicketController extends Controller return $this->fail([500101, '关闭失败']); } } + + public function show($ticketId) + { + $ticket = Ticket::with([ + 'user', + 'messages' => function ($query) { + $query->with(['user']); // 如果需要用户信息 + } + ])->findOrFail($ticketId); + + // 自动包含 is_me 属性 + return response()->json([ + 'data' => $ticket + ]); + } } diff --git a/app/Http/Controllers/V2/Admin/UserController.php b/app/Http/Controllers/V2/Admin/UserController.php index 6b28c4c..9b8f3c9 100644 --- a/app/Http/Controllers/V2/Admin/UserController.php +++ b/app/Http/Controllers/V2/Admin/UserController.php @@ -81,7 +81,7 @@ class UserController extends Controller // 处理关联查询 if (str_contains($field, '.')) { [$relation, $relationField] = explode('.', $field); - $query->whereHas($relation, function($q) use ($relationField, $value) { + $query->whereHas($relation, function ($q) use ($relationField, $value) { if (is_array($value)) { $q->whereIn($relationField, $value); } else if (is_string($value) && str_contains($value, ':')) { @@ -163,7 +163,8 @@ class UserController extends Controller $users = $userModel->orderBy('id', 'desc') ->paginate($pageSize, ['*'], 'page', $current); - $users->getCollection()->transform(function ($user) { + /** @phpstan-ignore-next-line */ + $users->getCollection()->transform(function ($user): array { return self::transformUserData($user); }); @@ -177,13 +178,14 @@ class UserController extends Controller * Transform user data for response * * @param User $user - * @return User + * @return array */ - public static function transformUserData(User $user): User + public static function transformUserData(User $user): array { - $user->subscribe_url = Helper::getSubscribeUrl($user->token); - $user->balance = $user->balance / 100; - $user->commission_balance = $user->commission_balance / 100; + $user = $user->toArray(); + $user['balance'] = $user['balance'] / 100; + $user['commission_balance'] = $user['commission_balance'] / 100; + $user['subscribe_url'] = Helper::getSubscribeUrl($user['token']); return $user; } @@ -235,7 +237,7 @@ class UserController extends Controller if (isset($params['banned']) && (int) $params['banned'] === 1) { $authService = new AuthService($user); - $authService->removeSession(); + $authService->removeAllSessions(); } if (isset($params['balance'])) { $params['balance'] = $params['balance'] * 100; @@ -263,7 +265,7 @@ class UserController extends Controller { ini_set('memory_limit', '-1'); gc_enable(); // 启用垃圾回收 - + // 优化查询:使用with预加载plan关系,避免N+1问题 $query = User::with('plan:id,name') ->orderBy('id', 'asc') @@ -278,18 +280,18 @@ class UserController extends Controller 'token', 'plan_id' ]); - + $this->applyFiltersAndSorts($request, $query); - + $filename = 'users_' . date('Y-m-d_His') . '.csv'; - - return response()->streamDownload(function() use ($query) { + + return response()->streamDownload(function () use ($query) { // 打开输出流 $output = fopen('php://output', 'w'); - + // 添加BOM标记,确保Excel正确显示中文 - fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); - + fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF)); + // 写入CSV头部 fputcsv($output, [ '邮箱', @@ -301,9 +303,9 @@ class UserController extends Controller '订阅计划', '订阅地址' ]); - + // 分批处理数据以减少内存使用 - $query->chunk(500, function($users) use ($output) { + $query->chunk(500, function ($users) use ($output) { foreach ($users as $user) { try { $row = [ @@ -325,11 +327,11 @@ class UserController extends Controller continue; // 继续处理下一条记录 } } - + // 清理内存 gc_collect_cycles(); }); - + fclose($output); }, $filename, [ 'Content-Type' => 'text/csv; charset=UTF-8', diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index d8db93e..4801da4 100755 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -11,7 +11,7 @@ class Kernel extends HttpKernel * * These middleware are run during every request to your application. * - * @var array + * @var array */ protected $middleware = [ \Illuminate\Http\Middleware\HandleCors::class, @@ -26,7 +26,7 @@ class Kernel extends HttpKernel /** * The application's route middleware groups. * - * @var array + * @var array> */ protected $middlewareGroups = [ 'web' => [ @@ -57,7 +57,7 @@ class Kernel extends HttpKernel * * These middleware may be assigned to groups or used individually. * - * @var array + * @var array */ protected $middlewareAliases = [ 'auth' => \App\Http\Middleware\Authenticate::class, @@ -84,7 +84,7 @@ class Kernel extends HttpKernel * * This forces non-global middleware to always be in the given order. * - * @var array + * @var array */ protected $middlewarePriority = [ \Illuminate\Session\Middleware\StartSession::class, diff --git a/app/Http/Middleware/Admin.php b/app/Http/Middleware/Admin.php index b39f49d..1a63b4f 100755 --- a/app/Http/Middleware/Admin.php +++ b/app/Http/Middleware/Admin.php @@ -5,6 +5,7 @@ namespace App\Http\Middleware; use App\Exceptions\ApiException; use Illuminate\Support\Facades\Auth; use Closure; +use App\Models\User; class Admin { @@ -17,15 +18,13 @@ class Admin */ public function handle($request, Closure $next) { - if (!Auth::guard('sanctum')->check()) { - throw new ApiException('未登录或登陆已过期', 403); - } - + /** @var User|null $user */ $user = Auth::guard('sanctum')->user(); - if (!$user->is_admin) { - throw new ApiException('无管理员权限', 403); + + if (!$user || !$user->is_admin) { + return response()->json(['message' => 'Unauthorized'], 403); } - + return $next($request); } } diff --git a/app/Http/Middleware/CheckForMaintenanceMode.php b/app/Http/Middleware/CheckForMaintenanceMode.php index 35b9824..53fcdd5 100755 --- a/app/Http/Middleware/CheckForMaintenanceMode.php +++ b/app/Http/Middleware/CheckForMaintenanceMode.php @@ -2,16 +2,17 @@ namespace App\Http\Middleware; -use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware; +use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance; -class CheckForMaintenanceMode extends Middleware +class CheckForMaintenanceMode extends PreventRequestsDuringMaintenance { /** - * The URIs that should be reachable while maintenance mode is enabled. - * - * @var array + * 维护模式白名单URI + * @var array */ protected $except = [ - // + // 示例: + // '/api/health-check', + // '/status' ]; } diff --git a/app/Http/Middleware/EncryptCookies.php b/app/Http/Middleware/EncryptCookies.php index 033136a..31e9d1a 100755 --- a/app/Http/Middleware/EncryptCookies.php +++ b/app/Http/Middleware/EncryptCookies.php @@ -7,9 +7,8 @@ use Illuminate\Cookie\Middleware\EncryptCookies as Middleware; class EncryptCookies extends Middleware { /** - * The names of the cookies that should not be encrypted. - * - * @var array + * 不需要加密的Cookie名称列表 + * @var array */ protected $except = [ // diff --git a/app/Http/Middleware/TrimStrings.php b/app/Http/Middleware/TrimStrings.php index 5a50e7b..fb507a4 100755 --- a/app/Http/Middleware/TrimStrings.php +++ b/app/Http/Middleware/TrimStrings.php @@ -7,12 +7,13 @@ use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware; class TrimStrings extends Middleware { /** - * The names of the attributes that should not be trimmed. - * - * @var array + * 不需要去除前后空格的字段名 + * @var array */ protected $except = [ 'password', 'password_confirmation', + 'encrypted_data', + 'signature' ]; } diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 392efca..83c5400 100755 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -8,9 +8,8 @@ use Illuminate\Http\Request; class TrustProxies extends Middleware { /** - * The trusted proxies for this application. - * - * @var array|string + * 可信代理列表 + * @var array|string|null */ protected $proxies = [ "173.245.48.0/20", @@ -36,8 +35,7 @@ class TrustProxies extends Middleware ]; /** - * The headers that should be used to detect proxies. - * + * 代理头映射 * @var int */ protected $headers = diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php index 324a166..9e7c0bd 100755 --- a/app/Http/Middleware/VerifyCsrfToken.php +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -7,16 +7,14 @@ use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** - * Indicates whether the XSRF-TOKEN cookie should be set on the response. - * + * 是否在响应中设置XSRF-TOKEN cookie * @var bool */ protected $addHttpCookie = true; /** - * The URIs that should be excluded from CSRF verification. - * - * @var array + * 不需要CSRF验证的URI列表 + * @var array */ protected $except = [ // diff --git a/app/Http/Requests/Admin/ServerSave.php b/app/Http/Requests/Admin/ServerSave.php index 54fc40e..b4d40b7 100644 --- a/app/Http/Requests/Admin/ServerSave.php +++ b/app/Http/Requests/Admin/ServerSave.php @@ -54,7 +54,19 @@ class ServerSave extends FormRequest 'reality_settings.short_id' => 'nullable|string', ], 'socks' => [ - ] + ], + 'naive' => [ + 'tls' => 'required|integer', + 'tls_settings' => 'nullable|array', + ], + 'http' => [ + 'tls' => 'required|integer', + 'tls_settings' => 'nullable|array', + ], + 'mieru' => [ + 'transport' => 'required|string', + 'multiplexing' => 'required|string', + ], ]; private function getBaseRules(): array diff --git a/app/Http/Resources/OrderResource.php b/app/Http/Resources/OrderResource.php index d2d5ff8..ae3e6e4 100644 --- a/app/Http/Resources/OrderResource.php +++ b/app/Http/Resources/OrderResource.php @@ -2,10 +2,14 @@ namespace App\Http\Resources; +use App\Models\Order; use App\Services\PlanService; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; +/** + * @mixin Order + */ class OrderResource extends JsonResource { /** @@ -17,8 +21,8 @@ class OrderResource extends JsonResource { return [ ...parent::toArray($request), - 'period' => PlanService::getLegacyPeriod($this->period), - 'plan' => PlanResource::make($this->plan), + 'period' => PlanService::getLegacyPeriod((string)$this->period), + 'plan' => $this->whenLoaded('plan', fn() => PlanResource::make($this->plan)), ]; } } diff --git a/app/Http/Routes/V1/ClientRoute.php b/app/Http/Routes/V1/ClientRoute.php index 8c38cfb..ad13989 100644 --- a/app/Http/Routes/V1/ClientRoute.php +++ b/app/Http/Routes/V1/ClientRoute.php @@ -1,6 +1,8 @@ 'client' ], function ($router) { // Client - $router->get('/subscribe', 'V1\\Client\\ClientController@subscribe')->name('client.subscribe.legacy'); + $router->get('/subscribe', [ClientController::class, 'subscribe'])->name('client.subscribe.legacy'); // App - $router->get('/app/getConfig', 'V1\\Client\\AppController@getConfig'); - $router->get('/app/getVersion', 'V1\\Client\\AppController@getVersion'); + $router->get('/app/getConfig', [AppController::class, 'getConfig']); + $router->get('/app/getVersion', [AppController::class, 'getVersion']); }); } } diff --git a/app/Http/Routes/V1/PassportRoute.php b/app/Http/Routes/V1/PassportRoute.php index dc405e8..3134b96 100644 --- a/app/Http/Routes/V1/PassportRoute.php +++ b/app/Http/Routes/V1/PassportRoute.php @@ -1,6 +1,8 @@ 'passport' ], function ($router) { // Auth - $router->post('/auth/register', 'V1\\Passport\\AuthController@register'); - $router->post('/auth/login', 'V1\\Passport\\AuthController@login'); - $router->get ('/auth/token2Login', 'V1\\Passport\\AuthController@token2Login'); - $router->post('/auth/forget', 'V1\\Passport\\AuthController@forget'); - $router->post('/auth/getQuickLoginUrl', 'V1\\Passport\\AuthController@getQuickLoginUrl'); - $router->post('/auth/loginWithMailLink', 'V1\\Passport\\AuthController@loginWithMailLink'); + $router->post('/auth/register', [AuthController::class, 'register']); + $router->post('/auth/login', [AuthController::class, 'login']); + $router->get('/auth/token2Login', [AuthController::class, 'token2Login']); + $router->post('/auth/forget', [AuthController::class, 'forget']); + $router->post('/auth/getQuickLoginUrl', [AuthController::class, 'getQuickLoginUrl']); + $router->post('/auth/loginWithMailLink', [AuthController::class, 'loginWithMailLink']); // Comm - $router->post('/comm/sendEmailVerify', 'V1\\Passport\\CommController@sendEmailVerify'); - $router->post('/comm/pv', 'V1\\Passport\\CommController@pv'); + $router->post('/comm/sendEmailVerify', [CommController::class, 'sendEmailVerify']); + $router->post('/comm/pv', [CommController::class, 'pv']); }); } } diff --git a/app/Http/Routes/V1/StaffRoute.php b/app/Http/Routes/V1/StaffRoute.php deleted file mode 100644 index 3889bee..0000000 --- a/app/Http/Routes/V1/StaffRoute.php +++ /dev/null @@ -1,32 +0,0 @@ -group([ - 'prefix' => 'staff', - 'middleware' => 'staff' - ], function ($router) { - // Ticket - // $router->get ('/ticket/fetch', 'V1\\Staff\\TicketController@fetch'); - // $router->post('/ticket/reply', 'V1\\Staff\\TicketController@reply'); - // $router->post('/ticket/close', 'V1\\Staff\\TicketController@close'); - // // User - // $router->post('/user/update', 'V1\\Staff\\UserController@update'); - // $router->get ('/user/getUserInfoById', 'V1\\Staff\\UserController@getUserInfoById'); - // $router->post('/user/sendMail', 'V1\\Staff\\UserController@sendMail'); - // $router->post('/user/ban', 'V1\\Staff\\UserController@ban'); - // // Plan - // $router->get ('/plan/fetch', 'V1\\Staff\\PlanController@fetch'); - // // Notice - // $router->get ('/notice/fetch', 'V1\\Admin\\NoticeController@fetch'); - // $router->post('/notice/save', 'V1\\Admin\\NoticeController@save'); - // $router->post('/notice/update', 'V1\\Admin\\NoticeController@update'); - // $router->post('/notice/drop', 'V1\\Admin\\NoticeController@drop'); - }); - } -} diff --git a/app/Http/Routes/V1/UserRoute.php b/app/Http/Routes/V1/UserRoute.php index 839a552..578f64d 100644 --- a/app/Http/Routes/V1/UserRoute.php +++ b/app/Http/Routes/V1/UserRoute.php @@ -1,6 +1,18 @@ 'user' ], function ($router) { // User - $router->get ('/resetSecurity', 'V1\\User\\UserController@resetSecurity'); - $router->get ('/info', 'V1\\User\\UserController@info'); - $router->post('/changePassword', 'V1\\User\\UserController@changePassword'); - $router->post('/update', 'V1\\User\\UserController@update'); - $router->get ('/getSubscribe', 'V1\\User\\UserController@getSubscribe'); - $router->get ('/getStat', 'V1\\User\\UserController@getStat'); - $router->get ('/checkLogin', 'V1\\User\\UserController@checkLogin'); - $router->post('/transfer', 'V1\\User\\UserController@transfer'); - $router->post('/getQuickLoginUrl', 'V1\\User\\UserController@getQuickLoginUrl'); - $router->get ('/getActiveSession', 'V1\\User\\UserController@getActiveSession'); - $router->post('/removeActiveSession', 'V1\\User\\UserController@removeActiveSession'); + $router->get('/resetSecurity', [UserController::class, 'resetSecurity']); + $router->get('/info', [UserController::class, 'info']); + $router->post('/changePassword', [UserController::class, 'changePassword']); + $router->post('/update', [UserController::class, 'update']); + $router->get('/getSubscribe', [UserController::class, 'getSubscribe']); + $router->get('/getStat', [UserController::class, 'getStat']); + $router->get('/checkLogin', [UserController::class, 'checkLogin']); + $router->post('/transfer', [UserController::class, 'transfer']); + $router->post('/getQuickLoginUrl', [UserController::class, 'getQuickLoginUrl']); + $router->get('/getActiveSession', [UserController::class, 'getActiveSession']); + $router->post('/removeActiveSession', [UserController::class, 'removeActiveSession']); // Order - $router->post('/order/save', 'V1\\User\\OrderController@save'); - $router->post('/order/checkout', 'V1\\User\\OrderController@checkout'); - $router->get ('/order/check', 'V1\\User\\OrderController@check'); - $router->get ('/order/detail', 'V1\\User\\OrderController@detail'); - $router->get ('/order/fetch', 'V1\\User\\OrderController@fetch'); - $router->get ('/order/getPaymentMethod', 'V1\\User\\OrderController@getPaymentMethod'); - $router->post('/order/cancel', 'V1\\User\\OrderController@cancel'); + $router->post('/order/save', [OrderController::class, 'save']); + $router->post('/order/checkout', [OrderController::class, 'checkout']); + $router->get('/order/check', [OrderController::class, 'check']); + $router->get('/order/detail', [OrderController::class, 'detail']); + $router->get('/order/fetch', [OrderController::class, 'fetch']); + $router->get('/order/getPaymentMethod', [OrderController::class, 'getPaymentMethod']); + $router->post('/order/cancel', [OrderController::class, 'cancel']); // Plan - $router->get ('/plan/fetch', 'V1\\User\\PlanController@fetch'); + $router->get('/plan/fetch', [PlanController::class, 'fetch']); // Invite - $router->get ('/invite/save', 'V1\\User\\InviteController@save'); - $router->get ('/invite/fetch', 'V1\\User\\InviteController@fetch'); - $router->get ('/invite/details', 'V1\\User\\InviteController@details'); + $router->get('/invite/save', [InviteController::class, 'save']); + $router->get('/invite/fetch', [InviteController::class, 'fetch']); + $router->get('/invite/details', [InviteController::class, 'details']); // Notice - $router->get ('/notice/fetch', 'V1\\User\\NoticeController@fetch'); + $router->get('/notice/fetch', [NoticeController::class, 'fetch']); // Ticket - $router->post('/ticket/reply', 'V1\\User\\TicketController@reply'); - $router->post('/ticket/close', 'V1\\User\\TicketController@close'); - $router->post('/ticket/save', 'V1\\User\\TicketController@save'); - $router->get ('/ticket/fetch', 'V1\\User\\TicketController@fetch'); - $router->post('/ticket/withdraw', 'V1\\User\\TicketController@withdraw'); + $router->post('/ticket/reply', [TicketController::class, 'reply']); + $router->post('/ticket/close', [TicketController::class, 'close']); + $router->post('/ticket/save', [TicketController::class, 'save']); + $router->get('/ticket/fetch', [TicketController::class, 'fetch']); + $router->post('/ticket/withdraw', [TicketController::class, 'withdraw']); // Server - $router->get ('/server/fetch', 'V1\\User\\ServerController@fetch'); + $router->get('/server/fetch', [ServerController::class, 'fetch']); // Coupon - $router->post('/coupon/check', 'V1\\User\\CouponController@check'); + $router->post('/coupon/check', [CouponController::class, 'check']); // Telegram - $router->get ('/telegram/getBotInfo', 'V1\\User\\TelegramController@getBotInfo'); + $router->get('/telegram/getBotInfo', [TelegramController::class, 'getBotInfo']); // Comm - $router->get ('/comm/config', 'V1\\User\\CommController@config'); - $router->Post('/comm/getStripePublicKey', 'V1\\User\\CommController@getStripePublicKey'); + $router->get('/comm/config', [CommController::class, 'config']); + $router->Post('/comm/getStripePublicKey', [CommController::class, 'getStripePublicKey']); // Knowledge - $router->get ('/knowledge/fetch', 'V1\\User\\KnowledgeController@fetch'); - $router->get ('/knowledge/getCategory', 'V1\\User\\KnowledgeController@getCategory'); + $router->get('/knowledge/fetch', [KnowledgeController::class, 'fetch']); + $router->get('/knowledge/getCategory', [KnowledgeController::class, 'getCategory']); // Stat - $router->get ('/stat/getTrafficLog', 'V1\\User\\StatController@getTrafficLog'); + $router->get('/stat/getTrafficLog', [StatController::class, 'getTrafficLog']); }); } } diff --git a/app/Http/Routes/V2/PassportRoute.php b/app/Http/Routes/V2/PassportRoute.php index d45fc65..ed91d81 100644 --- a/app/Http/Routes/V2/PassportRoute.php +++ b/app/Http/Routes/V2/PassportRoute.php @@ -1,6 +1,8 @@ 'passport' ], function ($router) { // Auth - $router->post('/auth/register', 'V1\\Passport\\AuthController@register'); - $router->post('/auth/login', 'V1\\Passport\\AuthController@login'); - $router->get ('/auth/token2Login', 'V1\\Passport\\AuthController@token2Login'); - $router->post('/auth/forget', 'V1\\Passport\\AuthController@forget'); - $router->post('/auth/getQuickLoginUrl', 'V1\\Passport\\AuthController@getQuickLoginUrl'); - $router->post('/auth/loginWithMailLink', 'V1\\Passport\\AuthController@loginWithMailLink'); + $router->post('/auth/register', [AuthController::class, 'register']); + $router->post('/auth/login', [AuthController::class, 'login']); + $router->get ('/auth/token2Login', [AuthController::class, 'token2Login']); + $router->post('/auth/forget', [AuthController::class, 'forget']); + $router->post('/auth/getQuickLoginUrl', [AuthController::class, 'getQuickLoginUrl']); + $router->post('/auth/loginWithMailLink', [AuthController::class, 'loginWithMailLink']); // Comm - $router->post('/comm/sendEmailVerify', 'V1\\Passport\\CommController@sendEmailVerify'); - $router->post('/comm/pv', 'V1\\Passport\\CommController@pv'); + $router->post('/comm/sendEmailVerify', [CommController::class, 'sendEmailVerify']); + $router->post('/comm/pv', [CommController::class, 'pv']); }); } } diff --git a/app/Http/Routes/V2/UserRoute.php b/app/Http/Routes/V2/UserRoute.php index ceed9bc..38bc12f 100644 --- a/app/Http/Routes/V2/UserRoute.php +++ b/app/Http/Routes/V2/UserRoute.php @@ -1,6 +1,7 @@ 'user' ], function ($router) { // User - $router->get('/resetSecurity', 'V1\\User\\UserController@resetSecurity'); - $router->get('/info', 'V1\\User\\UserController@info'); + $router->get('/resetSecurity', [UserController::class, 'resetSecurity']); + $router->get('/info', [UserController::class, 'info']); }); } } diff --git a/app/Logging/MysqlLoggerHandler.php b/app/Logging/MysqlLoggerHandler.php index dfe178a..eb0b09e 100644 --- a/app/Logging/MysqlLoggerHandler.php +++ b/app/Logging/MysqlLoggerHandler.php @@ -17,28 +17,28 @@ class MysqlLoggerHandler extends AbstractProcessingHandler protected function write(LogRecord $record): void { $record = $record->toArray(); - try{ - if(isset($record['context']['exception']) && is_object($record['context']['exception'])){ + try { + if (isset($record['context']['exception']) && is_object($record['context']['exception'])) { $record['context']['exception'] = (array)$record['context']['exception']; } - $record['request_data'] = request()->all() ??[]; + + $record['request_data'] = request()->all(); + $log = [ 'title' => $record['message'], 'level' => $record['level_name'], - 'host' => $record['request_host'] ?? request()->getSchemeAndHttpHost(), - 'uri' => $record['request_uri'] ?? request()->getRequestUri(), - 'method' => $record['request_method'] ?? request()->getMethod(), + 'host' => $record['extra']['request_host'] ?? request()->getSchemeAndHttpHost(), + 'uri' => $record['extra']['request_uri'] ?? request()->getRequestUri(), + 'method' => $record['extra']['request_method'] ?? request()->getMethod(), 'ip' => request()->getClientIp(), - 'data' => json_encode($record['request_data']) , - 'context' => isset($record['context']) ? json_encode($record['context']) : '', + 'data' => json_encode($record['request_data']), + 'context' => json_encode($record['context']), 'created_at' => $record['datetime']->getTimestamp(), 'updated_at' => $record['datetime']->getTimestamp(), ]; - LogModel::insert( - $log - ); - }catch (\Exception $e){ + LogModel::insert($log); + } catch (\Exception $e) { // Log::channel('daily')->error($e->getMessage().$e->getFile().$e->getTraceAsString()); } } diff --git a/app/Models/Order.php b/app/Models/Order.php index 593c9a1..4ee0b14 100755 --- a/app/Models/Order.php +++ b/app/Models/Order.php @@ -3,7 +3,38 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +/** + * App\Models\Order + * + * @property int $id + * @property int $user_id + * @property int $plan_id + * @property int|null $payment_id + * @property int $period + * @property string $trade_no + * @property int $total_amount + * @property int|null $handling_amount + * @property int|null $balance_amount + * @property int $type + * @property int $status + * @property array|null $surplus_order_ids + * @property int|null $coupon_id + * @property int $created_at + * @property int $updated_at + * @property int|null $commission_status + * @property int|null $invite_user_id + * @property int|null $actual_commission_balance + * @property int|null $commission_rate + * @property int|null $commission_auto_check + * + * @property-read Plan $plan + * @property-read Payment|null $payment + * @property-read User $user + * @property-read \Illuminate\Database\Eloquent\Collection $commission_log + */ class Order extends Model { protected $table = 'v2_order'; @@ -12,7 +43,8 @@ class Order extends Model protected $casts = [ 'created_at' => 'timestamp', 'updated_at' => 'timestamp', - 'surplus_order_ids' => 'array' + 'surplus_order_ids' => 'array', + 'handling_amount' => 'integer' ]; const STATUS_PENDING = 0; // 待支付 @@ -40,21 +72,34 @@ class Order extends Model self::TYPE_RESET_TRAFFIC => '流量重置', ]; - public function payment() + /** + * 获取与订单关联的支付方式 + */ + public function payment(): BelongsTo { return $this->belongsTo(Payment::class, 'payment_id', 'id'); } - public function user() + /** + * 获取与订单关联的用户 + */ + public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id', 'id'); } - public function plan() + + /** + * 获取与订单关联的套餐 + */ + public function plan(): BelongsTo { - return $this->belongsTo(Plan::class); + return $this->belongsTo(Plan::class, 'plan_id', 'id'); } - public function commission_log() + /** + * 获取与订单关联的佣金记录 + */ + public function commission_log(): HasMany { return $this->hasMany(CommissionLog::class, 'trade_no', 'trade_no'); } diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 5830367..fec8b00 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -12,6 +12,7 @@ class Payment extends Model protected $casts = [ 'created_at' => 'timestamp', 'updated_at' => 'timestamp', - 'config' => 'array' + 'config' => 'array', + 'enable' => 'boolean' ]; } diff --git a/app/Models/Plan.php b/app/Models/Plan.php index ba48ef1..84740af 100755 --- a/app/Models/Plan.php +++ b/app/Models/Plan.php @@ -7,7 +7,31 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasMany; use InvalidArgumentException; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Relations\HasOne; +/** + * App\Models\Plan + * + * @property int $id + * @property string $name 套餐名称 + * @property int|null $group_id 权限组ID + * @property int $transfer_enable 流量(KB) + * @property int|null $speed_limit 速度限制Mbps + * @property bool $show 是否显示 + * @property bool $renew 是否允许续费 + * @property bool $sell 是否允许购买 + * @property array|null $prices 价格配置 + * @property int $sort 排序 + * @property string|null $content 套餐描述 + * @property int $reset_traffic_method 流量重置方式 + * @property int|null $capacity_limit 订阅人数限制 + * @property int|null $device_limit 设备数量限制 + * @property int $created_at + * @property int $updated_at + * + * @property-read ServerGroup|null $group 关联的权限组 + * @property-read \Illuminate\Database\Eloquent\Collection $order 关联的订单 + */ class Plan extends Model { use HasFactory; @@ -16,12 +40,12 @@ class Plan extends Model protected $dateFormat = 'U'; // 定义流量重置方式 - public const RESET_TRAFFIC_FOLLOW_SYSTEM = 0; // 跟随系统设置 - public const RESET_TRAFFIC_FIRST_DAY_MONTH = 1; // 每月1号 - public const RESET_TRAFFIC_MONTHLY = 2; // 按月重置 - public const RESET_TRAFFIC_NEVER = 3; // 不重置 - public const RESET_TRAFFIC_FIRST_DAY_YEAR = 4; // 每年1月1日 - public const RESET_TRAFFIC_YEARLY = 5; // 按年重置 + public const RESET_TRAFFIC_FOLLOW_SYSTEM = null; // 跟随系统设置 + public const RESET_TRAFFIC_FIRST_DAY_MONTH = 0; // 每月1号 + public const RESET_TRAFFIC_MONTHLY = 1; // 按月重置 + public const RESET_TRAFFIC_NEVER = 2; // 不重置 + public const RESET_TRAFFIC_FIRST_DAY_YEAR = 3; // 每年1月1日 + public const RESET_TRAFFIC_YEARLY = 4; // 按年重置 // 定义价格类型 public const PRICE_TYPE_RESET_TRAFFIC = 'reset_traffic'; // 重置流量价格 @@ -346,7 +370,7 @@ class Plan extends Model return $this->hasMany(User::class); } - public function group() + public function group(): HasOne { return $this->hasOne(ServerGroup::class, 'id', 'group_id'); } @@ -384,4 +408,9 @@ class Plan extends Model $prices[self::PRICE_TYPE_RESET_TRAFFIC] = max(0, $price); $this->prices = $prices; } + + public function order(): HasMany + { + return $this->hasMany(Order::class); + } } \ No newline at end of file diff --git a/app/Models/Server.php b/app/Models/Server.php index 02b51da..fdc092e 100644 --- a/app/Models/Server.php +++ b/app/Models/Server.php @@ -9,7 +9,45 @@ use Illuminate\Support\Facades\Cache; use App\Utils\CacheKey; use App\Utils\Helper; use App\Models\User; +use Illuminate\Database\Eloquent\Casts\Attribute; +/** + * App\Models\Server + * + * @property int $id + * @property string $name 节点名称 + * @property string $type 服务类型 + * @property string $host 主机地址 + * @property string $port 端口 + * @property string|null $server_port 服务器端口 + * @property array|null $group_ids 分组IDs + * @property array|null $route_ids 路由IDs + * @property array|null $tags 标签 + * @property string|null $show 是否显示 + * @property string|null $allow_insecure 是否允许不安全 + * @property string|null $network 网络类型 + * @property int|null $parent_id 父节点ID + * @property float|null $rate 倍率 + * @property int|null $sort 排序 + * @property array|null $protocol_settings 协议设置 + * @property int $created_at + * @property int $updated_at + * + * @property-read Server|null $parent 父节点 + * @property-read \Illuminate\Database\Eloquent\Collection $stats 节点统计 + * + * @property-read int|null $last_check_at 最后检查时间(Unix时间戳) + * @property-read int|null $last_push_at 最后推送时间(Unix时间戳) + * @property-read int $online 在线用户数 + * @property-read int $is_online 是否在线(1在线 0离线) + * @property-read string $available_status 可用状态描述 + * @property-read string $cache_key 缓存键 + * @property string|null $ports 端口范围 + * @property string|null $password 密码 + * @property int|null $u 上行流量 + * @property int|null $d 下行流量 + * @property int|null $total 总流量 + */ class Server extends Model { public const TYPE_HYSTERIA = 'hysteria'; @@ -19,6 +57,9 @@ class Server extends Model public const TYPE_TUIC = 'tuic'; public const TYPE_SHADOWSOCKS = 'shadowsocks'; public const TYPE_SOCKS = 'socks'; + public const TYPE_NAIVE = 'naive'; + public const TYPE_HTTP = 'http'; + public const TYPE_MIERU = 'mieru'; public const STATUS_OFFLINE = 0; public const STATUS_ONLINE_NO_PUSH = 1; public const STATUS_ONLINE = 2; @@ -53,6 +94,9 @@ class Server extends Model self::TYPE_TUIC, self::TYPE_SHADOWSOCKS, self::TYPE_SOCKS, + self::TYPE_NAIVE, + self::TYPE_HTTP, + self::TYPE_MIERU, ]; protected $table = 'v2_server'; @@ -143,6 +187,32 @@ class Server extends Model 'allow_insecure' => ['type' => 'boolean', 'default' => false] ] ] + ], + self::TYPE_SOCKS => [ + 'tls' => ['type' => 'integer', 'default' => 0], + 'tls_settings' => [ + 'type' => 'object', + 'fields' => [ + 'allow_insecure' => ['type' => 'boolean', 'default' => false] + ] + ] + ], + self::TYPE_NAIVE => [ + 'tls' => ['type' => 'integer', 'default' => 0], + 'tls_settings' => ['type' => 'array', 'default' => null] + ], + self::TYPE_HTTP => [ + 'tls' => ['type' => 'integer', 'default' => 0], + 'tls_settings' => [ + 'type' => 'object', + 'fields' => [ + 'allow_insecure' => ['type' => 'boolean', 'default' => false] + ] + ] + ], + self::TYPE_MIERU => [ + 'transport' => ['type' => 'string', 'default' => 'tcp'], + 'multiplexing' => ['type' => 'string', 'default' => 'MULTIPLEXING_LOW'] ] ]; @@ -174,19 +244,6 @@ class Server extends Model return $result; } - private function getDefaultSettings(array $configs): array - { - $defaults = []; - foreach ($configs as $key => $config) { - if ($config['type'] === 'object') { - $defaults[$key] = $this->getDefaultSettings($config['fields']); - } else { - $defaults[$key] = $config['default']; - } - } - return $defaults; - } - public function getProtocolSettingsAttribute($value) { $settings = json_decode($value, true) ?? []; @@ -206,53 +263,22 @@ class Server extends Model $this->attributes['protocol_settings'] = json_encode($castedSettings); } - public function loadParentCreatedAt(): void - { - if ($this->parent_id) { - $this->created_at = $this->parent()->value('created_at'); - } - } - - public function loadServerStatus(): void - { - $type = strtoupper($this->type); - $serverId = $this->parent_id ?: $this->id; - - $this->last_check_at = Cache::get(CacheKey::get("SERVER_{$type}_LAST_CHECK_AT", $serverId)); - $this->last_push_at = Cache::get(CacheKey::get("SERVER_{$type}_LAST_PUSH_AT", $serverId)); - $this->online = Cache::get(CacheKey::get("SERVER_{$type}_ONLINE_USER", $serverId)) ?? 0; - $this->is_online = (time() - 300 > $this->last_check_at) ? 0 : 1; - $this->available_status = $this->getAvailableStatus(); - $this->cache_key = "{$this->type}-{$this->id}-{$this->updated_at}-{$this->is_online}"; - } - - public function handlePortAllocation(): void - { - if (strpos($this->port, '-') !== false) { - $this->ports = $this->port; - $this->port = Helper::randomPort($this->port); - } else { - $this->port = (int) $this->port; - } - } - - public function generateShadowsocksPassword(User $user): void + public function generateShadowsocksPassword(User $user): string { if ($this->type !== self::TYPE_SHADOWSOCKS) { - return; + return $user->uuid; } - $this->password = $user->uuid; $cipher = data_get($this, 'protocol_settings.cipher'); if (!$cipher || !isset(self::CIPHER_CONFIGURATIONS[$cipher])) { - return; + return $user->uuid; } $config = self::CIPHER_CONFIGURATIONS[$cipher]; $serverKey = Helper::getServerKey($this->created_at, $config['serverKeySize']); $userKey = Helper::uuidToBase64($user->uuid, $config['userKeySize']); - $this->password = "{$serverKey}:{$userKey}"; + return "{$serverKey}:{$userKey}"; } public static function normalizeType(string $type): string @@ -265,7 +291,7 @@ class Server extends Model return in_array(self::normalizeType($type), self::VALID_TYPES, true); } - public function getAvailableStatus(): int + public function getAvailableStatusAttribute(): int { $now = time(); if (!$this->last_check_at || ($now - self::CHECK_INTERVAL) >= $this->last_check_at) { @@ -297,4 +323,84 @@ class Server extends Model return ServerRoute::whereIn('id', $this->route_ids)->get(); } + /** + * 最后检查时间访问器 + */ + protected function lastCheckAt(): Attribute + { + return Attribute::make( + get: function () { + $type = strtoupper($this->type); + $serverId = $this->parent_id ?: $this->id; + return Cache::get(CacheKey::get("SERVER_{$type}_LAST_CHECK_AT", $serverId)); + } + ); + } + + /** + * 最后推送时间访问器 + */ + protected function lastPushAt(): Attribute + { + return Attribute::make( + get: function () { + $type = strtoupper($this->type); + $serverId = $this->parent_id ?: $this->id; + return Cache::get(CacheKey::get("SERVER_{$type}_LAST_PUSH_AT", $serverId)); + } + ); + } + + /** + * 在线用户数访问器 + */ + protected function online(): Attribute + { + return Attribute::make( + get: function () { + $type = strtoupper($this->type); + $serverId = $this->parent_id ?: $this->id; + return Cache::get(CacheKey::get("SERVER_{$type}_ONLINE_USER", $serverId)) ?? 0; + } + ); + } + + /** + * 是否在线访问器 + */ + protected function isOnline(): Attribute + { + return Attribute::make( + get: function () { + return (time() - 300 > $this->last_check_at) ? 0 : 1; + } + ); + } + + /** + * 缓存键访问器 + */ + protected function cacheKey(): Attribute + { + return Attribute::make( + get: function () { + return "{$this->type}-{$this->id}-{$this->updated_at}-{$this->is_online}"; + } + ); + } + + /** + * 服务器密钥访问器 + */ + protected function serverKey(): Attribute + { + return Attribute::make( + get: function () { + if ($this->type === self::TYPE_SHADOWSOCKS) { + return Helper::getServerKey($this->created_at, 16); + } + return null; + } + ); + } } diff --git a/app/Models/ServerGroup.php b/app/Models/ServerGroup.php index 3a47144..57f3514 100755 --- a/app/Models/ServerGroup.php +++ b/app/Models/ServerGroup.php @@ -4,7 +4,17 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\Casts\Attribute; +/** + * App\Models\ServerGroup + * + * @property int $id + * @property string $name 分组名 + * @property int $created_at + * @property int $updated_at + * @property-read int $server_count 服务器数量 + */ class ServerGroup extends Model { protected $table = 'v2_server_group'; @@ -23,4 +33,14 @@ class ServerGroup extends Model { return Server::whereJsonContains('group_ids', (string) $this->id)->get(); } + + /** + * 获取服务器数量 + */ + protected function serverCount(): Attribute + { + return Attribute::make( + get: fn () => Server::whereJsonContains('group_ids', (string) $this->id)->count(), + ); + } } diff --git a/app/Models/StatServer.php b/app/Models/StatServer.php index fc4cbd1..efa1fc6 100644 --- a/app/Models/StatServer.php +++ b/app/Models/StatServer.php @@ -4,6 +4,18 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +/** + * App\Models\StatServer + * + * @property int $id + * @property int $server_id 服务器ID + * @property int $u 上行流量 + * @property int $d 下行流量 + * @property int $record_at 记录时间 + * @property int $created_at + * @property int $updated_at + * @property-read int $value 通过SUM(u + d)计算的总流量值,仅在查询指定时可用 + */ class StatServer extends Model { protected $table = 'v2_stat_server'; diff --git a/app/Models/StatUser.php b/app/Models/StatUser.php index 07984d9..a956bd7 100644 --- a/app/Models/StatUser.php +++ b/app/Models/StatUser.php @@ -4,6 +4,18 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +/** + * App\Models\StatUser + * + * @property int $id + * @property int $user_id 用户ID + * @property int $u 上行流量 + * @property int $d 下行流量 + * @property int $record_at 记录时间 + * @property int $created_at + * @property int $updated_at + * @property-read int $value 通过SUM(u + d)计算的总流量值,仅在查询指定时可用 + */ class StatUser extends Model { protected $table = 'v2_stat_user'; diff --git a/app/Models/Ticket.php b/app/Models/Ticket.php index b92a5e9..86ba9b6 100644 --- a/app/Models/Ticket.php +++ b/app/Models/Ticket.php @@ -3,7 +3,25 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +/** + * App\Models\Ticket + * + * @property int $id + * @property int $user_id 用户ID + * @property string $subject 工单主题 + * @property string|null $level 工单等级 + * @property int $status 工单状态 + * @property int|null $reply_status 回复状态 + * @property int|null $last_reply_user_id 最后回复人 + * @property int $created_at + * @property int $updated_at + * + * @property-read User $user 关联的用户 + * @property-read \Illuminate\Database\Eloquent\Collection $messages 关联的工单消息 + */ class Ticket extends Model { protected $table = 'v2_ticket'; @@ -21,16 +39,21 @@ class Ticket extends Model self::STATUS_CLOSED => '关闭' ]; - public function user() + public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id', 'id'); } - public function messages() + + /** + * 关联的工单消息 + */ + public function messages(): HasMany { return $this->hasMany(TicketMessage::class, 'ticket_id', 'id'); } + // 即将删除 - public function message() + public function message(): HasMany { return $this->hasMany(TicketMessage::class, 'ticket_id', 'id'); } diff --git a/app/Models/TicketMessage.php b/app/Models/TicketMessage.php index 4673b33..0cc3c95 100644 --- a/app/Models/TicketMessage.php +++ b/app/Models/TicketMessage.php @@ -3,7 +3,20 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +/** + * App\Models\TicketMessage + * + * @property int $id + * @property int $ticket_id + * @property int $user_id + * @property string $message + * @property \Illuminate\Support\Carbon $created_at + * @property \Illuminate\Support\Carbon $updated_at + * @property-read \App\Models\Ticket $ticket 关联的工单 + * @property-read bool $is_me 当前消息是否由工单发起人发送 + */ class TicketMessage extends Model { protected $table = 'v2_ticket_message'; @@ -13,4 +26,22 @@ class TicketMessage extends Model 'created_at' => 'timestamp', 'updated_at' => 'timestamp' ]; + + protected $appends = ['is_me']; + + /** + * 关联的工单 + */ + public function ticket(): BelongsTo + { + return $this->belongsTo(Ticket::class, 'ticket_id', 'id'); + } + + /** + * 判断消息是否由工单发起人发送 + */ + public function getIsMeAttribute(): bool + { + return $this->ticket->user_id === $this->user_id; + } } diff --git a/app/Models/User.php b/app/Models/User.php index e23baa0..3e8205f 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,10 +2,55 @@ namespace App\Models; -use Illuminate\Database\Eloquent\Model; +use App\Utils\Helper; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Sanctum\HasApiTokens; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +/** + * App\Models\User + * + * @property int $id 用户ID + * @property string $email 邮箱 + * @property string $password 密码 + * @property string|null $password_algo 加密方式 + * @property string|null $password_salt 加密盐 + * @property string $token 邀请码 + * @property string $uuid + * @property int|null $invite_user_id 邀请人 + * @property int|null $plan_id 订阅ID + * @property int|null $group_id 权限组ID + * @property int|null $transfer_enable 流量(KB) + * @property int|null $speed_limit 限速Mbps + * @property int|null $u 上行流量 + * @property int|null $d 下行流量 + * @property int|null $banned 是否封禁 + * @property int|null $remind_expire 到期提醒 + * @property int|null $remind_traffic 流量提醒 + * @property int|null $expired_at 过期时间 + * @property int|null $balance 余额 + * @property int|null $commission_balance 佣金余额 + * @property float $commission_rate 返佣比例 + * @property int|null $device_limit 设备限制数量 + * @property int|null $discount 折扣 + * @property int|null $last_login_at 最后登录时间 + * @property int|null $parent_id 父账户ID + * @property int|null $is_admin 是否管理员 + * @property int $created_at + * @property int $updated_at + * @property bool $commission_auto_check 是否自动计算佣金 + * + * @property-read User|null $invite_user 邀请人信息 + * @property-read \App\Models\Plan|null $plan 用户订阅计划 + * @property-read ServerGroup|null $group 权限组 + * @property-read \Illuminate\Database\Eloquent\Collection $codes 邀请码列表 + * @property-read \Illuminate\Database\Eloquent\Collection $orders 订单列表 + * @property-read \Illuminate\Database\Eloquent\Collection $stat 统计信息 + * @property-read \Illuminate\Database\Eloquent\Collection $tickets 工单列表 + * @property-read User|null $parent 父账户 + * @property-read string $subscribe_url 订阅链接(动态生成) + */ class User extends Authenticatable { use HasApiTokens; @@ -14,52 +59,72 @@ class User extends Authenticatable protected $guarded = ['id']; protected $casts = [ 'created_at' => 'timestamp', - 'updated_at' => 'timestamp' + 'updated_at' => 'timestamp', + 'banned' => 'integer', + 'remind_expire' => 'boolean', + 'remind_traffic' => 'boolean', + 'commission_auto_check' => 'boolean', + 'commission_rate' => 'float' ]; protected $hidden = ['password']; + public const COMMISSION_TYPE_SYSTEM = 0; + public const COMMISSION_TYPE_PERIOD = 1; + public const COMMISSION_TYPE_ONETIME = 2; + // 获取邀请人信息 - public function invite_user() + public function invite_user(): BelongsTo { return $this->belongsTo(self::class, 'invite_user_id', 'id'); } - // 获取用户套餐 - public function plan() + /** + * 获取用户订阅计划 + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function plan(): BelongsTo { return $this->belongsTo(Plan::class, 'plan_id', 'id'); } - public function group() + public function group(): BelongsTo { return $this->belongsTo(ServerGroup::class, 'group_id', 'id'); } // 获取用户邀请码列表 - public function codes() + public function codes(): HasMany { return $this->hasMany(InviteCode::class, 'user_id', 'id'); } - public function orders() + public function orders(): HasMany { return $this->hasMany(Order::class, 'user_id', 'id'); } - public function stat() + public function stat(): HasMany { return $this->hasMany(StatUser::class, 'user_id', 'id'); } // 关联工单列表 - public function tickets() + public function tickets(): HasMany { return $this->hasMany(Ticket::class, 'user_id', 'id'); } - public function parent() + public function parent(): BelongsTo { return $this->belongsTo(self::class, 'parent_id', 'id'); } + + /** + * 获取订阅链接属性 + */ + public function getSubscribeUrlAttribute(): string + { + return Helper::getSubscribeUrl($this->token); + } } diff --git a/app/Payments/BTCPay.php b/app/Payments/BTCPay.php index 00a3cea..432fc17 100644 --- a/app/Payments/BTCPay.php +++ b/app/Payments/BTCPay.php @@ -83,7 +83,6 @@ class BTCPay implements PaymentInterface if (!self::hashEqual($signraturHeader, $computedSignature)) { throw new ApiException('HMAC signature does not match', 400); - return false; } //get order id store in metadata @@ -112,8 +111,8 @@ class BTCPay implements PaymentInterface $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt( diff --git a/app/Payments/BinancePay.php b/app/Payments/BinancePay.php new file mode 100644 index 0000000..7b727ba --- /dev/null +++ b/app/Payments/BinancePay.php @@ -0,0 +1,118 @@ +config = $config; + } + + public function form() + { + return [ + 'api_key' => [ + 'label' => 'API Key', + 'type' => 'input', + 'description' => '请输入您的 Binance API Key' + ], + 'secret_key' => [ + 'label' => 'Secret Key', + 'type' => 'input', + 'description' => '请输入您的 Binance Secret Key' + ] + ]; + } + + public function pay($order) + { + $timestamp = intval(microtime(true) * 1000); // Timestamp in milliseconds + $nonceStr = bin2hex(random_bytes(16)); // Generating a nonce + $request = [ + "env" => [ + "terminalType" => "APP" + ], + 'merchantTradeNo' => strval($order['trade_no']), + 'fiatCurrency' => 'CNY', + 'fiatAmount' => ($order["total_amount"] / 100), + 'supportPayCurrency' => "USDT,BNB", + 'description' => strval($order['trade_no']), + 'webhookUrl' => $order['notify_url'], + 'returnUrl' => $order['return_url'], + "goodsDetails" => [ + [ + "goodsType" => "01", + "goodsCategory" => "D000", + "referenceGoodsId" => "7876763A3B", + "goodsName" => "Ice Cream", + "goodsDetail" => "Greentea ice cream cone" + ] + ] + ]; + $body = json_encode($request, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, 'https://bpay.binanceapi.com/binancepay/openapi/v3/order'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $body); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json; charset=utf-8', + 'BinancePay-Timestamp: ' . $timestamp, + 'BinancePay-Nonce: ' . $nonceStr, + 'BinancePay-Certificate-SN: ' . $this->config['api_key'], + 'BinancePay-Signature: ' . $this->generateSignature($body, $this->config['secret_key'], $timestamp, $nonceStr), + ]); + curl_setopt($ch, CURLOPT_PROXY, "socks5h://154.3.37.204:47714"); + curl_setopt($ch, CURLOPT_PROXYUSERPWD, "GGn28Io5fW:9VkWfoPGiG"); + $response = curl_exec($ch); + curl_close($ch); + if (!$response) { + abort(400, '支付失败,请稍后再试'); + } + $res = json_decode($response, true); + \Log::channel('daily')->info($res); + if (!is_array($res)) { + abort(400, '支付失败,请稍后再试'); + } + if (isset($res['code']) && $res['code'] == '400201') { + $res['data'] = \Cache::get('CheckoutInfo_' . strval($order['trade_no'])); + } + if (!isset($res['data'])) { + abort(400, '支付失败,请稍后再试'); + } + if (!is_array($res['data']) || !isset($res['data']['checkoutUrl'])) { + abort(400, '支付失败,请稍后再试'); + } + // 缓存支付信息 + \Cache::put('CheckoutInfo_' . strval($order['trade_no']), $res['data']); + return [ + 'type' => 1, // 0:qrcode 1:url + 'data' => $res['data']['checkoutUrl'] + ]; + } + + public function notify($params) + { + $bizStatus = $params['bizStatus']; + if ($bizStatus !== 'PAY_SUCCESS'){ + return false; + } + $data = json_decode($params['data'], true); + + return [ + 'trade_no' => $data['merchantTradeNo'], + 'callback_no' => $params['bizIdStr'], + 'custom_result' => '{"returnCode":"SUCCESS","returnMessage":null}' + ]; + } + private function generateSignature($body, $secret, $timestamp, $nonceStr) + { + $payload = $timestamp . chr(0x0A) . $nonceStr . chr(0x0A) . $body . chr(0x0A); + return strtoupper(hash_hmac('sha512', $payload, $secret)); + } +} diff --git a/app/Payments/Coinbase.php b/app/Payments/Coinbase.php index bb5c3bb..9c9cdc2 100644 --- a/app/Payments/Coinbase.php +++ b/app/Payments/Coinbase.php @@ -95,8 +95,8 @@ class Coinbase implements PaymentInterface $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt( diff --git a/app/Payments/EPayWxpay.php b/app/Payments/EPayWxpay.php new file mode 100644 index 0000000..db1deca --- /dev/null +++ b/app/Payments/EPayWxpay.php @@ -0,0 +1,71 @@ +config = $config; + } + + public function form() + { + return [ + 'url' => [ + 'label' => 'URL', + 'description' => '', + 'type' => 'input', + ], + 'pid' => [ + 'label' => 'PID', + 'description' => '', + 'type' => 'input', + ], + 'key' => [ + 'label' => 'KEY', + 'description' => '', + 'type' => 'input', + ] + ]; + } + + public function pay($order) + { + $params = [ + 'money' => $order['total_amount'] / 100, + 'type' => 'wxpay', + 'name' => $order['trade_no'], + 'notify_url' => $order['notify_url'], + 'return_url' => $order['return_url'], + 'out_trade_no' => $order['trade_no'], + 'pid' => $this->config['pid'] + ]; + ksort($params); + reset($params); + $str = stripslashes(urldecode(http_build_query($params))) . $this->config['key']; + $params['sign'] = md5($str); + $params['sign_type'] = 'MD5'; + return [ + 'type' => 1, // 0:qrcode 1:url + 'data' => $this->config['url'] . '/submit.php?' . http_build_query($params) + ]; + } + + public function notify($params) + { + $sign = $params['sign']; + unset($params['sign']); + unset($params['sign_type']); + ksort($params); + reset($params); + $str = stripslashes(urldecode(http_build_query($params))) . $this->config['key']; + if ($sign !== md5($str)) { + return false; + } + return [ + 'trade_no' => $params['out_trade_no'], + 'callback_no' => $params['trade_no'] + ]; + } +} diff --git a/app/Payments/HiiCashPayment.php b/app/Payments/HiiCashPayment.php new file mode 100644 index 0000000..8571653 --- /dev/null +++ b/app/Payments/HiiCashPayment.php @@ -0,0 +1,113 @@ +config = $config; + } + + public function form() + { + return [ + 'rate' => [ + 'label' => '汇率', + 'description' => 'HiiCash支付单位为美元,如果您站点金额单位不为美元则需要填写汇率', + 'type' => 'input', + 'default' => '2333' + ], + 'pid' => [ + 'label' => '商户号', + 'description' => '', + 'type' => 'input', + ], + 'appid' => [ + 'label' => '应用ID', + 'description' => '', + 'type' => 'input' + ], + 'key' => [ + 'label' => '私钥', + 'description' => '', + 'type' => 'input', + ] + ]; + } + + public function pay($order) + { + + $request = [ + "mchNo" => $this->config["pid"], + "appId" => $this->config["appid"], + "mchOrderNo" => $order["trade_no"], + "amount" => ceil(($order["total_amount"] * 100) / ($this->config['rate'] ?? "1")) / 100, + "payDataType" => "Cashier", + "currency" => "USD", + "subject" => $order["trade_no"], + "notifyUrl" => $order["notify_url"], + "returnUrl" => $order["return_url"], + ]; + $headers = [ + "HiicashPay-Timestamp" => (int)(string)floor(microtime(true) * 1000), + "HiicashPay-Nonce" => \Str::random(32), + "HiicashPay-AppId" => $this->config["appid"] + ]; + $body = json_encode($request, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $payload = $headers['HiicashPay-Timestamp'] . chr(0x0A) . $headers['HiicashPay-Nonce'] . chr(0x0A) . $body . chr(0x0A); + $signature = $this->generate_signature($payload, $this->config['key']); + $headers["HiicashPay-Signature"] = $signature; + $jsonStr = json_encode($request, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + $httpHeaders = []; + foreach ($headers as $key => $header) { + $httpHeaders[] = $key . ': ' . $header; + } + $httpHeaders[] = 'Content-Type: application/json; charset=utf-8'; + $httpHeaders[] = 'Content-Length: ' . strlen($jsonStr); + $ch = curl_init(file_get_contents('https://hiicash.oss-ap-northeast-1.aliyuncs.com/gateway.txt') . 'pay/order/create'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr); + curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders); + $response = curl_exec($ch); + curl_close($ch); + if (!$response) { + abort(400, '支付失败,请稍后再试'); + } + $res = json_decode($response, true); + if (!is_array($res) || !isset($res['data'])) { + abort(400, '支付失败,请稍后再试'); + } + if (!is_array($res['data']) || !isset($res['data']['payData'])) { + abort(400, '支付失败,请稍后再试'); + } + return [ + 'type' => 1, // 0:qrcode 1:url + 'data' => $res['data']['payData'] + ]; + } + + public function notify($params) + { + if (!isset($params['mchOrderNo']) || !isset($params['mchOrderNo'])) { + return false; + } + return [ + 'trade_no' => $params['mchOrderNo'], + 'callback_no' => $params['payOrderId'], + 'custom_result' => '{"returnCode": "success","returnMsg": ""}' + ]; + } + + + // 使用 HMAC-SHA512 算法生成签名 + function generate_signature(string $payload, string $secret_key) + { + $hash = hash_hmac("sha512", $payload, $secret_key, true); + // 将签名转换为大写字符串 + return strtoupper(bin2hex($hash)); + } +} diff --git a/app/Payments/PayPal.php b/app/Payments/PayPal.php new file mode 100644 index 0000000..544f9b4 --- /dev/null +++ b/app/Payments/PayPal.php @@ -0,0 +1,132 @@ +config = $config; + $this->client = new Client(); + $this->apiHost = optional($this->config)['mode'] == 'sandbox' ? "https://api.sandbox.paypal.com" : "https://api.paypal.com"; + } + + public function form() + { + return [ + 'mode' => [ + 'label' => 'Mode', + 'description' => '沙箱/生产模式 sandbox/live', + 'type' => 'input', + ], + 'client_id' => [ + 'label' => 'Client ID', + 'description' => 'PayPal Client ID', + 'type' => 'input', + ], + 'client_secret' => [ + 'label' => 'Client Secret', + 'description' => 'PayPal Client Secret', + 'type' => 'input', + ], + 'rate' => [ + 'label' => '汇率', + 'description' => 'Paypal支付单位为USD,如果您站点金额单位不为USD则需要填写汇率', + 'type' => 'input', + 'default' => '2333' + ], + ]; + } + + public function pay($order) + { + $this->token = json_decode($this->client->post("{$this->apiHost}/v1/oauth2/token", [ + 'auth' => [$this->config['client_id'], $this->config['client_secret']], + 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], + 'form_params' => ['grant_type' => 'client_credentials'] + ])->getBody(), true)['access_token']; + // 创建订单 + $order = json_decode($this->client->request('POST', "{$this->apiHost}/v2/checkout/orders", [ + 'headers' => [ + 'Content-Type' => 'application/json', + 'PayPal-Request-Id' => $order['trade_no'], + 'Authorization' => "Bearer {$this->token}" + ], + 'json' => [ + 'intent' => 'CAPTURE', + 'purchase_units' => [ + [ + "reference_id" => $order['trade_no'], + "amount" => [ + "currency_code" => "USD", + "value" => number_format(ceil(($order["total_amount"] * 100) / ($this->config['rate'] ?? "1")) / 10000, 2, '.', '') + ] + ] + ], + "payment_source" => [ + "paypal" => [ + "experience_context" => [ + "payment_method_preference" => "UNRESTRICTED", + "brand_name" => $order['trade_no'], + "locale" => "zh-CN", + "landing_page" => "NO_PREFERENCE", + "shipping_preference" => "NO_SHIPPING", + "user_action" => "PAY_NOW", + "return_url" => $order['return_url'], + "cancel_url" => $order['return_url'] + ] + ] + ] + ] + + ])->getBody(), true); + + $payerActionUrl = ''; + foreach ($order['links'] as $link) { + if ($link['rel'] === 'payer-action') { + $payerActionUrl = $link['href']; + break; + } + } + + return [ + 'type' => 1, // 0:qrcode 1:url + 'data' => $payerActionUrl + ]; + + } + + public function notify($params) + { + $this->token = json_decode($this->client->post("{$this->apiHost}/v1/oauth2/token", [ + 'auth' => [$this->config['client_id'], $this->config['client_secret']], + 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], + 'form_params' => ['grant_type' => 'client_credentials'] + ])->getBody(), true)['access_token']; + $resource = $params['resource']; + $purchase_units = $resource['purchase_units']; + if ($params['event_type'] == 'CHECKOUT.ORDER.APPROVED') { + $order = json_decode($this->client->request('POST', "{$this->apiHost}/v2/checkout/orders/{$resource['id']}/capture", [ + "headers" => [ + 'Content-Type' => 'application/json', + 'Authorization' => "Bearer {$this->token}" + ] + ])->getBody(), true); + if ($order['status'] == 'COMPLETED') { + return [ + 'trade_no' => $purchase_units[0]['reference_id'], + 'callback_no' => $order['id'] + ]; + } + } + return false; + + } +} diff --git a/app/Protocols/Clash.php b/app/Protocols/Clash.php index 63bca4b..2946e02 100644 --- a/app/Protocols/Clash.php +++ b/app/Protocols/Clash.php @@ -28,7 +28,7 @@ class Clash implements ProtocolInterface $servers = $this->servers; $user = $this->user; $appName = admin_setting('app_name', 'XBoard'); - + // 优先从 admin_setting 获取模板 $template = admin_setting('subscribe_template_clash'); if (empty($template)) { @@ -40,7 +40,7 @@ class Clash implements ProtocolInterface $template = file_get_contents($defaultConfig); } } - + $config = Yaml::parse($template); $proxy = []; $proxies = []; @@ -67,6 +67,14 @@ class Clash implements ProtocolInterface array_push($proxy, self::buildTrojan($user['uuid'], $item)); array_push($proxies, $item['name']); } + if ($item['type'] === 'socks') { + array_push($proxy, self::buildSocks5($user['uuid'], $item)); + array_push($proxies, $item['name']); + } + if ($item['type'] === 'http') { + array_push($proxy, self::buildHttp($user['uuid'], $item)); + array_push($proxies, $item['name']); + } } $config['proxies'] = array_merge($config['proxies'] ? $config['proxies'] : [], $proxy); @@ -171,7 +179,7 @@ class Clash implements ProtocolInterface if (data_get($protocol_settings, 'network_settings.header.type', 'none') !== 'none') { $array['http-opts'] = [ 'headers' => data_get($protocol_settings, 'network_settings.header.request.headers'), - 'path' => \Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])) + 'path' => \Illuminate\Support\Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])) ]; } break; @@ -231,9 +239,56 @@ class Clash implements ProtocolInterface return $array; } + public static function buildSocks5($password, $server) + { + $protocol_settings = $server['protocol_settings']; + $array = []; + $array['name'] = $server['name']; + $array['type'] = 'socks5'; + $array['server'] = $server['host']; + $array['port'] = $server['port']; + $array['udp'] = true; + + $array['username'] = $password; + $array['password'] = $password; + + // TLS 配置 + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = true; + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false); + } + + return $array; + } + + public static function buildHttp($password, $server) + { + $protocol_settings = $server['protocol_settings']; + $array = []; + $array['name'] = $server['name']; + $array['type'] = 'http'; + $array['server'] = $server['host']; + $array['port'] = $server['port']; + + $array['username'] = $password; + $array['password'] = $password; + + // TLS 配置 + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = true; + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false); + } + + return $array; + } + private function isMatch($exp, $str) { - return @preg_match($exp, $str); + try { + return preg_match($exp, $str) === 1; + } catch (\Exception $e) { + return false; + } } private function isRegex($exp) @@ -241,6 +296,10 @@ class Clash implements ProtocolInterface if (empty($exp)) { return false; } - return @preg_match((string) $exp, '') !== false; + try { + return preg_match($exp, '') !== false; + } catch (\Exception $e) { + return false; + } } } diff --git a/app/Protocols/ClashMeta.php b/app/Protocols/ClashMeta.php index c14c7a2..bac28f2 100644 --- a/app/Protocols/ClashMeta.php +++ b/app/Protocols/ClashMeta.php @@ -13,7 +13,11 @@ class ClashMeta implements ProtocolInterface private $servers; private $user; - public function __construct($user, $servers, array $options = null) + /** + * @param mixed $user 用户实例 + * @param array $servers 服务器列表 + */ + public function __construct($user, $servers) { $this->user = $user; $this->servers = $servers; @@ -78,6 +82,18 @@ class ClashMeta implements ProtocolInterface array_push($proxy, self::buildTuic($user['uuid'], $item)); array_push($proxies, $item['name']); } + if ($item['type'] === 'socks') { + array_push($proxy, self::buildSocks5($user['uuid'], $item)); + array_push($proxies, $item['name']); + } + if ($item['type'] === 'http') { + array_push($proxy, self::buildHttp($user['uuid'], $item)); + array_push($proxies, $item['name']); + } + if ($item['type'] === 'mieru') { + array_push($proxy, self::buildMieru($user['uuid'], $item)); + array_push($proxies, $item['name']); + } } $config['proxies'] = array_merge($config['proxies'] ? $config['proxies'] : [], $proxy); @@ -176,7 +192,7 @@ class ClashMeta implements ProtocolInterface if (data_get($protocol_settings, 'network_settings.header.type', 'none') !== 'none') { $array['http-opts'] = [ 'headers' => data_get($protocol_settings, 'network_settings.header.request.headers'), - 'path' => \Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])) + 'path' => \Illuminate\Support\Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])) ]; } break; @@ -369,9 +385,78 @@ class ClashMeta implements ProtocolInterface return $array; } + public static function buildMieru($password, $server) + { + $protocol_settings = data_get($server, 'protocol_settings', []); + $array = [ + 'name' => $server['name'], + 'type' => 'mieru', + 'server' => $server['host'], + 'port' => $server['port'], + 'username' => $password, + 'password' => $password, + 'transport' => strtoupper(data_get($protocol_settings, 'transport', 'TCP')), + 'multiplexing' => data_get($protocol_settings, 'multiplexing', 'MULTIPLEXING_LOW') + ]; + + // 如果配置了端口范围 + if (isset($server['ports'])) { + $array['port-range'] = $server['ports']; + } + + return $array; + } + + public static function buildSocks5($password, $server) + { + $protocol_settings = $server['protocol_settings']; + $array = []; + $array['name'] = $server['name']; + $array['type'] = 'socks5'; + $array['server'] = $server['host']; + $array['port'] = $server['port']; + $array['udp'] = true; + + $array['username'] = $password; + $array['password'] = $password; + + // TLS 配置 + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = true; + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false); + } + + return $array; + } + + public static function buildHttp($password, $server) + { + $protocol_settings = $server['protocol_settings']; + $array = []; + $array['name'] = $server['name']; + $array['type'] = 'http'; + $array['server'] = $server['host']; + $array['port'] = $server['port']; + + $array['username'] = $password; + $array['password'] = $password; + + // TLS 配置 + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = true; + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false); + } + + return $array; + } + private function isMatch($exp, $str) { - return @preg_match($exp, $str); + try { + return preg_match($exp, $str) === 1; + } catch (\Exception $e) { + return false; + } } private function isRegex($exp) @@ -379,6 +464,10 @@ class ClashMeta implements ProtocolInterface if (empty($exp)) { return false; } - return @preg_match($exp, '') !== false; + try { + return preg_match($exp, '') !== false; + } catch (\Exception $e) { + return false; + } } } diff --git a/app/Protocols/General.php b/app/Protocols/General.php index 5c18caa..6da11f3 100644 --- a/app/Protocols/General.php +++ b/app/Protocols/General.php @@ -5,7 +5,7 @@ namespace App\Protocols; use App\Contracts\ProtocolInterface; use App\Utils\Helper; - +use Illuminate\Support\Arr; class General implements ProtocolInterface { public $flags = ['general', 'v2rayn', 'v2rayng', 'passwall', 'ssrplus', 'sagernet']; @@ -45,6 +45,9 @@ class General implements ProtocolInterface if ($item['type'] === 'hysteria') { $uri .= self::buildHysteria($user['uuid'], $item); } + if ($item['type'] === 'socks') { + $uri .= self::buildSocks($user['uuid'], $item); + } } return base64_encode($uri); } @@ -87,8 +90,11 @@ class General implements ProtocolInterface case 'tcp': if (data_get($protocol_settings, 'network_settings.header.type', 'none') !== 'none') { $config['type'] = data_get($protocol_settings, 'network_settings.header.type', 'http'); - $config['path'] = \Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])); - $config['host'] = data_get($protocol_settings, 'network_settings.headers.Host') ? \Arr::random(data_get($protocol_settings, 'network_settings.headers.Host'), ['/']) : null; + $config['path'] = Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])); + $config['host'] = + data_get($protocol_settings, 'network_settings.headers.Host') + ? Arr::random(data_get($protocol_settings, 'network_settings.headers.Host', ['/']), ) + : null; } break; case 'ws': @@ -249,4 +255,11 @@ class General implements ProtocolInterface return $uri; } + public static function buildSocks($password, $server) + { + $name = rawurlencode($server['name']); + $credentials = base64_encode("{$password}:{$password}"); + return "socks://{$credentials}@{$server['host']}:{$server['port']}#{$name}\r\n"; + } + } diff --git a/app/Protocols/QuantumultX.php b/app/Protocols/QuantumultX.php index 25cf6a3..b759a4a 100644 --- a/app/Protocols/QuantumultX.php +++ b/app/Protocols/QuantumultX.php @@ -53,7 +53,6 @@ class QuantumultX implements ProtocolInterface 'udp-relay=true', "tag={$server['name']}" ]; - $config = array_filter($config); $uri = implode(',', $config); $uri .= "\r\n"; return $uri; diff --git a/app/Protocols/Shadowrocket.php b/app/Protocols/Shadowrocket.php index 017b840..fe63e05 100644 --- a/app/Protocols/Shadowrocket.php +++ b/app/Protocols/Shadowrocket.php @@ -89,9 +89,9 @@ class Shadowrocket implements ProtocolInterface if ($protocol_settings['tls']) { $config['tls'] = 1; if (data_get($protocol_settings, 'tls_settings')) { - if (data_get($protocol_settings, 'tls_settings.allow_insecure') && !empty(data_get($protocol_settings, 'tls_settings.allow_insecure'))) + if (!!data_get($protocol_settings, 'tls_settings.allow_insecure')) $config['allowInsecure'] = (int) data_get($protocol_settings, 'tls_settings.allow_insecure'); - if (data_get($protocol_settings, 'tls_settings.server_name') && !empty(data_get($protocol_settings, 'tls_settings.server_name'))) + if (!!data_get($protocol_settings, 'tls_settings.server_name')) $config['peer'] = data_get($protocol_settings, 'tls_settings.server_name'); } } @@ -100,8 +100,8 @@ class Shadowrocket implements ProtocolInterface case 'tcp': if (data_get($protocol_settings, 'network_settings.header.type', 'none') !== 'none') { $config['obfs'] = data_get($protocol_settings, 'network_settings.header.type'); - $config['path'] = \Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])); - $config['obfsParam'] = \Arr::random(data_get($protocol_settings, 'network_settings.header.request.headers.Host', ['www.example.com'])); + $config['path'] = \Illuminate\Support\Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])); + $config['obfsParam'] = \Illuminate\Support\Arr::random(data_get($protocol_settings, 'network_settings.header.request.headers.Host', ['www.example.com'])); } break; case 'ws': @@ -168,8 +168,8 @@ class Shadowrocket implements ProtocolInterface case 'tcp': if (data_get($protocol_settings, 'network_settings.header.type', 'none') !== 'none') { $config['obfs'] = data_get($protocol_settings, 'network_settings.header.type'); - $config['path'] = \Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])); - $config['obfsParam'] = \Arr::random(data_get($protocol_settings, 'network_settings.header.request.headers.Host', ['www.example.com'])); + $config['path'] = \Illuminate\Support\Arr::random(data_get($protocol_settings, 'network_settings.header.request.path', ['/'])); + $config['obfsParam'] = \Illuminate\Support\Arr::random(data_get($protocol_settings, 'network_settings.header.request.headers.Host', ['www.example.com'])); } break; case 'ws': @@ -225,6 +225,8 @@ class Shadowrocket implements ProtocolInterface public static function buildHysteria($password, $server) { $protocol_settings = $server['protocol_settings']; + $uri = ''; // 初始化变量 + switch (data_get($protocol_settings, 'version')) { case 1: $params = [ diff --git a/app/Protocols/Shadowsocks.php b/app/Protocols/Shadowsocks.php index dd76370..3bebc48 100644 --- a/app/Protocols/Shadowsocks.php +++ b/app/Protocols/Shadowsocks.php @@ -47,7 +47,7 @@ class Shadowsocks implements ProtocolInterface $subs['version'] = 1; $subs['bytes_used'] = $bytesUsed; $subs['bytes_remaining'] = $bytesRemaining; - $subs['servers'] = array_merge($subs['servers'] ? $subs['servers'] : [], $configs); + $subs['servers'] = array_merge($subs['servers'], $configs); return json_encode($subs, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } diff --git a/app/Protocols/SingBox.php b/app/Protocols/SingBox.php index 192ea36..877c568 100644 --- a/app/Protocols/SingBox.php +++ b/app/Protocols/SingBox.php @@ -11,7 +11,7 @@ class SingBox implements ProtocolInterface private $user; private $config; - public function __construct($user, $servers, array $options = null) + public function __construct($user, $servers) { $this->user = $user; $this->servers = $servers; @@ -84,6 +84,14 @@ class SingBox implements ProtocolInterface $tuicConfig = $this->buildTuic($this->user['uuid'], $item); $proxies[] = $tuicConfig; } + if ($item['type'] === 'socks') { + $socksConfig = $this->buildSocks($this->user['uuid'], $item); + $proxies[] = $socksConfig; + } + if ($item['type'] === 'http') { + $httpConfig = $this->buildHttp($this->user['uuid'], $item); + $proxies[] = $httpConfig; + } } foreach ($outbounds as &$outbound) { if (in_array($outbound['type'], ['urltest', 'selector'])) { @@ -361,4 +369,58 @@ class SingBox implements ProtocolInterface return $array; } + + protected function buildSocks($password, $server): array + { + $protocol_settings = data_get($server, 'protocol_settings', []); + $array = [ + 'type' => 'socks', + 'tag' => $server['name'], + 'server' => $server['host'], + 'server_port' => $server['port'], + 'version' => '5', // 默认使用 socks5 + 'username' => $password, + 'password' => $password, + ]; + + if (data_get($protocol_settings, 'udp_over_tcp')) { + $array['udp_over_tcp'] = true; + } + + return $array; + } + + protected function buildHttp($password, $server): array + { + $protocol_settings = data_get($server, 'protocol_settings', []); + $array = [ + 'type' => 'http', + 'tag' => $server['name'], + 'server' => $server['host'], + 'server_port' => $server['port'], + 'username' => $password, + 'password' => $password, + ]; + + if ($path = data_get($protocol_settings, 'path')) { + $array['path'] = $path; + } + + if ($headers = data_get($protocol_settings, 'headers')) { + $array['headers'] = $headers; + } + + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = [ + 'enabled' => true, + 'insecure' => (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false), + ]; + + if ($serverName = data_get($protocol_settings, 'tls_settings.server_name')) { + $array['tls']['server_name'] = $serverName; + } + } + + return $array; + } } diff --git a/app/Protocols/Stash.php b/app/Protocols/Stash.php index 927e95e..4d2522c 100644 --- a/app/Protocols/Stash.php +++ b/app/Protocols/Stash.php @@ -82,6 +82,18 @@ class Stash implements ProtocolInterface array_push($proxy, self::buildTrojan($user['uuid'], $item)); array_push($proxies, $item['name']); } + if ($item['type'] === 'tuic') { + array_push($proxy, self::buildTuic($user['uuid'], $item)); + array_push($proxies, $item['name']); + } + if ($item['type'] === 'socks') { + array_push($proxy, self::buildSocks5($user['uuid'], $item)); + array_push($proxies, $item['name']); + } + if ($item['type'] === 'http') { + array_push($proxy, self::buildHttp($user['uuid'], $item)); + array_push($proxies, $item['name']); + } } $config['proxies'] = array_merge($config['proxies'] ? $config['proxies'] : [], $proxy); @@ -289,12 +301,91 @@ class Stash implements ProtocolInterface } + public static function buildTuic($password, $server) + { + $protocol_settings = data_get($server, 'protocol_settings', []); + $array = [ + 'name' => $server['name'], + 'type' => 'tuic', + 'server' => $server['host'], + 'port' => $server['port'], + 'uuid' => $password, + 'password' => $password, + 'congestion-controller' => data_get($protocol_settings, 'congestion_control', 'cubic'), + 'udp-relay-mode' => data_get($protocol_settings, 'udp_relay_mode', 'native'), + 'alpn' => data_get($protocol_settings, 'alpn', ['h3']), + 'reduce-rtt' => true, + 'fast-open' => true, + 'heartbeat-interval' => 10000, + 'request-timeout' => 8000, + 'max-udp-relay-packet-size' => 1500, + ]; + + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls.allow_insecure', false); + if ($serverName = data_get($protocol_settings, 'tls.server_name')) { + $array['sni'] = $serverName; + } + + return $array; + } + + public static function buildSocks5($password, $server) + { + $protocol_settings = $server['protocol_settings']; + $array = [ + 'name' => $server['name'], + 'type' => 'socks5', + 'server' => $server['host'], + 'port' => $server['port'], + 'username' => $password, + 'password' => $password, + 'udp' => true, + ]; + + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = true; + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false); + if ($serverName = data_get($protocol_settings, 'tls_settings.server_name')) { + $array['sni'] = $serverName; + } + } + + return $array; + } + + public static function buildHttp($password, $server) + { + $protocol_settings = $server['protocol_settings']; + $array = [ + 'name' => $server['name'], + 'type' => 'http', + 'server' => $server['host'], + 'port' => $server['port'], + 'username' => $password, + 'password' => $password, + ]; + + if (data_get($protocol_settings, 'tls')) { + $array['tls'] = true; + $array['skip-cert-verify'] = (bool) data_get($protocol_settings, 'tls_settings.allow_insecure', false); + if ($serverName = data_get($protocol_settings, 'tls_settings.server_name')) { + $array['sni'] = $serverName; + } + } + + return $array; + } + private function isRegex($exp) { if (empty($exp)) { return false; } - return @preg_match($exp, '') !== false; + try { + return preg_match($exp, '') !== false; + } catch (\Exception $e) { + return false; + } } private function isMatch($exp, $str) diff --git a/app/Protocols/Surfboard.php b/app/Protocols/Surfboard.php index 5fe05d7..525ce1c 100644 --- a/app/Protocols/Surfboard.php +++ b/app/Protocols/Surfboard.php @@ -4,6 +4,7 @@ namespace App\Protocols; use App\Utils\Helper; use App\Contracts\ProtocolInterface; +use Illuminate\Support\Facades\File; class Surfboard implements ProtocolInterface { @@ -63,7 +64,7 @@ class Surfboard implements ProtocolInterface $defaultConfig = base_path() . '/resources/rules/default.surfboard.conf'; $customConfig = base_path() . '/resources/rules/custom.surfboard.conf'; - if (\File::exists($customConfig)) { + if (File::exists($customConfig)) { $config = file_get_contents("$customConfig"); } else { $config = file_get_contents("$defaultConfig"); @@ -127,9 +128,9 @@ class Surfboard implements ProtocolInterface array_push($config, 'tls=true'); if (data_get($protocol_settings, 'tls_settings')) { $tlsSettings = data_get($protocol_settings, 'tls_settings'); - if (isset($tlsSettings['allowInsecure']) && !empty($tlsSettings['allowInsecure'])) + if (!!data_get($tlsSettings, 'allowInsecure')) array_push($config, 'skip-cert-verify=' . ($tlsSettings['allowInsecure'] ? 'true' : 'false')); - if (isset($tlsSettings['serverName']) && !empty($tlsSettings['serverName'])) + if (!!data_get($tlsSettings, 'serverName')) array_push($config, "sni={$tlsSettings['serverName']}"); } } @@ -161,8 +162,8 @@ class Surfboard implements ProtocolInterface 'tfo=true', 'udp-relay=true' ]; - if (!empty($protocol_settings['allow_insecure'])) { - array_push($config, $protocol_settings['allow_insecure'] ? 'skip-cert-verify=true' : 'skip-cert-verify=false'); + if (data_get($protocol_settings, 'allow_insecure')) { + array_push($config, !!data_get($protocol_settings, 'allow_insecure') ? 'skip-cert-verify=true' : 'skip-cert-verify=false'); } $config = array_filter($config); $uri = implode(',', $config); diff --git a/app/Protocols/Surge.php b/app/Protocols/Surge.php index 4b8931f..1657436 100644 --- a/app/Protocols/Surge.php +++ b/app/Protocols/Surge.php @@ -164,7 +164,7 @@ class Surge implements ProtocolInterface 'udp-relay=true' ]; if (!empty($protocol_settings['allow_insecure'])) { - array_push($config, $protocol_settings['allow_insecure'] ? 'skip-cert-verify=true' : 'skip-cert-verify=false'); + array_push($config, !!data_get($protocol_settings, 'allow_insecure') ? 'skip-cert-verify=true' : 'skip-cert-verify=false'); } $config = array_filter($config); $uri = implode(',', $config); @@ -189,7 +189,7 @@ class Surge implements ProtocolInterface 'udp-relay=true' ]; if (data_get($protocol_settings, 'tls.allow_insecure')) { - $config[] = data_get($protocol_settings, 'tls.allow_insecure') ? 'skip-cert-verify=true' : 'skip-cert-verify=false'; + $config[] = !!data_get($protocol_settings, 'tls.allow_insecure') ? 'skip-cert-verify=true' : 'skip-cert-verify=false'; } $config = array_filter($config); $uri = implode(',', $config); diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 3049068..b92a7dd 100755 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -8,17 +8,15 @@ use Illuminate\Support\Facades\Gate; class AuthServiceProvider extends ServiceProvider { /** - * The policy mappings for the application. - * - * @var array + * 策略映射 + * @var array */ protected $policies = [ // 'App\Model' => 'App\Policies\ModelPolicy', ]; /** - * Register any authentication / authorization services. - * + * 注册任何认证/授权服务 * @return void */ public function boot() diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index e2d1497..299c8be 100755 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -8,16 +8,14 @@ use Illuminate\Support\Facades\Event; class EventServiceProvider extends ServiceProvider { /** - * The event listener mappings for the application. - * - * @var array + * 事件监听器映射 + * @var array> */ protected $listen = [ ]; /** - * Register any events for your application. - * + * 注册任何事件 * @return void */ public function boot() diff --git a/app/Services/Auth/LoginService.php b/app/Services/Auth/LoginService.php new file mode 100644 index 0000000..8538d1e --- /dev/null +++ b/app/Services/Auth/LoginService.php @@ -0,0 +1,111 @@ += (int)admin_setting('password_limit_count', 5)) { + return [false, [429, __('There are too many password errors, please try again after :minute minutes.', [ + 'minute' => admin_setting('password_limit_expire', 60) + ])]]; + } + } + + // 查找用户 + $user = User::where('email', $email)->first(); + if (!$user) { + return [false, [400, __('Incorrect email or password')]]; + } + + // 验证密码 + if (!Helper::multiPasswordVerify( + $user->password_algo, + $user->password_salt, + $password, + $user->password) + ) { + // 增加密码错误计数 + if ((int)admin_setting('password_limit_enable', true)) { + $passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0); + Cache::put( + CacheKey::get('PASSWORD_ERROR_LIMIT', $email), + (int)$passwordErrorCount + 1, + 60 * (int)admin_setting('password_limit_expire', 60) + ); + } + return [false, [400, __('Incorrect email or password')]]; + } + + // 检查账户状态 + if ($user->banned) { + return [false, [400, __('Your account has been suspended')]]; + } + + // 更新最后登录时间 + $user->last_login_at = time(); + $user->save(); + + return [true, $user]; + } + + /** + * 处理密码重置 + * + * @param string $email 用户邮箱 + * @param string $emailCode 邮箱验证码 + * @param string $password 新密码 + * @return array [成功状态, 结果或错误信息] + */ + public function resetPassword(string $email, string $emailCode, string $password): array + { + // 检查重置请求限制 + $forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $email); + $forgetRequestLimit = (int)Cache::get($forgetRequestLimitKey); + if ($forgetRequestLimit >= 3) { + return [false, [429, __('Reset failed, Please try again later')]]; + } + + // 验证邮箱验证码 + if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $email)) !== (string)$emailCode) { + Cache::put($forgetRequestLimitKey, $forgetRequestLimit ? $forgetRequestLimit + 1 : 1, 300); + return [false, [400, __('Incorrect email verification code')]]; + } + + // 查找用户 + $user = User::where('email', $email)->first(); + if (!$user) { + return [false, [400, __('This email is not registered in the system')]]; + } + + // 更新密码 + $user->password = password_hash($password, PASSWORD_DEFAULT); + $user->password_algo = NULL; + $user->password_salt = NULL; + + if (!$user->save()) { + return [false, [500, __('Reset failed')]]; + } + + // 清除邮箱验证码 + Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email)); + + return [true, true]; + } +} \ No newline at end of file diff --git a/app/Services/Auth/MailLinkService.php b/app/Services/Auth/MailLinkService.php new file mode 100644 index 0000000..653df7a --- /dev/null +++ b/app/Services/Auth/MailLinkService.php @@ -0,0 +1,122 @@ +first(); + if (!$user) { + return [true, true]; // 成功但用户不存在,保护用户隐私 + } + + $code = Helper::guid(); + $key = CacheKey::get('TEMP_TOKEN', $code); + Cache::put($key, $user->id, 300); + Cache::put(CacheKey::get('LAST_SEND_LOGIN_WITH_MAIL_LINK_TIMESTAMP', $email), time(), 60); + + $redirectUrl = '/#/login?verify=' . $code . '&redirect=' . ($redirect ? $redirect : 'dashboard'); + if (admin_setting('app_url')) { + $link = admin_setting('app_url') . $redirectUrl; + } else { + $link = url($redirectUrl); + } + + $this->sendMailLinkEmail($user, $link); + + return [true, $link]; + } + + /** + * 发送邮件链接登录邮件 + * + * @param User $user 用户对象 + * @param string $link 登录链接 + * @return void + */ + private function sendMailLinkEmail(User $user, string $link): void + { + SendEmailJob::dispatch([ + 'email' => $user->email, + 'subject' => __('Login to :name', [ + 'name' => admin_setting('app_name', 'XBoard') + ]), + 'template_name' => 'login', + 'template_value' => [ + 'name' => admin_setting('app_name', 'XBoard'), + 'link' => $link, + 'url' => admin_setting('app_url') + ] + ]); + } + + /** + * 获取快速登录URL + * + * @param User $user 用户对象 + * @param string|null $redirect 重定向地址 + * @return string 登录URL + */ + public function getQuickLoginUrl(User $user, ?string $redirect = null): string + { + $code = Helper::guid(); + $key = CacheKey::get('TEMP_TOKEN', $code); + Cache::put($key, $user->id, 60); + + $redirectUrl = '/#/login?verify=' . $code . '&redirect=' . ($redirect ? $redirect : 'dashboard'); + + if (admin_setting('app_url')) { + return admin_setting('app_url') . $redirectUrl; + } else { + return url($redirectUrl); + } + } + + /** + * 处理Token登录 + * + * @param string $token 登录令牌 + * @return int|null 用户ID或null + */ + public function handleTokenLogin(string $token): ?int + { + $key = CacheKey::get('TEMP_TOKEN', $token); + $userId = Cache::get($key); + + if (!$userId) { + return null; + } + + $user = User::find($userId); + + if (!$user || $user->banned) { + return null; + } + + Cache::forget($key); + + return $userId; + } +} \ No newline at end of file diff --git a/app/Services/Auth/RegisterService.php b/app/Services/Auth/RegisterService.php new file mode 100644 index 0000000..9956b49 --- /dev/null +++ b/app/Services/Auth/RegisterService.php @@ -0,0 +1,209 @@ +ip())) ?? 0; + if ((int)$registerCountByIP >= (int)admin_setting('register_limit_count', 3)) { + return [false, [429, __('Register frequently, please try again after :minute minute', [ + 'minute' => admin_setting('register_limit_expire', 60) + ])]]; + } + } + + // 检查验证码 + if ((int)admin_setting('recaptcha_enable', 0)) { + $recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); + $recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); + if (!$recaptchaResp->isSuccess()) { + return [false, [400, __('Invalid code is incorrect')]]; + } + } + + // 检查邮箱白名单 + if ((int)admin_setting('email_whitelist_enable', 0)) { + if (!Helper::emailSuffixVerify( + $request->input('email'), + admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT)) + ) { + return [false, [400, __('Email suffix is not in the Whitelist')]]; + } + } + + // 检查Gmail限制 + if ((int)admin_setting('email_gmail_limit_enable', 0)) { + $prefix = explode('@', $request->input('email'))[0]; + if (strpos($prefix, '.') !== false || strpos($prefix, '+') !== false) { + return [false, [400, __('Gmail alias is not supported')]]; + } + } + + // 检查是否关闭注册 + if ((int)admin_setting('stop_register', 0)) { + return [false, [400, __('Registration has closed')]]; + } + + // 检查邀请码要求 + if ((int)admin_setting('invite_force', 0)) { + if (empty($request->input('invite_code'))) { + return [false, [422, __('You must use the invitation code to register')]]; + } + } + + // 检查邮箱验证 + if ((int)admin_setting('email_verify', 0)) { + if (empty($request->input('email_code'))) { + return [false, [422, __('Email verification code cannot be empty')]]; + } + if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { + return [false, [400, __('Incorrect email verification code')]]; + } + } + + // 检查邮箱是否存在 + $email = $request->input('email'); + $exist = User::where('email', $email)->first(); + if ($exist) { + return [false, [400201, __('Email already exists')]]; + } + + return [true, null]; + } + + /** + * 处理邀请码 + * + * @param User $user 用户对象 + * @param string|null $inviteCode 邀请码 + * @return array [是否成功, 错误消息] + */ + public function handleInviteCode(User $user, ?string $inviteCode): array + { + if (!$inviteCode) { + return [true, null]; + } + + $inviteCodeModel = InviteCode::where('code', $inviteCode) + ->where('status', 0) + ->first(); + + if (!$inviteCodeModel) { + if ((int)admin_setting('invite_force', 0)) { + return [false, [400, __('Invalid invitation code')]]; + } + return [true, null]; + } + + $user->invite_user_id = $inviteCodeModel->user_id ? $inviteCodeModel->user_id : null; + + if (!(int)admin_setting('invite_never_expire', 0)) { + $inviteCodeModel->status = true; + $inviteCodeModel->save(); + } + + return [true, null]; + } + + /** + * 处理试用计划 + * + * @param User $user 用户对象 + * @return void + */ + public function handleTryOut(User $user): void + { + if ((int)admin_setting('try_out_plan_id', 0)) { + $plan = Plan::find(admin_setting('try_out_plan_id')); + if ($plan) { + $user->transfer_enable = $plan->transfer_enable * 1073741824; + $user->plan_id = $plan->id; + $user->group_id = $plan->group_id; + $user->expired_at = time() + (admin_setting('try_out_hour', 1) * 3600); + $user->speed_limit = $plan->speed_limit; + } + } + } + + /** + * 注册用户 + * + * @param Request $request 请求对象 + * @return array [成功状态, 用户对象或错误信息] + */ + public function register(Request $request): array + { + // 验证注册数据 + [$valid, $error] = $this->validateRegister($request); + if (!$valid) { + return [false, $error]; + } + + $email = $request->input('email'); + $password = $request->input('password'); + + // 创建用户 + $user = new User(); + $user->email = $email; + $user->password = password_hash($password, PASSWORD_DEFAULT); + $user->uuid = Helper::guid(true); + $user->token = Helper::guid(); + $user->remind_expire = admin_setting('default_remind_expire', 1); + $user->remind_traffic = admin_setting('default_remind_traffic', 1); + + // 处理邀请码 + [$inviteSuccess, $inviteError] = $this->handleInviteCode($user, $request->input('invite_code')); + if (!$inviteSuccess) { + return [false, $inviteError]; + } + + // 处理试用计划 + $this->handleTryOut($user); + + // 保存用户 + if (!$user->save()) { + return [false, [500, __('Register failed')]]; + } + + // 清除邮箱验证码 + if ((int)admin_setting('email_verify', 0)) { + Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email)); + } + + // 更新最近登录时间 + $user->last_login_at = time(); + $user->save(); + + // 更新IP注册计数 + if ((int)admin_setting('register_limit_by_ip_enable', 0)) { + $registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0; + Cache::put( + CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip()), + (int)$registerCountByIP + 1, + (int)admin_setting('register_limit_expire', 60) * 60 + ); + } + + return [true, $user]; + } +} \ No newline at end of file diff --git a/app/Services/AuthService.php b/app/Services/AuthService.php index 9b73072..f82fdf9 100644 --- a/app/Services/AuthService.php +++ b/app/Services/AuthService.php @@ -40,7 +40,13 @@ class AuthService return $this->user->tokens()->get()->toArray(); } - public function removeSession(): bool + public function removeSession(string $sessionId): bool + { + $this->user->tokens()->where('id', $sessionId)->delete(); + return true; + } + + public function removeAllSessions(): bool { $this->user->tokens()->delete(); return true; @@ -54,4 +60,26 @@ class AuthService return $accessToken?->tokenable; } + + /** + * 解密认证数据 + * + * @param string $authorization + * @return array|null 用户数据或null + */ + public static function decryptAuthData(string $authorization): ?array + { + $user = self::findUserByBearerToken($authorization); + + if (!$user) { + return null; + } + + return [ + 'id' => $user->id, + 'email' => $user->email, + 'is_admin' => (bool)$user->is_admin, + 'is_staff' => (bool)$user->is_staff + ]; + } } diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php index 73848d1..329ae67 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -127,30 +127,30 @@ class OrderService $inviter = User::find($user->invite_user_id); if (!$inviter) return; + $commissionType = (int) $inviter->commission_type; + if ($commissionType === User::COMMISSION_TYPE_SYSTEM) { + $commissionType = (bool) admin_setting('commission_first_time_enable', true) ? User::COMMISSION_TYPE_ONETIME : User::COMMISSION_TYPE_PERIOD; + } $isCommission = false; - switch ((int) $inviter->commission_type) { - case 0: - $commissionFirstTime = (int) admin_setting('commission_first_time_enable', 1); - $isCommission = (!$commissionFirstTime || ($commissionFirstTime && !$this->haveValidOrder($user))); - break; - case 1: + switch ($commissionType) { + case User::COMMISSION_TYPE_PERIOD: $isCommission = true; break; - case 2: + case User::COMMISSION_TYPE_ONETIME: $isCommission = !$this->haveValidOrder($user); break; } if (!$isCommission) return; - if ($inviter && $inviter->commission_rate) { + if ($inviter->commission_rate) { $order->commission_balance = $order->total_amount * ($inviter->commission_rate / 100); } else { $order->commission_balance = $order->total_amount * (admin_setting('invite_commission', 10) / 100); } } - private function haveValidOrder(User $user) + private function haveValidOrder(User $user): Order|null { return Order::where('user_id', $user->id) ->whereNotIn('status', [0, 2]) diff --git a/app/Services/PlanService.php b/app/Services/PlanService.php index 52549cf..e67363d 100644 --- a/app/Services/PlanService.php +++ b/app/Services/PlanService.php @@ -74,10 +74,9 @@ class PlanService // 转换周期格式为新版格式 $periodKey = self::getPeriodKey($period); + $price = $this->plan->prices[$periodKey] ?? null; - - // 检查价格时使用新版格式 - if (!isset($this->plan->prices[$periodKey]) || $this->plan->prices[$periodKey] === NULL) { + if ($price === null) { throw new ApiException(__('This payment period cannot be purchased, please choose another period')); } diff --git a/app/Services/Plugin/HookManager.php b/app/Services/Plugin/HookManager.php index 4147962..6e3ef51 100644 --- a/app/Services/Plugin/HookManager.php +++ b/app/Services/Plugin/HookManager.php @@ -45,9 +45,16 @@ class HookManager * @param mixed ...$args 其他参数 * @return mixed */ - public static function filter(string $hook, mixed $value): mixed + public static function filter(string $hook, mixed $value, mixed ...$args): mixed { - return Eventy::filter($hook, $value); + if (!self::hasHook($hook)) { + return $value; + } + + /** @phpstan-ignore-next-line */ + $result = Eventy::filter($hook, $value, ...$args); + + return $result; } /** @@ -88,4 +95,10 @@ class HookManager Eventy::removeAction($hook, $callback); Eventy::removeFilter($hook, $callback); } + + private static function hasHook(string $hook): bool + { + // Implementation of hasHook method + return true; // Placeholder return, actual implementation needed + } } \ No newline at end of file diff --git a/app/Services/ServerService.php b/app/Services/ServerService.php index b2ff59d..e660953 100644 --- a/app/Services/ServerService.php +++ b/app/Services/ServerService.php @@ -15,14 +15,18 @@ class ServerService * 获取所有服务器列表 * @return Collection */ - public static function getAllServers() + public static function getAllServers(): Collection { - return Server::orderBy('sort', 'ASC') - ->get() - ->transform(function (Server $server) { - $server->loadServerStatus(); - return $server; - }); + $query = Server::orderBy('sort', 'ASC'); + + return $query->get()->append([ + 'last_check_at', + 'last_push_at', + 'online', + 'is_online', + 'available_status', + 'cache_key' + ]); } /** @@ -32,28 +36,25 @@ class ServerService */ public static function getAvailableServers(User $user): array { - return Server::whereJsonContains('group_ids', (string) $user->group_id) + $servers = Server::whereJsonContains('group_ids', (string) $user->group_id) ->where('show', true) ->orderBy('sort', 'ASC') ->get() - ->transform(function (Server $server) use ($user) { - $server->loadParentCreatedAt(); - $server->handlePortAllocation(); - $server->loadServerStatus(); - if ($server->type === 'shadowsocks') { - $server->server_key = Helper::getServerKey($server->created_at, 16); - } - $server->generateShadowsocksPassword($user); + ->append(['last_check_at', 'last_push_at', 'online', 'is_online', 'available_status', 'cache_key', 'server_key']); - return $server; - }) - ->toArray(); + $servers = collect($servers)->map(function ($server) use ($user) { + // 判断动态端口 + if (str_contains($server->port, '-')) { + $server->port = (string) Helper::randomPort($server->port); + $server->ports = $server->port; + } + $server->password = $server->generateShadowsocksPassword($user); + return $server; + })->toArray(); + + return $servers; } - /** - * 加 - */ - /** * 根据权限组获取可用的用户列表 * @param array $groupIds diff --git a/app/Services/StatisticalService.php b/app/Services/StatisticalService.php index 8d38c63..e57d6ae 100644 --- a/app/Services/StatisticalService.php +++ b/app/Services/StatisticalService.php @@ -122,7 +122,7 @@ class StatisticalService $key = "{$rate}_{$uid}"; $stats[$key] = $stats[$key] ?? [ 'record_at' => $this->startAt, - 'server_rate' => number_format($rate, 2, '.', ''), + 'server_rate' => number_format((float) $rate, 2, '.', ''), 'u' => 0, 'd' => 0, 'user_id' => intval($userId), @@ -156,27 +156,40 @@ class StatisticalService /** - * 获取缓存中的服务器爆表 + * Retrieve server statistics from Redis cache. + * + * @return array */ - public function getStatServer() + public function getStatServer(): array { + /** @var array $stats */ $stats = []; $statsServer = $this->redis->zrange($this->statServerKey, 0, -1, true); + foreach ($statsServer as $member => $value) { - list($serverType, $serverId, $type) = explode('_', $member); + $parts = explode('_', $member); + if (count($parts) !== 3) { + continue; // Skip malformed members + } + [$serverType, $serverId, $type] = $parts; + + if (!in_array($type, ['u', 'd'], true)) { + continue; // Skip invalid types + } + $key = "{$serverType}_{$serverId}"; if (!isset($stats[$key])) { $stats[$key] = [ - 'server_id' => intval($serverId), + 'server_id' => (int) $serverId, 'server_type' => $serverType, - 'u' => 0, - 'd' => 0, + 'u' => 0.0, + 'd' => 0.0, ]; } - $stats[$key][$type] += $value; + $stats[$key][$type] += (float) $value; } - return array_values($stats); + return array_values($stats); } /** @@ -281,25 +294,22 @@ class StatisticalService ->where('record_type', 'd'); } ) + ->withSum('stats as u', 'u') // 预加载 u 的总和 + ->withSum('stats as d', 'd') // 预加载 d 的总和 ->get() - ->each(function ($item) { - $item->u = (int) $item->stats()->sum('u'); - $item->d = (int) $item->stats()->sum('d'); - $item->total = (int) $item->u + $item->d; - $item->server_name = optional($item->parent)->name ?? $item->name; - $item->server_id = $item->id; - $item->server_type = $item->type; + ->map(function ($item) { + return [ + 'server_name' => optional($item->parent)->name ?? $item->name, + 'server_id' => $item->id, + 'server_type' => $item->type, + 'u' => (int) $item->u, + 'd' => (int) $item->d, + 'total' => (int) $item->u + (int) $item->d, + ]; }) ->sortByDesc('total') - ->select([ - 'server_name', - 'server_id', - 'server_type', - 'u', - 'd', - 'total' - ]) - ->values()->toArray(); + ->values() + ->toArray(); return $statistics; } diff --git a/app/Services/UserOnlineService.php b/app/Services/UserOnlineService.php index 5445fa0..8ddc556 100644 --- a/app/Services/UserOnlineService.php +++ b/app/Services/UserOnlineService.php @@ -156,13 +156,17 @@ class UserOnlineService } /** - * 计算设备数量 + * Calculate the number of devices based on IPs array and device limit mode. + * + * @param array $ipsArray Array containing IP data + * @return int Number of devices */ private function calculateDeviceCount(array $ipsArray): int { - // 设备限制模式 - return match ((int) admin_setting('device_limit_mode', 0)) { - // 宽松模式 + $mode = (int) admin_setting('device_limit_mode', 0); + + return match ($mode) { + // Loose mode: Count unique IPs (ignoring suffixes after '_') 1 => collect($ipsArray) ->filter(fn(mixed $data): bool => is_array($data) && isset($data['aliveips'])) ->flatMap( @@ -173,9 +177,12 @@ class UserOnlineService ) ->unique() ->count(), + // Strict mode: Sum total number of alive IPs 0 => collect($ipsArray) ->filter(fn(mixed $data): bool => is_array($data) && isset($data['aliveips'])) - ->sum(fn(array $data): int => count($data['aliveips'])) + ->sum(fn(array $data): int => count($data['aliveips'])), + // Handle invalid modes + default => throw new \InvalidArgumentException("Invalid device limit mode: $mode"), }; } } \ No newline at end of file diff --git a/app/Services/UserService.php b/app/Services/UserService.php index a733bfc..a085630 100644 --- a/app/Services/UserService.php +++ b/app/Services/UserService.php @@ -12,7 +12,7 @@ use App\Services\Plugin\HookManager; class UserService { - private function calcResetDayByMonthFirstDay() + private function calcResetDayByMonthFirstDay(): int { $today = date('d'); $lastDay = date('d', strtotime('last day of +0 months')); @@ -51,55 +51,34 @@ class UserService return (int) (($nextYear - time()) / 86400); } - public function getResetDay(User $user) + public function getResetDay(User $user): ?int { - if (!isset($user->plan)) { - $user->plan = Plan::find($user->plan_id); - } - if ($user->expired_at <= time() || $user->expired_at === NULL) + // 前置条件检查 + if ($user->expired_at <= time() || $user->expired_at === null) { return null; - // if reset method is not reset - if ($user->plan->reset_traffic_method === 2) - return null; - switch (true) { - case ($user->plan->reset_traffic_method === NULL): { - $resetTrafficMethod = admin_setting('reset_traffic_method', 0); - switch ((int) $resetTrafficMethod) { - // month first day - case 0: - return $this->calcResetDayByMonthFirstDay(); - // expire day - case 1: - return $this->calcResetDayByExpireDay($user->expired_at); - // no action - case 2: - return null; - // year first day - case 3: - return $this->calcResetDayByYearFirstDay(); - // year expire day - case 4: - return $this->calcResetDayByYearExpiredAt($user->expired_at); - } - break; - } - case ($user->plan->reset_traffic_method === 0): { - return $this->calcResetDayByMonthFirstDay(); - } - case ($user->plan->reset_traffic_method === 1): { - return $this->calcResetDayByExpireDay($user->expired_at); - } - case ($user->plan->reset_traffic_method === 2): { - return null; - } - case ($user->plan->reset_traffic_method === 3): { - return $this->calcResetDayByYearFirstDay(); - } - case ($user->plan->reset_traffic_method === 4): { - return $this->calcResetDayByYearExpiredAt($user->expired_at); - } } - 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; + + return $handler ? $handler() : null; } public function isAvailable(User $user) diff --git a/app/Support/Setting.php b/app/Support/Setting.php index d112ef9..6b7165b 100644 --- a/app/Support/Setting.php +++ b/app/Support/Setting.php @@ -32,10 +32,11 @@ class Setting /** * 设置配置信息. * - * @param array $data - * @return $this + * @param string $key + * @param mixed $value + * @return bool 设置是否成功 */ - public function set($key, $value = null): bool + public function set(string $key, $value = null): bool { if (is_array($value)) { $value = json_encode($value); @@ -50,12 +51,12 @@ class Setting /** * 保存配置到数据库. * - * @param array $data - * @return $this + * @param array $settings 要保存的设置数组 + * @return bool 保存是否成功 */ - public function save(array $data = []): bool + public function save(array $settings): bool { - foreach ($data as $key => $value) { + foreach ($settings as $key => $value) { $this->set($key, $value); } @@ -99,4 +100,22 @@ class Setting { return $this->fromDatabase(); } + + /** + * 更新单个设置项 + * + * @param string $key 设置键名 + * @param mixed $value 设置值 + * @return bool 更新是否成功 + */ + public function update(string $key, $value): bool + { + if (is_array($value)) { + $value = json_encode($value); + } + $key = strtolower($key); + SettingModel::updateOrCreate(['name' => $key], ['value' => $value]); + $this->cache->forget(self::CACHE_KEY); + return true; + } } diff --git a/app/Utils/CacheKey.php b/app/Utils/CacheKey.php index 132186e..384f012 100644 --- a/app/Utils/CacheKey.php +++ b/app/Utils/CacheKey.php @@ -31,6 +31,22 @@ class CacheKey 'MULTI_SERVER_TUIC_ONLINE_USER' => 'TUIC节点多服务器在线用户', 'SERVER_TUIC_LAST_CHECK_AT' => 'TUIC节点最后检查时间', 'SERVER_TUIC_LAST_PUSH_AT' => 'TUIC节点最后推送时间', + 'SERVER_SOCKS_ONLINE_USER' => 'socks节点在线用户', + 'MULTI_SERVER_SOCKS_ONLINE_USER' => 'socks节点多服务器在线用户', + 'SERVER_SOCKS_LAST_CHECK_AT' => 'socks节点最后检查时间', + 'SERVER_SOCKS_LAST_PUSH_AT' => 'socks节点最后推送时间', + 'SERVER_NAIVE_ONLINE_USER' => 'naive节点在线用户', + 'MULTI_SERVER_NAIVE_ONLINE_USER' => 'naive节点多服务器在线用户', + 'SERVER_NAIVE_LAST_CHECK_AT' => 'naive节点最后检查时间', + 'SERVER_NAIVE_LAST_PUSH_AT' => 'naive节点最后推送时间', + 'SERVER_HTTP_ONLINE_USER' => 'http节点在线用户', + 'MULTI_SERVER_HTTP_ONLINE_USER' => 'http节点多服务器在线用户', + 'SERVER_HTTP_LAST_CHECK_AT' => 'http节点最后检查时间', + 'SERVER_HTTP_LAST_PUSH_AT' => 'http节点最后推送时间', + 'SERVER_MIERU_ONLINE_USER' => 'mieru节点在线用户', + 'MULTI_SERVER_MIERU_ONLINE_USER' => 'mieru节点多服务器在线用户', + 'SERVER_MIERU_LAST_CHECK_AT' => 'mieru节点最后检查时间', + 'SERVER_MIERU_LAST_PUSH_AT' => 'mieru节点最后推送时间', 'TEMP_TOKEN' => '临时令牌', 'LAST_SEND_EMAIL_REMIND_TRAFFIC' => '最后发送流量邮件提醒', 'SCHEDULE_LAST_CHECK_AT' => '计划任务最后检查时间', diff --git a/app/Utils/Helper.php b/app/Utils/Helper.php index f974af8..d153875 100644 --- a/app/Utils/Helper.php +++ b/app/Utils/Helper.php @@ -134,7 +134,7 @@ class Helper public static function randomPort($range): int { $portRange = explode('-', $range); - return random_int($portRange[0], $portRange[1]); + return random_int((int)$portRange[0], (int)$portRange[1]); } public static function base64EncodeUrlSafe($data) diff --git a/composer.json b/composer.json index eca5f28..6b9f00c 100755 --- a/composer.json +++ b/composer.json @@ -37,8 +37,10 @@ "require-dev": { "barryvdh/laravel-debugbar": "^3.9", "fakerphp/faker": "^1.9.1", + "larastan/larastan": "^3.0", "mockery/mockery": "^1.6", "nunomaduro/collision": "^8.0", + "nunomaduro/larastan": "^3.1", "orangehill/iseed": "^3.0", "phpunit/phpunit": "^10.5", "spatie/laravel-ignition": "^2.4" diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..d14e701 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,17 @@ +includes: + - vendor/larastan/larastan/extension.neon + - vendor/nesbot/carbon/extension.neon + +parameters: + + paths: + - app/ + + # Level 10 is the highest level + level: 5 + + ignoreErrors: + - '#Negated boolean expression is always false\.#' + +# excludePaths: +# - ./*/*/FileToBeExcluded.php \ No newline at end of file diff --git a/public/assets/admin/assets/index.js b/public/assets/admin/assets/index.js index 6e7a0c1..9dce2a5 100644 --- a/public/assets/admin/assets/index.js +++ b/public/assets/admin/assets/index.js @@ -1,9 +1,9 @@ -import{r as m,j as e,t as Sl,c as kl,I as Ka,a as Ls,S as _a,u as ks,b as wa,R as fn,d as gn,e as Tl,F as Dl,C as Pl,L as jn,T as vn,f as bn,g as El,h as Rl,i as Il,k as A,z as h,l as M,m as fe,n as ye,o as ie,p as Ze,q as Ce,s as it,v as Vl,O as Ca,w as Ml,x as Fl,y as Ol,A as zl,B as Ll,D as Al,Q as $l,E as ql,G as Hl,H as Ul,P as Kl,J as Bl,K as Gl,M as Wl,N as Yl,U as yn,V as Nn,W as $t,X as qt,Y as Sa,Z as Xe,_ as Ht,$ as Ut,a0 as _n,a1 as wn,a2 as Cn,a3 as ka,a4 as Sn,a5 as Ql,a6 as kn,a7 as Tn,a8 as Dn,a9 as Pn,aa as As,ab as En,ac as Jl,ad as Rn,ae as In,af as Zl,ag as Xl,ah as ei,ai as si,aj as ti,ak as ai,al as ni,am as ri,an as li,ao as ii,ap as oi,aq as Vn,ar as ci,as as di,at as $s,au as Mn,av as ui,aw as mi,ax as Fn,ay as Ta,az as xi,aA as hi,aB as Ba,aC as pi,aD as On,aE as fi,aF as zn,aG as gi,aH as ji,aI as vi,aJ as bi,aK as yi,aL as Ni,aM as Ln,aN as _i,aO as wi,aP as Ci,aQ as Fe,aR as Si,aS as An,aT as $n,aU as ki,aV as Ti,aW as qn,aX as Di,aY as Pi,aZ as Je,a_ as Ei,a$ as Ri,b0 as Hn,b1 as Un,b2 as Kn,b3 as Ii,b4 as Vi,b5 as Mi,b6 as Bn,b7 as Fi,b8 as Da,b9 as Gn,ba as Oi,bb as Wn,bc as zi,bd as Yn,be as Li,bf as Qn,bg as Jn,bh as Ai,bi as $i,bj as Zn,bk as qi,bl as Hi,bm as Xn,bn as Ui,bo as er,bp as Ki,bq as Bi,br as ls,bs as jt,bt as Gi,bu as Wi,bv as Yi,bw as Qi,bx as Ji,by as Zi,bz as Ga,bA as Wa,bB as Xi,bC as eo,bD as so,bE as to,bF as ao,bG as pa,bH as pt,bI as no,bJ as ro,bK as lo,bL as Ya,bM as fa,bN as ga,bO as io,bP as oo,bQ as sr,bR as co,bS as Pa,bT as uo,bU as mo,bV as xo,bW as tr,bX as ar,bY as ho,bZ as po,b_ as fo,b$ as go,c0 as jo,c1 as nr,c2 as vo,c3 as bo,c4 as yo,c5 as No,c6 as Vt,c7 as Re,c8 as Qa,c9 as _o,ca as rr,cb as lr,cc as ir,cd as or,ce as cr,cf as dr,cg as wo,ch as Co,ci as So,cj as Kt,ck as qs,cl as os,cm as ts,cn as as,co as cs,cp as ds,cq as us,cr as ko,cs as To,ct as Do,cu as Po,cv as Eo,cw as Ro,cx as Io,cy as Vo,cz as Mo,cA as ja,cB as Ea,cC as Ra,cD as Fo,cE as Ts,cF as Ds,cG as vt,cH as Oo,cI as Mt,cJ as zo,cK as Ja,cL as ur,cM as Za,cN as Ft,cO as Lo,cP as Ao,cQ as $o,cR as qo,cS as mr,cT as Ho,cU as Uo,cV as xr,cW as va,cX as hr,cY as Ko,cZ as pr,c_ as fr,c$ as Bo,d0 as Go,d1 as Wo,d2 as Yo,d3 as Qo}from"./vendor.js";import"./index.js";var cp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dp(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Jo(s){if(s.__esModule)return s;var n=s.default;if(typeof n=="function"){var a=function r(){return this instanceof r?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};a.prototype=n.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(s).forEach(function(r){var l=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(a,r,l.get?l:{enumerable:!0,get:function(){return s[r]}})}),a}const Zo={theme:"system",setTheme:()=>null},gr=m.createContext(Zo);function Xo({children:s,defaultTheme:n="system",storageKey:a="vite-ui-theme",...r}){const[l,c]=m.useState(()=>localStorage.getItem(a)||n);m.useEffect(()=>{const u=window.document.documentElement;if(u.classList.remove("light","dark"),l==="system"){const x=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";u.classList.add(x);return}u.classList.add(l)},[l]);const o={theme:l,setTheme:u=>{localStorage.setItem(a,u),c(u)}};return e.jsx(gr.Provider,{...r,value:o,children:s})}const ec=()=>{const s=m.useContext(gr);if(s===void 0)throw new Error("useTheme must be used within a ThemeProvider");return s},sc=function(){const n=typeof document<"u"&&document.createElement("link").relList;return n&&n.supports&&n.supports("modulepreload")?"modulepreload":"preload"}(),tc=function(s,n){return new URL(s,n).href},Xa={},ue=function(n,a,r){let l=Promise.resolve();if(a&&a.length>0){const o=document.getElementsByTagName("link"),u=document.querySelector("meta[property=csp-nonce]"),x=u?.nonce||u?.getAttribute("nonce");l=Promise.allSettled(a.map(i=>{if(i=tc(i,r),i in Xa)return;Xa[i]=!0;const d=i.endsWith(".css"),f=d?'[rel="stylesheet"]':"";if(!!r)for(let C=o.length-1;C>=0;C--){const p=o[C];if(p.href===i&&(!d||p.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${i}"]${f}`))return;const P=document.createElement("link");if(P.rel=d?"stylesheet":sc,d||(P.as="script"),P.crossOrigin="",P.href=i,x&&P.setAttribute("nonce",x),document.head.appendChild(P),d)return new Promise((C,p)=>{P.addEventListener("load",C),P.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${i}`)))})}))}function c(o){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=o,window.dispatchEvent(u),!u.defaultPrevented)throw o}return l.then(o=>{for(const u of o||[])u.status==="rejected"&&c(u.reason);return n().catch(c)})};function _(...s){return Sl(kl(s))}const tt=Ls("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),D=m.forwardRef(({className:s,variant:n,size:a,asChild:r=!1,children:l,disabled:c,loading:o=!1,leftSection:u,rightSection:x,...i},d)=>{const f=r?_a:"button";return e.jsxs(f,{className:_(tt({variant:n,size:a,className:s})),disabled:o||c,ref:d,...i,children:[(u&&o||!u&&!x&&o)&&e.jsx(Ka,{className:"mr-2 h-4 w-4 animate-spin"}),!o&&u&&e.jsx("div",{className:"mr-2",children:u}),l,!o&&x&&e.jsx("div",{className:"ml-2",children:x}),x&&o&&e.jsx(Ka,{className:"ml-2 h-4 w-4 animate-spin"})]})});D.displayName="Button";function Gs({className:s,minimal:n=!1}){const a=ks();return e.jsx("div",{className:_("h-svh w-full",s),children:e.jsxs("div",{className:"m-auto flex h-full w-full flex-col items-center justify-center gap-2",children:[!n&&e.jsx("h1",{className:"text-[7rem] font-bold leading-tight",children:"500"}),e.jsxs("span",{className:"font-medium",children:["Oops! Something went wrong ",":')"]}),e.jsxs("p",{className:"text-center text-muted-foreground",children:["We apologize for the inconvenience. ",e.jsx("br",{})," Please try again later."]}),!n&&e.jsxs("div",{className:"mt-6 flex gap-4",children:[e.jsx(D,{variant:"outline",onClick:()=>a(-1),children:"Go Back"}),e.jsx(D,{onClick:()=>a("/"),children:"Back to Home"})]})]})})}function en(){const s=ks();return e.jsx("div",{className:"h-svh",children:e.jsxs("div",{className:"m-auto flex h-full w-full flex-col items-center justify-center gap-2",children:[e.jsx("h1",{className:"text-[7rem] font-bold leading-tight",children:"404"}),e.jsx("span",{className:"font-medium",children:"Oops! Page Not Found!"}),e.jsxs("p",{className:"text-center text-muted-foreground",children:["It seems like the page you're looking for ",e.jsx("br",{}),"does not exist or might have been removed."]}),e.jsxs("div",{className:"mt-6 flex gap-4",children:[e.jsx(D,{variant:"outline",onClick:()=>s(-1),children:"Go Back"}),e.jsx(D,{onClick:()=>s("/"),children:"Back to Home"})]})]})})}function ac(){return e.jsx("div",{className:"h-svh",children:e.jsxs("div",{className:"m-auto flex h-full w-full flex-col items-center justify-center gap-2",children:[e.jsx("h1",{className:"text-[7rem] font-bold leading-tight",children:"503"}),e.jsx("span",{className:"font-medium",children:"Website is under maintenance!"}),e.jsxs("p",{className:"text-center text-muted-foreground",children:["The site is not available at the moment. ",e.jsx("br",{}),"We'll be back online shortly."]}),e.jsx("div",{className:"mt-6 flex gap-4",children:e.jsx(D,{variant:"outline",children:"Learn more"})})]})})}function nc(s){return typeof s>"u"}function rc(s){return s===null}function lc(s){return rc(s)||nc(s)}class ic{storage;prefixKey;constructor(n){this.storage=n.storage,this.prefixKey=n.prefixKey}getKey(n){return`${this.prefixKey}${n}`.toUpperCase()}set(n,a,r=null){const l=JSON.stringify({value:a,time:Date.now(),expire:r!==null?new Date().getTime()+r*1e3:null});this.storage.setItem(this.getKey(n),l)}get(n,a=null){const r=this.storage.getItem(this.getKey(n));if(!r)return{value:a,time:0};try{const l=JSON.parse(r),{value:c,time:o,expire:u}=l;return lc(u)||u>new Date().getTime()?{value:c,time:o}:(this.remove(n),{value:a,time:0})}catch{return this.remove(n),{value:a,time:0}}}remove(n){this.storage.removeItem(this.getKey(n))}clear(){this.storage.clear()}}function jr({prefixKey:s="",storage:n=sessionStorage}){return new ic({prefixKey:s,storage:n})}const vr="Xboard_",oc=function(s={}){return jr({prefixKey:s.prefixKey||"",storage:localStorage})},cc=function(s={}){return jr({prefixKey:s.prefixKey||"",storage:sessionStorage})},Bt=oc({prefixKey:vr});cc({prefixKey:vr});const br="access_token";function ft(){return Bt.get(br)}function yr(){Bt.remove(br)}const sn=["/sign-in","/sign-in-2","/sign-up","/forgot-password","/otp"];function dc({children:s}){const n=ks(),a=wa(),r=ft();return m.useEffect(()=>{if(!r.value&&!sn.includes(a.pathname)){const l=encodeURIComponent(a.pathname+a.search);n(`/sign-in?redirect=${l}`)}},[r.value,a.pathname,a.search,n]),sn.includes(a.pathname)||r.value?e.jsx(e.Fragment,{children:s}):null}const Se=m.forwardRef(({className:s,orientation:n="horizontal",decorative:a=!0,...r},l)=>e.jsx(fn,{ref:l,decorative:a,orientation:n,className:_("shrink-0 bg-border",n==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Se.displayName=fn.displayName;const uc=Ls("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ot=m.forwardRef(({className:s,...n},a)=>e.jsx(gn,{ref:a,className:_(uc(),s),...n}));Ot.displayName=gn.displayName;const Ne=Dl,Nr=m.createContext({}),b=({...s})=>e.jsx(Nr.Provider,{value:{name:s.name},children:e.jsx(Pl,{...s})}),Gt=()=>{const s=m.useContext(Nr),n=m.useContext(_r),{getFieldState:a,formState:r}=Tl(),l=a(s.name,r);if(!s)throw new Error("useFormField should be used within ");const{id:c}=n;return{id:c,name:s.name,formItemId:`${c}-form-item`,formDescriptionId:`${c}-form-item-description`,formMessageId:`${c}-form-item-message`,...l}},_r=m.createContext({}),v=m.forwardRef(({className:s,...n},a)=>{const r=m.useId();return e.jsx(_r.Provider,{value:{id:r},children:e.jsx("div",{ref:a,className:_("space-y-2",s),...n})})});v.displayName="FormItem";const y=m.forwardRef(({className:s,...n},a)=>{const{error:r,formItemId:l}=Gt();return e.jsx(Ot,{ref:a,className:_(r&&"text-destructive",s),htmlFor:l,...n})});y.displayName="FormLabel";const N=m.forwardRef(({...s},n)=>{const{error:a,formItemId:r,formDescriptionId:l,formMessageId:c}=Gt();return e.jsx(_a,{ref:n,id:r,"aria-describedby":a?`${l} ${c}`:`${l}`,"aria-invalid":!!a,...s})});N.displayName="FormControl";const z=m.forwardRef(({className:s,...n},a)=>{const{formDescriptionId:r}=Gt();return e.jsx("p",{ref:a,id:r,className:_("text-[0.8rem] text-muted-foreground",s),...n})});z.displayName="FormDescription";const k=m.forwardRef(({className:s,children:n,...a},r)=>{const{error:l,formMessageId:c}=Gt(),o=l?String(l?.message):n;return o?e.jsx("p",{ref:r,id:c,className:_("text-[0.8rem] font-medium text-destructive",s),...a,children:o}):null});k.displayName="FormMessage";const Wt=El,bt=m.forwardRef(({className:s,...n},a)=>e.jsx(jn,{ref:a,className:_("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",s),...n}));bt.displayName=jn.displayName;const Ke=m.forwardRef(({className:s,...n},a)=>e.jsx(vn,{ref:a,className:_("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",s),...n}));Ke.displayName=vn.displayName;const Ns=m.forwardRef(({className:s,...n},a)=>e.jsx(bn,{ref:a,className:_("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...n}));Ns.displayName=bn.displayName;function _e(s=void 0,n="YYYY-MM-DD HH:mm:ss"){return s==null?"":(Math.floor(s).toString().length===10&&(s=s*1e3),Rl(s).format(n))}function mc(s=void 0,n="YYYY-MM-DD"){return _e(s,n)}function Qs(s){const n=typeof s=="string"?parseFloat(s):s;return isNaN(n)?"0.00":n.toFixed(2)}function Fs(s,n=!0){if(s==null)return n?"¥0.00":"0.00";const a=typeof s=="string"?parseFloat(s):s;if(isNaN(a))return n?"¥0.00":"0.00";const l=(a/100).toFixed(2).replace(/\.?0+$/,c=>c.includes(".")?".00":c);return n?`¥${l}`:l}function zt(s){return new Promise(n=>{(async()=>{try{if(navigator.clipboard)await navigator.clipboard.writeText(s);else{const r=document.createElement("textarea");r.value=s,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select();const l=document.execCommand("copy");if(document.body.removeChild(r),!l)throw new Error("execCommand failed")}n(!0)}catch(r){console.error(r),n(!1)}})()})}function hs(s){const n=s/1024,a=n/1024,r=a/1024,l=r/1024;return l>=1?Qs(l)+" TB":r>=1?Qs(r)+" GB":a>=1?Qs(a)+" MB":Qs(n)+" KB"}const xc="locale";function hc(){return Bt.get(xc)}function wr(){yr();const s=window.location.pathname,n=s&&!["/404","/sign-in"].includes(s),a=new URL(window.location.href),l=`${a.pathname.split("/")[1]?`/${a.pathname.split("/")[1]}`:""}#/sign-in`;window.location.href=l+(n?`?redirect=${s}`:"")}const pc=["/passport/auth/login","/passport/auth/token2Login","/passport/auth/register","/guest/comm/config","/passport/comm/sendEmailVerify","/passport/auth/forget"];function fc(){const s=window.settings?.base_url||"/";return s.endsWith("/")?s+"api/v2":s+"/api/v2"}const V=Il.create({baseURL:fc(),timeout:12e3,headers:{"Content-Type":"application/json"}});V.interceptors.request.use(s=>{s.method?.toLowerCase()==="get"&&(s.params={...s.params,t:Date.now()});const n=ft();if(!pc.includes(s.url?.split("?")[0]||"")){if(!n.value)return wr(),Promise.reject({code:-1,message:"未登录"});s.headers.Authorization=n.value}return s.headers["Content-Language"]=hc().value||"zh-CN",s},s=>Promise.reject(s));V.interceptors.response.use(s=>s?.data||{code:-1,message:"未知错误"},s=>{const n=s.response?.status,a=s.response?.data?.message;return(n===401||n===403)&&wr(),A.error(a||{401:"登录已过期",403:"没有权限",404:"资源或接口不存在"}[n]||"未知异常"),Promise.reject(s.response?.data||{data:null,code:-1,message:"未知错误"})});const gc="access_token";function jc(s){Bt.set(gc,s)}const U=window?.settings?.secure_path,vc=s=>V.get(U+"/stat/getOrder",{params:s}),bc=()=>V.get(U+"/stat/getStats"),tn=s=>V.get(U+"/stat/getTrafficRank",{params:s}),yc=()=>V.get(U+"/theme/getThemes"),Nc=s=>V.post(U+"/theme/getThemeConfig",{name:s}),_c=(s,n)=>V.post(U+"/theme/saveThemeConfig",{name:s,config:n}),wc=s=>{const n=new FormData;return n.append("file",s),V.post(U+"/theme/upload",n,{headers:{"Content-Type":"multipart/form-data"}})},Cc=s=>V.post(U+"/theme/delete",{name:s}),Sc=s=>V.post(U+"/config/save",s),Cr=()=>V.get(U+"/server/manage/getNodes"),kc=s=>V.post(U+"/server/manage/save",s),Tc=s=>V.post(U+"/server/manage/drop",s),Dc=s=>V.post(U+"/server/manage/copy",s),Pc=s=>V.post(U+"/server/manage/update",s),Ec=s=>V.post(U+"/server/manage/sort",s),yt=()=>V.get(U+"/server/group/fetch"),Rc=s=>V.post(U+"/server/group/save",s),Ic=s=>V.post(U+"/server/group/drop",s),Sr=()=>V.get(U+"/server/route/fetch"),Vc=s=>V.post(U+"/server/route/save",s),Mc=s=>V.post(U+"/server/route/drop",s),Fc=()=>V.get(U+"/payment/fetch"),Oc=()=>V.get(U+"/payment/getPaymentMethods"),zc=s=>V.post(U+"/payment/getPaymentForm",s),Lc=s=>V.post(U+"/payment/save",s),Ac=s=>V.post(U+"/payment/drop",s),$c=s=>V.post(U+"/payment/show",s),qc=s=>V.post(U+"/payment/sort",s),Hc=s=>V.post(U+"/notice/save",s),Uc=s=>V.post(U+"/notice/drop",s),Kc=s=>V.post(U+"/notice/show",s),Bc=()=>V.get(U+"/knowledge/fetch"),Gc=s=>V.get(U+"/knowledge/fetch?id="+s),Wc=s=>V.post(U+"/knowledge/save",s),Yc=s=>V.post(U+"/knowledge/drop",s),Qc=s=>V.post(U+"/knowledge/show",s),Jc=s=>V.post(U+"/knowledge/sort",s),Hs=()=>V.get(U+"/plan/fetch"),Zc=s=>V.post(U+"/plan/save",s),na=s=>V.post(U+"/plan/update",s),Xc=s=>V.post(U+"/plan/drop",s),ed=s=>V.post(U+"/plan/sort",{ids:s}),sd=async s=>V.post(U+"/order/fetch",s),td=s=>V.post(U+"/order/detail",s),ad=s=>V.post(U+"/order/paid",s),nd=s=>V.post(U+"/order/cancel",s),an=s=>V.post(U+"/order/update",s),rd=s=>V.post(U+"/order/assign",s),ld=s=>V.post(U+"/coupon/fetch",s),id=s=>V.post(U+"/coupon/generate",s),od=s=>V.post(U+"/coupon/drop",s),cd=s=>V.post(U+"/coupon/update",s),dd=s=>V.post(U+"/user/fetch",s),ud=s=>V.post(U+"/user/update",s),md=s=>V.post(U+"/user/resetSecret",s),xd=s=>V.post(U+"/user/generate",s),hd=s=>V.post(U+"/stat/getStatUser",s),pd=s=>V.post(U+"/ticket/fetch",s),fd=s=>V.get(U+"/ticket/fetch?id= "+s),gd=s=>V.post(U+"/ticket/close",{id:s}),fs=(s="")=>V.get(U+"/config/fetch?key="+s),gs=s=>V.post(U+"/config/save",s),jd=()=>V.get(U+"/config/getEmailTemplate"),vd=()=>V.post(U+"/config/testSendMail"),bd=()=>V.post(U+"/config/setTelegramWebhook"),yd=h.object({subscribe_template_singbox:h.string().nullable(),subscribe_template_clash:h.string().nullable(),subscribe_template_clashmeta:h.string().nullable(),subscribe_template_stash:h.string().nullable(),subscribe_template_surge:h.string().nullable()}),Nd={subscribe_template_singbox:"",subscribe_template_clash:"",subscribe_template_clashmeta:"",subscribe_template_stash:"",subscribe_template_surge:""};function _d(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),[l,c]=m.useState("singbox"),o=fe({resolver:ye(yd),defaultValues:Nd,mode:"onBlur"}),{data:u}=ie({queryKey:["settings","client"],queryFn:()=>fs("subscribe_template")}),{mutateAsync:x}=Ze({mutationFn:gs,onSuccess:f=>{f.data&&A.success(s("common.autoSaved"))}});m.useEffect(()=>{if(u?.data.subscribe_template){const f=u.data.subscribe_template;Object.entries(f).forEach(([w,P])=>{o.setValue(w,P)}),r.current=f}},[u]),console.log(o.getValues());const i=m.useCallback(Ce.debounce(async f=>{if(!Ce.isEqual(f,r.current)){a(!0);try{await x(f),r.current=f}finally{a(!1)}}},1e3),[x]),d=m.useCallback(f=>{i(f)},[i]);return e.jsx(Ne,{...o,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Wt,{value:l,onValueChange:c,children:[e.jsxs(bt,{children:[e.jsx(Ke,{value:"singbox",children:"Sing-box"}),e.jsx(Ke,{value:"clash",children:"Clash"}),e.jsx(Ke,{value:"clashmeta",children:"Clash Meta"}),e.jsx(Ke,{value:"stash",children:"Stash"}),e.jsx(Ke,{value:"surge",children:"Surge"})]}),e.jsx(Ns,{value:"singbox",children:e.jsx(b,{control:o.control,name:"subscribe_template_singbox",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe_template.singbox.title")}),e.jsx(N,{children:e.jsx(it,{height:"500px",defaultLanguage:"json",value:f.value||"",onChange:w=>{typeof w=="string"&&(f.onChange(w),d(o.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(z,{children:s("subscribe_template.singbox.description")}),e.jsx(k,{})]})})}),e.jsx(Ns,{value:"clash",children:e.jsx(b,{control:o.control,name:"subscribe_template_clash",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe_template.clash.title")}),e.jsx(N,{children:e.jsx(it,{height:"500px",defaultLanguage:"yaml",value:f.value||"",onChange:w=>{typeof w=="string"&&(f.onChange(w),d(o.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(z,{children:s("subscribe_template.clash.description")}),e.jsx(k,{})]})})}),e.jsx(Ns,{value:"clashmeta",children:e.jsx(b,{control:o.control,name:"subscribe_template_clashmeta",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe_template.clashmeta.title")}),e.jsx(N,{children:e.jsx(it,{height:"500px",defaultLanguage:"yaml",value:f.value||"",onChange:w=>{typeof w=="string"&&(f.onChange(w),d(o.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(z,{children:s("subscribe_template.clashmeta.description")}),e.jsx(k,{})]})})}),e.jsx(Ns,{value:"stash",children:e.jsx(b,{control:o.control,name:"subscribe_template_stash",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe_template.stash.title")}),e.jsx(N,{children:e.jsx(it,{height:"500px",defaultLanguage:"yaml",value:f.value||"",onChange:w=>{typeof w=="string"&&(f.onChange(w),d(o.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(z,{children:s("subscribe_template.stash.description")}),e.jsx(k,{})]})})}),e.jsx(Ns,{value:"surge",children:e.jsx(b,{control:o.control,name:"subscribe_template_surge",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe_template.surge.title")}),e.jsx(N,{children:e.jsx(it,{height:"500px",defaultLanguage:"ini",value:f.value||"",onChange:w=>{typeof w=="string"&&(f.onChange(w),d(o.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(z,{children:s("subscribe_template.surge.description")}),e.jsx(k,{})]})})})]}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function wd(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("subscribe_template.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("subscribe_template.description")})]}),e.jsx(Se,{}),e.jsx(_d,{})]})}const Cd=()=>e.jsx(dc,{children:e.jsx(Ca,{})}),Sd=Vl([{path:"/sign-in",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Hd);return{default:s}},void 0,import.meta.url)).default})},{element:e.jsx(Cd,{}),children:[{path:"/",lazy:async()=>({Component:(await ue(()=>Promise.resolve().then(()=>Zd),void 0,import.meta.url)).default}),errorElement:e.jsx(Gs,{}),children:[{index:!0,lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Nu);return{default:s}},void 0,import.meta.url)).default})},{path:"config",errorElement:e.jsx(Gs,{}),children:[{path:"system",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Su);return{default:s}},void 0,import.meta.url)).default}),children:[{index:!0,lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Pu);return{default:s}},void 0,import.meta.url)).default})},{path:"safe",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Mu);return{default:s}},void 0,import.meta.url)).default})},{path:"subscribe",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Au);return{default:s}},void 0,import.meta.url)).default})},{path:"invite",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Ku);return{default:s}},void 0,import.meta.url)).default})},{path:"frontend",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Qu);return{default:s}},void 0,import.meta.url)).default})},{path:"server",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>sm);return{default:s}},void 0,import.meta.url)).default})},{path:"email",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>lm);return{default:s}},void 0,import.meta.url)).default})},{path:"telegram",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>um);return{default:s}},void 0,import.meta.url)).default})},{path:"APP",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>fm);return{default:s}},void 0,import.meta.url)).default})},{path:"subscribe-template",element:e.jsx(wd,{})}]},{path:"payment",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Sm);return{default:s}},void 0,import.meta.url)).default})},{path:"plugin",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Dm);return{default:s}},void 0,import.meta.url)).default})},{path:"theme",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Im);return{default:s}},void 0,import.meta.url)).default})},{path:"notice",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Am);return{default:s}},void 0,import.meta.url)).default})},{path:"knowledge",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Wm);return{default:s}},void 0,import.meta.url)).default})}]},{path:"server",errorElement:e.jsx(Gs,{}),children:[{path:"manage",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>bx);return{default:s}},void 0,import.meta.url)).default})},{path:"group",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Cx);return{default:s}},void 0,import.meta.url)).default})},{path:"route",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Ex);return{default:s}},void 0,import.meta.url)).default})}]},{path:"finance",errorElement:e.jsx(Gs,{}),children:[{path:"plan",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Ax);return{default:s}},void 0,import.meta.url)).default})},{path:"order",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>eh);return{default:s}},void 0,import.meta.url)).default})},{path:"coupon",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>ch);return{default:s}},void 0,import.meta.url)).default})}]},{path:"user",errorElement:e.jsx(Gs,{}),children:[{path:"manage",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>Ah);return{default:s}},void 0,import.meta.url)).default})},{path:"ticket",lazy:async()=>({Component:(await ue(async()=>{const{default:s}=await Promise.resolve().then(()=>lp);return{default:s}},void 0,import.meta.url)).default})}]}]}]},{path:"/500",Component:Gs},{path:"/404",Component:en},{path:"/503",Component:ac},{path:"*",Component:en}]);function kd(){return V.get("/user/info")}const ra={token:ft()?.value||"",userInfo:null,isLoggedIn:!!ft()?.value,loading:!1,error:null},mt=Ml("user/fetchUserInfo",async()=>(await kd()).data,{condition:(s,{getState:n})=>{const{user:a}=n();return!!a.token&&!a.loading}}),kr=Fl({name:"user",initialState:ra,reducers:{setToken(s,n){s.token=n.payload,s.isLoggedIn=!!n.payload},resetUserState:()=>ra},extraReducers:s=>{s.addCase(mt.pending,n=>{n.loading=!0,n.error=null}).addCase(mt.fulfilled,(n,a)=>{n.loading=!1,n.userInfo=a.payload,n.error=null}).addCase(mt.rejected,(n,a)=>{if(n.loading=!1,n.error=a.error.message||"Failed to fetch user info",!n.token)return ra})}}),{setToken:Td,resetUserState:Dd}=kr.actions,Pd=s=>s.user.userInfo,Ed=kr.reducer,Tr=Ol({reducer:{user:Ed}});ft()?.value&&Tr.dispatch(mt());zl.use(Ll).use(Al).init({resources:{"en-US":window.XBOARD_TRANSLATIONS?.["en-US"]||{},"zh-CN":window.XBOARD_TRANSLATIONS?.["zh-CN"]||{},"ko-KR":window.XBOARD_TRANSLATIONS?.["ko-KR"]||{}},fallbackLng:"zh-CN",supportedLngs:["en-US","zh-CN","ko-KR"],detection:{order:["querystring","localStorage","navigator"],lookupQuerystring:"lang",lookupLocalStorage:"i18nextLng",caches:["localStorage"]},interpolation:{escapeValue:!1}});const Rd=new $l;ql.createRoot(document.getElementById("root")).render(e.jsx(Hl.StrictMode,{children:e.jsx(Ul,{client:Rd,children:e.jsx(Kl,{store:Tr,children:e.jsxs(Xo,{defaultTheme:"light",storageKey:"vite-ui-theme",children:[e.jsx(Bl,{router:Sd}),e.jsx(Gl,{richColors:!0,position:"top-right"})]})})})}));const Be=m.forwardRef(({className:s,...n},a)=>e.jsx("div",{ref:a,className:_("rounded-xl border bg-card text-card-foreground shadow",s),...n}));Be.displayName="Card";const es=m.forwardRef(({className:s,...n},a)=>e.jsx("div",{ref:a,className:_("flex flex-col space-y-1.5 p-6",s),...n}));es.displayName="CardHeader";const ws=m.forwardRef(({className:s,...n},a)=>e.jsx("h3",{ref:a,className:_("font-semibold leading-none tracking-tight",s),...n}));ws.displayName="CardTitle";const Zs=m.forwardRef(({className:s,...n},a)=>e.jsx("p",{ref:a,className:_("text-sm text-muted-foreground",s),...n}));Zs.displayName="CardDescription";const ss=m.forwardRef(({className:s,...n},a)=>e.jsx("div",{ref:a,className:_("p-6 pt-0",s),...n}));ss.displayName="CardContent";const Id=m.forwardRef(({className:s,...n},a)=>e.jsx("div",{ref:a,className:_("flex items-center p-6 pt-0",s),...n}));Id.displayName="CardFooter";const T=m.forwardRef(({className:s,type:n,...a},r)=>e.jsx("input",{type:n,className:_("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:r,...a}));T.displayName="Input";const Dr=m.forwardRef(({className:s,...n},a)=>{const[r,l]=m.useState(!1);return e.jsxs("div",{className:"relative rounded-md",children:[e.jsx("input",{type:r?"text":"password",className:_("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:a,...n}),e.jsx(D,{type:"button",size:"icon",variant:"ghost",className:"absolute right-1 top-1/2 h-6 w-6 -translate-y-1/2 rounded-md text-muted-foreground",onClick:()=>l(c=>!c),children:r?e.jsx(Wl,{size:18}):e.jsx(Yl,{size:18})})]})});Dr.displayName="PasswordInput";const Vd=s=>V({url:"/passport/auth/login",method:"post",data:s});function Md({className:s,onForgotPassword:n,...a}){const r=ks(),l=yn(),{t:c}=M("auth"),o=h.object({email:h.string().min(1,{message:c("signIn.validation.emailRequired")}),password:h.string().min(1,{message:c("signIn.validation.passwordRequired")}).min(7,{message:c("signIn.validation.passwordLength")})}),u=fe({resolver:ye(o),defaultValues:{email:"",password:""}});async function x(i){try{const{data:d}=await Vd(i);jc(d.auth_data),l(Td(d.auth_data)),await l(mt()).unwrap(),r("/")}catch(d){console.error("Login failed:",d),d.response?.data?.message&&u.setError("root",{message:d.response.data.message})}}return e.jsx("div",{className:_("grid gap-6",s),...a,children:e.jsx(Ne,{...u,children:e.jsx("form",{onSubmit:u.handleSubmit(x),className:"space-y-4",children:e.jsxs("div",{className:"space-y-4",children:[u.formState.errors.root&&e.jsx("div",{className:"text-sm text-destructive",children:u.formState.errors.root.message}),e.jsx(b,{control:u.control,name:"email",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:c("signIn.email")}),e.jsx(N,{children:e.jsx(T,{placeholder:c("signIn.emailPlaceholder"),autoComplete:"email",...i})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"password",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:c("signIn.password")}),e.jsx(N,{children:e.jsx(Dr,{placeholder:c("signIn.passwordPlaceholder"),autoComplete:"current-password",...i})}),e.jsx(k,{})]})}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(D,{variant:"link",type:"button",className:"px-0 text-sm font-normal text-muted-foreground hover:text-primary",onClick:n,children:c("signIn.forgotPassword")})}),e.jsx(D,{className:"w-full",size:"lg",loading:u.formState.isSubmitting,children:c("signIn.submit")})]})})})})}const ve=Nn,Ye=_n,Fd=wn,Nt=Sa,Pr=m.forwardRef(({className:s,...n},a)=>e.jsx($t,{ref:a,className:_("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...n}));Pr.displayName=$t.displayName;const pe=m.forwardRef(({className:s,children:n,...a},r)=>e.jsxs(Fd,{children:[e.jsx(Pr,{}),e.jsxs(qt,{ref:r,className:_("max-h-[95%] overflow-auto fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...a,children:[n,e.jsxs(Sa,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(Xe,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));pe.displayName=qt.displayName;const we=({className:s,...n})=>e.jsx("div",{className:_("flex flex-col space-y-1.5 text-center sm:text-left",s),...n});we.displayName="DialogHeader";const Oe=({className:s,...n})=>e.jsx("div",{className:_("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...n});Oe.displayName="DialogFooter";const be=m.forwardRef(({className:s,...n},a)=>e.jsx(Ht,{ref:a,className:_("text-lg font-semibold leading-none tracking-tight",s),...n}));be.displayName=Ht.displayName;const ke=m.forwardRef(({className:s,...n},a)=>e.jsx(Ut,{ref:a,className:_("text-sm text-muted-foreground",s),...n}));ke.displayName=Ut.displayName;const Xs=Ls("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),X=m.forwardRef(({className:s,variant:n,size:a,asChild:r=!1,...l},c)=>{const o=r?_a:"button";return e.jsx(o,{className:_(Xs({variant:n,size:a,className:s})),ref:c,...l})});X.displayName="Button";const Cs=Zl,Ss=Xl,Od=ei,zd=m.forwardRef(({className:s,inset:n,children:a,...r},l)=>e.jsxs(Cn,{ref:l,className:_("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",n&&"pl-8",s),...r,children:[a,e.jsx(ka,{className:"ml-auto h-4 w-4"})]}));zd.displayName=Cn.displayName;const Ld=m.forwardRef(({className:s,...n},a)=>e.jsx(Sn,{ref:a,className:_("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n}));Ld.displayName=Sn.displayName;const ps=m.forwardRef(({className:s,sideOffset:n=4,...a},r)=>e.jsx(Ql,{children:e.jsx(kn,{ref:r,sideOffset:n,className:_("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...a})}));ps.displayName=kn.displayName;const ge=m.forwardRef(({className:s,inset:n,...a},r)=>e.jsx(Tn,{ref:r,className:_("relative flex cursor-default cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",s),...a}));ge.displayName=Tn.displayName;const Ad=m.forwardRef(({className:s,children:n,checked:a,...r},l)=>e.jsxs(Dn,{ref:l,className:_("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),checked:a,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Pn,{children:e.jsx(As,{className:"h-4 w-4"})})}),n]}));Ad.displayName=Dn.displayName;const $d=m.forwardRef(({className:s,children:n,...a},r)=>e.jsxs(En,{ref:r,className:_("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Pn,{children:e.jsx(Jl,{className:"h-4 w-4 fill-current"})})}),n]}));$d.displayName=En.displayName;const Ia=m.forwardRef(({className:s,inset:n,...a},r)=>e.jsx(Rn,{ref:r,className:_("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",s),...a}));Ia.displayName=Rn.displayName;const et=m.forwardRef(({className:s,...n},a)=>e.jsx(In,{ref:a,className:_("-mx-1 my-1 h-px bg-muted",s),...n}));et.displayName=In.displayName;const ba=({className:s,...n})=>e.jsx("span",{className:_("ml-auto text-xs tracking-widest opacity-60",s),...n});ba.displayName="DropdownMenuShortcut";const la=[{code:"en-US",name:"English",flag:si,shortName:"EN"},{code:"zh-CN",name:"中文",flag:ti,shortName:"CN"},{code:"ko-KR",name:"한국어",flag:ai,shortName:"KR"}];function Er(){const{i18n:s}=M(),n=l=>{s.changeLanguage(l)},a=la.find(l=>l.code===s.language)||la[1],r=a.flag;return e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsxs(X,{variant:"ghost",size:"sm",className:"h-8 px-2 gap-1",children:[e.jsx(r,{className:"h-4 w-5 rounded-sm shadow-sm"}),e.jsx("span",{className:"text-sm font-medium",children:a.shortName})]})}),e.jsx(ps,{align:"end",className:"w-[120px]",children:la.map(l=>{const c=l.flag,o=l.code===s.language;return e.jsxs(ge,{onClick:()=>n(l.code),className:_("flex items-center gap-2 px-2 py-1.5 cursor-pointer",o&&"bg-accent"),children:[e.jsx(c,{className:"h-4 w-5 rounded-sm shadow-sm"}),e.jsx("span",{className:_("text-sm",o&&"font-medium"),children:l.name})]},l.code)})})]})}function qd(){const[s,n]=m.useState(!1),{t:a}=M("auth"),r=a("signIn.resetPassword.command");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"container relative grid h-svh flex-col items-center justify-center bg-primary-foreground lg:max-w-none lg:px-0",children:[e.jsx("div",{className:"absolute right-4 top-4 md:right-8 md:top-8",children:e.jsx(Er,{})}),e.jsxs("div",{className:"mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[480px] lg:p-8",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-center",children:[e.jsx("h1",{className:"text-3xl font-bold",children:window?.settings?.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:window?.settings?.description})]}),e.jsxs(Be,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-left",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:a("signIn.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a("signIn.description")})]}),e.jsx(Md,{onForgotPassword:()=>n(!0)})]})]})]}),e.jsx(ve,{open:s,onOpenChange:n,children:e.jsx(pe,{children:e.jsxs(we,{children:[e.jsx(be,{children:a("signIn.resetPassword.title")}),e.jsx(ke,{children:a("signIn.resetPassword.description")}),e.jsx("div",{className:"mt-4",children:e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"rounded-md bg-secondary p-4 pr-12 text-sm",children:r}),e.jsx(X,{variant:"ghost",size:"icon",className:"absolute right-2 top-2 h-8 w-8 hover:bg-secondary-foreground/10",onClick:()=>zt(r).then(()=>{A.success(a("common:copy.success"))}),children:e.jsx(ni,{className:"h-4 w-4"})})]})})]})})})]})}const Hd=Object.freeze(Object.defineProperty({__proto__:null,default:qd},Symbol.toStringTag,{value:"Module"})),Pe=m.forwardRef(({className:s,fadedBelow:n=!1,fixedHeight:a=!1,...r},l)=>e.jsx("div",{ref:l,className:_("relative flex h-full w-full flex-col",n&&"after:pointer-events-none after:absolute after:bottom-0 after:left-0 after:hidden after:h-32 after:w-full after:bg-[linear-gradient(180deg,_transparent_10%,_hsl(var(--background))_70%)] after:md:block",a&&"md:h-svh",s),...r}));Pe.displayName="Layout";const Ee=m.forwardRef(({className:s,...n},a)=>e.jsx("div",{ref:a,className:_("flex h-[var(--header-height)] flex-none items-center gap-4 bg-background p-4 md:px-8",s),...n}));Ee.displayName="LayoutHeader";const Ve=m.forwardRef(({className:s,fixedHeight:n,...a},r)=>e.jsx("div",{ref:r,className:_("flex-1 overflow-hidden px-4 py-6 md:px-8",n&&"h-[calc(100%-var(--header-height))]",s),...a}));Ve.displayName="LayoutBody";const Rr=ri,Ir=li,Vr=ii,je=oi,xe=ci,he=di,ce=m.forwardRef(({className:s,sideOffset:n=4,...a},r)=>e.jsx(Vn,{ref:r,sideOffset:n,className:_("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...a}));ce.displayName=Vn.displayName;function Yt(){const{pathname:s}=wa();return{checkActiveNav:a=>{if(a==="/"&&s==="/")return!0;const r=a.replace(/^\//,""),l=s.replace(/^\//,"");return r?l.startsWith(r):!1}}}function Mr({key:s,defaultValue:n}){const[a,r]=m.useState(()=>{const l=localStorage.getItem(s);return l!==null?JSON.parse(l):n});return m.useEffect(()=>{localStorage.setItem(s,JSON.stringify(a))},[a,s]),[a,r]}function Ud(){const[s,n]=Mr({key:"collapsed-sidebar-items",defaultValue:[]}),a=l=>!s.includes(l);return{isExpanded:a,toggleItem:l=>{a(l)?n([...s,l]):n(s.filter(c=>c!==l))}}}function Kd({links:s,isCollapsed:n,className:a,closeNav:r}){const{t:l}=M(),c=({sub:o,...u})=>{const x=`${l(u.title)}-${u.href}`;return n&&o?m.createElement(Wd,{...u,sub:o,key:x,closeNav:r}):n?m.createElement(Gd,{...u,key:x,closeNav:r}):o?m.createElement(Bd,{...u,sub:o,key:x,closeNav:r}):m.createElement(Fr,{...u,key:x,closeNav:r})};return e.jsx("div",{"data-collapsed":n,className:_("group border-b bg-background py-2 transition-[max-height,padding] duration-500 data-[collapsed=true]:py-2 md:border-none",a),children:e.jsx(je,{delayDuration:0,children:e.jsx("nav",{className:"grid gap-1 group-[[data-collapsed=true]]:justify-center group-[[data-collapsed=true]]:px-2",children:s.map(c)})})})}function Fr({title:s,icon:n,label:a,href:r,closeNav:l,subLink:c=!1}){const{checkActiveNav:o}=Yt(),{t:u}=M();return e.jsxs($s,{to:r,onClick:l,className:_(tt({variant:o(r)?"secondary":"ghost",size:"sm"}),"h-12 justify-start text-wrap rounded-none px-6",c&&"h-10 w-full border-l border-l-slate-500 px-2"),"aria-current":o(r)?"page":void 0,children:[e.jsx("div",{className:"mr-2",children:n}),u(s),a&&e.jsx("div",{className:"ml-2 rounded-lg bg-primary px-1 text-[0.625rem] text-primary-foreground",children:u(a)})]})}function Bd({title:s,icon:n,label:a,sub:r,closeNav:l}){const{checkActiveNav:c}=Yt(),{isExpanded:o,toggleItem:u}=Ud(),{t:x}=M(),i=!!r?.find(w=>c(w.href)),d=x(s),f=o(d)||i;return e.jsxs(Rr,{open:f,onOpenChange:()=>u(d),children:[e.jsxs(Ir,{className:_(tt({variant:i?"secondary":"ghost",size:"sm"}),"group h-12 w-full justify-start rounded-none px-6"),children:[e.jsx("div",{className:"mr-2",children:n}),x(s),a&&e.jsx("div",{className:"ml-2 rounded-lg bg-primary px-1 text-[0.625rem] text-primary-foreground",children:x(a)}),e.jsx("span",{className:_('ml-auto transition-all group-data-[state="open"]:-rotate-180'),children:e.jsx(Mn,{stroke:1})})]}),e.jsx(Vr,{className:"collapsibleDropdown",asChild:!0,children:e.jsx("ul",{children:r.map(w=>e.jsx("li",{className:"my-1 ml-8",children:e.jsx(Fr,{...w,subLink:!0,closeNav:l})},x(w.title)))})})]})}function Gd({title:s,icon:n,label:a,href:r,closeNav:l}){const{checkActiveNav:c}=Yt(),{t:o}=M();return e.jsxs(xe,{delayDuration:0,children:[e.jsx(he,{asChild:!0,children:e.jsxs($s,{to:r,onClick:l,className:_(tt({variant:c(r)?"secondary":"ghost",size:"icon"}),"h-12 w-12"),children:[n,e.jsx("span",{className:"sr-only",children:o(s)})]})}),e.jsxs(ce,{side:"right",className:"flex items-center gap-4",children:[o(s),a&&e.jsx("span",{className:"ml-auto text-muted-foreground",children:o(a)})]})]})}function Wd({title:s,icon:n,label:a,sub:r,closeNav:l}){const{checkActiveNav:c}=Yt(),{t:o}=M(),u=!!r?.find(x=>c(x.href));return e.jsxs(Cs,{children:[e.jsxs(xe,{delayDuration:0,children:[e.jsx(he,{asChild:!0,children:e.jsx(Ss,{asChild:!0,children:e.jsx(D,{variant:u?"secondary":"ghost",size:"icon",className:"h-12 w-12",children:n})})}),e.jsxs(ce,{side:"right",className:"flex items-center gap-4",children:[o(s)," ",a&&e.jsx("span",{className:"ml-auto text-muted-foreground",children:o(a)}),e.jsx(Mn,{size:18,className:"-rotate-90 text-muted-foreground"})]})]}),e.jsxs(ps,{side:"right",align:"start",sideOffset:4,children:[e.jsxs(Ia,{children:[o(s)," ",a?`(${o(a)})`:""]}),e.jsx(et,{}),r.map(({title:x,icon:i,label:d,href:f})=>e.jsx(ge,{asChild:!0,children:e.jsxs($s,{to:f,onClick:l,className:`${c(f)?"bg-secondary":""}`,children:[i," ",e.jsx("span",{className:"ml-2 max-w-52 text-wrap",children:o(x)}),d&&e.jsx("span",{className:"ml-auto text-xs",children:o(d)})]})},`${o(x)}-${f}`))]})]})}const Or=[{title:"nav:dashboard",label:"",href:"/",icon:e.jsx(ui,{size:18})},{title:"nav:systemManagement",label:"",href:"",icon:e.jsx(mi,{size:18}),sub:[{title:"nav:systemConfig",label:"",href:"/config/system",icon:e.jsx(Fn,{size:18})},{title:"nav:pluginManagement",label:"",href:"/config/plugin",icon:e.jsx(Ta,{size:18})},{title:"nav:themeConfig",label:"",href:"/config/theme",icon:e.jsx(xi,{size:18})},{title:"nav:noticeManagement",label:"",href:"/config/notice",icon:e.jsx(hi,{size:18})},{title:"nav:paymentConfig",label:"",href:"/config/payment",icon:e.jsx(Ba,{size:18})},{title:"nav:knowledgeManagement",label:"",href:"/config/knowledge",icon:e.jsx(pi,{size:18})}]},{title:"nav:nodeManagement",label:"",href:"",icon:e.jsx(On,{size:18}),sub:[{title:"nav:nodeManagement",label:"",href:"/server/manage",icon:e.jsx(fi,{size:18})},{title:"nav:permissionGroupManagement",label:"",href:"/server/group",icon:e.jsx(zn,{size:18})},{title:"nav:routeManagement",label:"",href:"/server/route",icon:e.jsx(gi,{size:18})}]},{title:"nav:subscriptionManagement",label:"",href:"",icon:e.jsx(ji,{size:18}),sub:[{title:"nav:planManagement",label:"",href:"/finance/plan",icon:e.jsx(vi,{size:18})},{title:"nav:orderManagement",label:"",href:"/finance/order",icon:e.jsx(Ba,{size:18})},{title:"nav:couponManagement",label:"",href:"/finance/coupon",icon:e.jsx(bi,{size:18})}]},{title:"nav:userManagement",label:"",href:"",icon:e.jsx(yi,{size:18}),sub:[{title:"nav:userManagement",label:"",href:"/user/manage",icon:e.jsx(Ni,{size:18})},{title:"nav:ticketManagement",label:"",href:"/user/ticket",icon:e.jsx(Ln,{size:18})}]}];function Yd({className:s,isCollapsed:n,setIsCollapsed:a}){const[r,l]=m.useState(!1),{t:c}=M();return m.useEffect(()=>{r?document.body.classList.add("overflow-hidden"):document.body.classList.remove("overflow-hidden")},[r]),e.jsxs("aside",{className:_(`fixed left-0 right-0 top-0 z-50 flex h-auto flex-col border-r-2 border-r-muted transition-[width] md:bottom-0 md:right-auto md:h-svh ${n?"md:w-14":"md:w-64"}`,s),children:[e.jsx("div",{onClick:()=>l(!1),className:`absolute inset-0 transition-[opacity] delay-100 duration-700 ${r?"h-svh opacity-50":"h-0 opacity-0"} w-full bg-black md:hidden`}),e.jsxs(Pe,{className:"flex h-full flex-col",children:[e.jsxs(Ee,{className:"sticky top-0 justify-between px-4 py-3 shadow md:px-4",children:[e.jsxs("div",{className:`flex items-center ${n?"":"gap-2"}`,children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",className:`transition-all ${n?"h-6 w-6":"h-8 w-8"}`,children:[e.jsx("rect",{width:"256",height:"256",fill:"none"}),e.jsx("line",{x1:"208",y1:"128",x2:"128",y2:"208",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"16"}),e.jsx("line",{x1:"192",y1:"40",x2:"40",y2:"192",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"16"}),e.jsx("span",{className:"sr-only",children:"Website Name"})]}),e.jsx("div",{className:`flex flex-col justify-end truncate ${n?"invisible w-0":"visible w-auto"}`,children:e.jsx("span",{className:"font-medium",children:window?.settings?.title})})]}),e.jsx(D,{variant:"ghost",size:"icon",className:"md:hidden","aria-label":c("common:toggleNavigation"),"aria-controls":"sidebar-menu","aria-expanded":r,onClick:()=>l(o=>!o),children:r?e.jsx(_i,{}):e.jsx(wi,{})})]}),e.jsx(Kd,{id:"sidebar-menu",className:_("flex-1 overflow-auto",r?"block":"hidden md:block","md:py-2"),closeNav:()=>l(!1),isCollapsed:n,links:Or}),e.jsx("div",{className:_("border-t border-border/50 bg-background","px-4 py-2.5 text-xs text-muted-foreground",r?"block":"hidden md:block",n?"text-center":"text-left"),children:e.jsxs("div",{className:_("flex items-center gap-1.5",n?"justify-center":"justify-start"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-green-500"}),e.jsxs("span",{className:_("tracking-wide whitespace-nowrap","transition-opacity duration-200",n&&"md:opacity-0"),children:["v",window?.settings?.version]})]})}),e.jsx(D,{onClick:()=>a(o=>!o),size:"icon",variant:"outline",className:"absolute -right-5 top-1/2 hidden rounded-full md:inline-flex","aria-label":c("common:toggleSidebar"),children:e.jsx(Ci,{stroke:1.5,className:`h-5 w-5 ${n?"rotate-180":""}`})})]})]})}function Qd(){const[s,n]=Mr({key:"collapsed-sidebar",defaultValue:!1});return m.useEffect(()=>{const a=()=>{n(window.innerWidth<768?!1:s)};return a(),window.addEventListener("resize",a),()=>{window.removeEventListener("resize",a)}},[s,n]),[s,n]}function Jd(){const[s,n]=Qd();return e.jsxs("div",{className:"relative h-full overflow-hidden bg-background",children:[e.jsx(Yd,{isCollapsed:s,setIsCollapsed:n}),e.jsx("main",{id:"content",className:`overflow-x-hidden pt-16 transition-[margin] md:overflow-y-hidden md:pt-0 ${s?"md:ml-14":"md:ml-64"} h-full`,children:e.jsx(Ca,{})})]})}const Zd=Object.freeze(Object.defineProperty({__proto__:null,default:Jd},Symbol.toStringTag,{value:"Module"})),Vs=m.forwardRef(({className:s,...n},a)=>e.jsx(Fe,{ref:a,className:_("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...n}));Vs.displayName=Fe.displayName;const Xd=({children:s,...n})=>e.jsx(ve,{...n,children:e.jsx(pe,{className:"overflow-hidden p-0",children:e.jsx(Vs,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:s})})}),Us=m.forwardRef(({className:s,...n},a)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Si,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Fe.Input,{ref:a,className:_("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",s),...n})]}));Us.displayName=Fe.Input.displayName;const Ms=m.forwardRef(({className:s,...n},a)=>e.jsx(Fe.List,{ref:a,className:_("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...n}));Ms.displayName=Fe.List.displayName;const Ks=m.forwardRef((s,n)=>e.jsx(Fe.Empty,{ref:n,className:"py-6 text-center text-sm",...s}));Ks.displayName=Fe.Empty.displayName;const Ge=m.forwardRef(({className:s,...n},a)=>e.jsx(Fe.Group,{ref:a,className:_("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",s),...n}));Ge.displayName=Fe.Group.displayName;const at=m.forwardRef(({className:s,...n},a)=>e.jsx(Fe.Separator,{ref:a,className:_("-mx-1 h-px bg-border",s),...n}));at.displayName=Fe.Separator.displayName;const Ie=m.forwardRef(({className:s,...n},a)=>e.jsx(Fe.Item,{ref:a,className:_("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n}));Ie.displayName=Fe.Item.displayName;function eu(){const s=[];for(const n of Or)if(n.href&&s.push(n),n.sub)for(const a of n.sub)s.push({...a,parent:n.title});return s}function qe(){const[s,n]=m.useState(!1),a=ks(),r=eu(),{t:l}=M("search"),{t:c}=M("nav");m.useEffect(()=>{const u=x=>{x.key==="k"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),n(i=>!i))};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[]);const o=m.useCallback(u=>{n(!1),a(u)},[a]);return e.jsxs(e.Fragment,{children:[e.jsxs(X,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-10 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>n(!0),children:[e.jsx(An,{className:"h-4 w-4 xl:mr-2"}),e.jsx("span",{className:"hidden xl:inline-flex",children:l("placeholder")}),e.jsx("span",{className:"sr-only",children:l("shortcut.label")}),e.jsx("kbd",{className:"pointer-events-none absolute right-1.5 top-2 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:l("shortcut.key")})]}),e.jsxs(Xd,{open:s,onOpenChange:n,children:[e.jsx(Us,{placeholder:l("placeholder")}),e.jsxs(Ms,{children:[e.jsx(Ks,{children:l("noResults")}),e.jsx(Ge,{heading:l("title"),children:r.map(u=>e.jsxs(Ie,{value:`${u.parent?u.parent+" ":""}${u.title}`,onSelect:()=>o(u.href),children:[e.jsx("div",{className:"mr-2",children:u.icon}),e.jsx("span",{children:c(u.title)}),u.parent&&e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c(u.parent)})]},u.href))})]})]})]})}const le=window?.settings?.secure_path,zr=5*60*1e3,ya=new Map,su=s=>{const n=ya.get(s);return n?Date.now()-n.timestamp>zr?(ya.delete(s),null):n.data:null},tu=(s,n)=>{ya.set(s,{data:n,timestamp:Date.now()})},au=async(s,n=zr)=>{const a=su(s);if(a)return a;const r=await V.get(s);return tu(s,r),r},Lt={getList:s=>V.post(`${le}/user/fetch`,s),update:s=>V.post(`${le}/user/update`,s),resetSecret:s=>V.post(`${le}/user/resetSecret`,{id:s}),generate:s=>V.post(`${le}/user/generate`,s),getStats:s=>V.post(`${le}/stat/getStatUser`,s),destroy:s=>V.post(`${le}/user/destroy`,{id:s}),sendMail:s=>V.post(`${le}/user/sendMail`,s),dumpCSV:s=>V.post(`${le}/user/dumpCSV`,s,{responseType:"blob"}),batchBan:s=>V.post(`${le}/user/ban`,s)},nn={getList:()=>au(`${le}/notice/fetch`),save:s=>V.post(`${le}/notice/save`,s),drop:s=>V.post(`${le}/notice/drop`,{id:s}),updateStatus:s=>V.post(`${le}/notice/show`,{id:s}),sort:s=>V.post(`${le}/notice/sort`,{ids:s})},ia={getList:s=>V.post(`${le}/ticket/fetch`,s),getInfo:s=>V.get(`${le}/ticket/fetch?id=${s}`),reply:s=>V.post(`${le}/ticket/reply`,s),close:s=>V.post(`${le}/ticket/close`,{id:s})},rn={getSystemStatus:()=>V.get(`${le}/system/getSystemStatus`),getQueueStats:()=>V.get(`${le}/system/getQueueStats`),getQueueWorkload:()=>V.get(`${le}/system/getQueueWorkload`),getQueueMasters:()=>V.get(`${le}/system/getQueueMasters`),getSystemLog:s=>V.get(`${le}/system/getSystemLog`,{params:s})},ys={getPluginList:()=>V.get(`${le}/plugin/getPlugins`),uploadPlugin:s=>{const n=new FormData;return n.append("file",s),V.post(`${le}/plugin/upload`,n,{headers:{"Content-Type":"multipart/form-data"}})},deletePlugin:s=>V.post(`${le}/plugin/delete`,{code:s}),installPlugin:s=>V.post(`${le}/plugin/install`,{code:s}),uninstallPlugin:s=>V.post(`${le}/plugin/uninstall`,{code:s}),enablePlugin:s=>V.post(`${le}/plugin/enable`,{code:s}),disablePlugin:s=>V.post(`${le}/plugin/disable`,{code:s}),getPluginConfig:s=>V.get(`${le}/plugin/config`,{params:{code:s}}),updatePluginConfig:(s,n)=>V.post(`${le}/plugin/config`,{code:s,config:n})},nu=()=>V.get(`${le}/update/check`),ru=()=>V.post(`${le}/update/execute`),lu=Ls("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/10",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function K({className:s,variant:n,...a}){return e.jsx("div",{className:_(lu({variant:n}),s),...a})}const zs=m.forwardRef(({className:s,children:n,...a},r)=>e.jsxs($n,{ref:r,className:_("relative overflow-hidden",s),...a,children:[e.jsx(ki,{className:"h-full w-full rounded-[inherit]",children:n}),e.jsx(At,{}),e.jsx(Ti,{})]}));zs.displayName=$n.displayName;const At=m.forwardRef(({className:s,orientation:n="vertical",...a},r)=>e.jsx(qn,{ref:r,orientation:n,className:_("flex touch-none select-none transition-colors",n==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",n==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...a,children:e.jsx(Di,{className:"relative flex-1 rounded-full bg-border"})}));At.displayName=qn.displayName;function iu(){const{t:s}=M("common"),[n,a]=m.useState(!1),{data:r}=ie({queryKey:["checkUpdate"],queryFn:async()=>await nu(),refetchInterval:1e3*60*60}),l=r?.data,c=Ze({mutationFn:ru,onSuccess:o=>{const u=o.data;u.success?(A.success(s("update.updateSuccess")),a(!1)):A.error(u.message)},onError:()=>{A.error(s("update.updateFailed"))}});return l?.has_update?e.jsxs(e.Fragment,{children:[e.jsxs(D,{size:"icon",variant:"ghost",className:"rounded-full relative",onClick:()=>a(!0),children:[e.jsx(Pi,{size:20,className:"text-red-500"}),e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"})]}),e.jsx(ve,{open:n,onOpenChange:a,children:e.jsxs(pe,{className:"sm:max-w-[500px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:s("update.title")}),e.jsxs(ke,{children:[s("update.newVersion")," ",l?.latest_version]})]}),e.jsxs("div",{className:"py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[s("update.currentVersion"),":",l?.current_version]}),e.jsxs(K,{variant:"outline",children:[s("update.latestVersion"),":",l?.latest_version]})]}),e.jsx(zs,{className:"h-[200px] rounded-md border p-4",children:e.jsx("div",{className:"space-y-4",children:l?.update_logs.map(o=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(K,{variant:"secondary",children:o.version}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Je(new Date(o.date),"yyyy-MM-dd HH:mm")})]}),e.jsx("p",{className:"text-sm",children:o.message})]},o.version))})})]}),e.jsxs(Oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>a(!1),children:s("update.updateLater")}),e.jsx(D,{onClick:()=>c.mutate(),disabled:c.isPending,children:c.isPending?s("update.updating"):s("update.updateNow")})]})]})})]}):null}function ze(){const{theme:s,setTheme:n}=ec();return m.useEffect(()=>{const a=s==="dark"?"#020817":"#fff",r=document.querySelector("meta[name='theme-color']");r&&r.setAttribute("content",a)},[s]),e.jsxs(e.Fragment,{children:[e.jsx(D,{size:"icon",variant:"ghost",className:"rounded-full",onClick:()=>n(s==="light"?"dark":"light"),children:s==="light"?e.jsx(Ei,{size:20}):e.jsx(Ri,{size:20})}),e.jsx(Er,{}),e.jsx(iu,{})]})}const Lr=m.forwardRef(({className:s,...n},a)=>e.jsx(Hn,{ref:a,className:_("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...n}));Lr.displayName=Hn.displayName;const Ar=m.forwardRef(({className:s,...n},a)=>e.jsx(Un,{ref:a,className:_("aspect-square h-full w-full",s),...n}));Ar.displayName=Un.displayName;const $r=m.forwardRef(({className:s,...n},a)=>e.jsx(Kn,{ref:a,className:_("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...n}));$r.displayName=Kn.displayName;function Le(){const s=ks(),n=yn(),a=Ii(Pd),{t:r}=M(["common"]),l=()=>{yr(),n(Dd()),s("/sign-in")},c=a?.email?.split("@")[0]||r("common:user"),o=c.substring(0,2).toUpperCase();return e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsx(D,{variant:"ghost",className:"relative h-8 w-8 rounded-full",children:e.jsxs(Lr,{className:"h-8 w-8",children:[e.jsx(Ar,{src:a?.avatar_url,alt:c}),e.jsx($r,{children:o})]})})}),e.jsxs(ps,{className:"w-56",align:"end",forceMount:!0,children:[e.jsx(Ia,{className:"font-normal",children:e.jsxs("div",{className:"flex flex-col space-y-1",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:c}),e.jsx("p",{className:"text-xs leading-none text-muted-foreground",children:a?.email||r("common:defaultEmail")})]})}),e.jsx(et,{}),e.jsx(ge,{asChild:!0,children:e.jsxs($s,{to:"/config/system",children:[r("common:settings"),e.jsx(ba,{children:"⌘S"})]})}),e.jsx(et,{}),e.jsxs(ge,{onClick:l,children:[r("common:logout"),e.jsx(ba,{children:"⇧⌘Q"})]})]})]})}const J=Vi,ns=qi,Z=Mi,W=m.forwardRef(({className:s,children:n,...a},r)=>e.jsxs(Bn,{ref:r,className:_("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...a,children:[n,e.jsx(Fi,{asChild:!0,children:e.jsx(Da,{className:"h-4 w-4 opacity-50"})})]}));W.displayName=Bn.displayName;const qr=m.forwardRef(({className:s,...n},a)=>e.jsx(Gn,{ref:a,className:_("flex cursor-default items-center justify-center py-1",s),...n,children:e.jsx(Oi,{className:"h-4 w-4"})}));qr.displayName=Gn.displayName;const Hr=m.forwardRef(({className:s,...n},a)=>e.jsx(Wn,{ref:a,className:_("flex cursor-default items-center justify-center py-1",s),...n,children:e.jsx(Da,{className:"h-4 w-4"})}));Hr.displayName=Wn.displayName;const Y=m.forwardRef(({className:s,children:n,position:a="popper",...r},l)=>e.jsx(zi,{children:e.jsxs(Yn,{ref:l,className:_("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:a,...r,children:[e.jsx(qr,{}),e.jsx(Li,{className:_("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:n}),e.jsx(Hr,{})]})}));Y.displayName=Yn.displayName;const ou=m.forwardRef(({className:s,...n},a)=>e.jsx(Qn,{ref:a,className:_("px-2 py-1.5 text-sm font-semibold",s),...n}));ou.displayName=Qn.displayName;const q=m.forwardRef(({className:s,children:n,...a},r)=>e.jsxs(Jn,{ref:r,className:_("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...a,children:[e.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ai,{children:e.jsx(As,{className:"h-4 w-4"})})}),e.jsx($i,{children:n})]}));q.displayName=Jn.displayName;const cu=m.forwardRef(({className:s,...n},a)=>e.jsx(Zn,{ref:a,className:_("-mx-1 my-1 h-px bg-muted",s),...n}));cu.displayName=Zn.displayName;function Bs({className:s,classNames:n,showOutsideDays:a=!0,...r}){return e.jsx(Hi,{showOutsideDays:a,className:_("p-3",s),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:_(Xs({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:_("relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md"),day:_(Xs({variant:"ghost"}),"h-8 w-8 p-0 font-normal aria-selected:opacity-100"),day_range_start:"day-range-start",day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...n},components:{IconLeft:({className:l,...c})=>e.jsx(Xn,{className:_("h-4 w-4",l),...c}),IconRight:({className:l,...c})=>e.jsx(ka,{className:_("h-4 w-4",l),...c})},...r})}Bs.displayName="Calendar";const js=Ki,vs=Bi,ms=m.forwardRef(({className:s,align:n="center",sideOffset:a=4,...r},l)=>e.jsx(Ui,{children:e.jsx(er,{ref:l,align:n,sideOffset:a,className:_("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})}));ms.displayName=er.displayName;const Ps={income:{main:"hsl(var(--primary))",gradient:{start:"hsl(var(--primary))",end:"transparent"}},commission:{main:"hsl(var(--secondary))",gradient:{start:"hsl(var(--secondary))",end:"transparent"}}},dt=s=>(s/100).toFixed(2),du=({active:s,payload:n,label:a})=>{const{t:r}=M();return s&&n&&n.length?e.jsxs("div",{className:"rounded-lg border bg-background p-3 shadow-sm",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:a}),n.map((l,c)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:l.color}}),e.jsxs("span",{className:"text-muted-foreground",children:[r(l.name),":"]}),e.jsx("span",{className:"font-medium",children:l.name.includes(r("dashboard:overview.amount"))?`¥${dt(l.value)}`:r("dashboard:overview.transactions",{count:l.value})})]},c))]}):null},uu=[{value:"7d",label:"dashboard:overview.last7Days"},{value:"30d",label:"dashboard:overview.last30Days"},{value:"90d",label:"dashboard:overview.last90Days"},{value:"180d",label:"dashboard:overview.last180Days"},{value:"365d",label:"dashboard:overview.lastYear"},{value:"custom",label:"dashboard:overview.customRange"}],mu=(s,n)=>{const a=new Date;if(s==="custom"&&n)return{startDate:n.from,endDate:n.to};let r;switch(s){case"7d":r=ls(a,7);break;case"30d":r=ls(a,30);break;case"90d":r=ls(a,90);break;case"180d":r=ls(a,180);break;case"365d":r=ls(a,365);break;default:r=ls(a,30)}return{startDate:r,endDate:a}};function xu(){const[s,n]=m.useState("amount"),[a,r]=m.useState("30d"),[l,c]=m.useState({from:ls(new Date,7),to:new Date}),{t:o}=M(),{startDate:u,endDate:x}=mu(a,l),{data:i}=ie({queryKey:["orderStat",{start_date:Je(u,"yyyy-MM-dd"),end_date:Je(x,"yyyy-MM-dd")}],queryFn:async()=>{const{data:d}=await vc({start_date:Je(u,"yyyy-MM-dd"),end_date:Je(x,"yyyy-MM-dd")});return d},refetchInterval:3e4});return e.jsxs(Be,{children:[e.jsx(es,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ws,{children:o("dashboard:overview.title")}),e.jsxs(Zs,{children:[i?.summary.start_date," ",o("dashboard:overview.to")," ",i?.summary.end_date]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsxs(J,{value:a,onValueChange:d=>r(d),children:[e.jsx(W,{className:"w-[120px]",children:e.jsx(Z,{placeholder:o("dashboard:overview.selectTimeRange")})}),e.jsx(Y,{children:uu.map(d=>e.jsx(q,{value:d.value,children:o(d.label)},d.value))})]}),a==="custom"&&e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(X,{variant:"outline",className:_("min-w-0 justify-start text-left font-normal",!l&&"text-muted-foreground"),children:[e.jsx(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:l?.from?l.to?e.jsxs(e.Fragment,{children:[Je(l.from,"yyyy-MM-dd")," -"," ",Je(l.to,"yyyy-MM-dd")]}):Je(l.from,"yyyy-MM-dd"):o("dashboard:overview.selectDate")})]})}),e.jsx(ms,{className:"w-auto p-0",align:"end",children:e.jsx(Bs,{mode:"range",defaultMonth:l?.from,selected:{from:l?.from,to:l?.to},onSelect:d=>{d?.from&&d?.to&&c({from:d.from,to:d.to})},numberOfMonths:2})})]})]}),e.jsx(Wt,{value:s,onValueChange:d=>n(d),children:e.jsxs(bt,{children:[e.jsx(Ke,{value:"amount",children:o("dashboard:overview.amount")}),e.jsx(Ke,{value:"count",children:o("dashboard:overview.count")})]})})]})]})}),e.jsxs(ss,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:o("dashboard:overview.totalIncome")}),e.jsxs("div",{className:"text-2xl font-bold",children:["¥",dt(i?.summary?.paid_total||0)]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:o("dashboard:overview.totalTransactions",{count:i?.summary?.paid_count||0})}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[o("dashboard:overview.avgOrderAmount")," ¥",dt(i?.summary?.avg_paid_amount||0)]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:o("dashboard:overview.totalCommission")}),e.jsxs("div",{className:"text-2xl font-bold",children:["¥",dt(i?.summary?.commission_total||0)]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:o("dashboard:overview.totalTransactions",{count:i?.summary?.commission_count||0})}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[o("dashboard:overview.commissionRate")," ",i?.summary?.commission_rate.toFixed(2)||0,"%"]})]})]}),e.jsx("div",{className:"h-[400px] w-full",children:e.jsx(Gi,{width:"100%",height:"100%",children:e.jsxs(Wi,{data:i?.list||[],margin:{top:20,right:20,left:0,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"incomeGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Ps.income.gradient.start,stopOpacity:.2}),e.jsx("stop",{offset:"100%",stopColor:Ps.income.gradient.end,stopOpacity:.1})]}),e.jsxs("linearGradient",{id:"commissionGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Ps.commission.gradient.start,stopOpacity:.2}),e.jsx("stop",{offset:"100%",stopColor:Ps.commission.gradient.end,stopOpacity:.1})]})]}),e.jsx(Yi,{dataKey:"date",axisLine:!1,tickLine:!1,tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:d=>Je(new Date(d),"MM-dd",{locale:Xi})}),e.jsx(Qi,{axisLine:!1,tickLine:!1,tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:d=>s==="amount"?`¥${dt(d)}`:o("dashboard:overview.transactions",{count:d})}),e.jsx(Ji,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))",opacity:.3}),e.jsx(Zi,{content:e.jsx(du,{})}),s==="amount"?e.jsxs(e.Fragment,{children:[e.jsx(Ga,{type:"monotone",dataKey:"paid_total",name:o("dashboard:overview.orderAmount"),stroke:Ps.income.main,fill:"url(#incomeGradient)",strokeWidth:2}),e.jsx(Ga,{type:"monotone",dataKey:"commission_total",name:o("dashboard:overview.commissionAmount"),stroke:Ps.commission.main,fill:"url(#commissionGradient)",strokeWidth:2})]}):e.jsxs(e.Fragment,{children:[e.jsx(Wa,{dataKey:"paid_count",name:o("dashboard:overview.orderCount"),fill:Ps.income.main,radius:[4,4,0,0],maxBarSize:40}),e.jsx(Wa,{dataKey:"commission_count",name:o("dashboard:overview.commissionCount"),fill:Ps.commission.main,radius:[4,4,0,0],maxBarSize:40})]})]})})})]})]})}function oe({className:s,...n}){return e.jsx("div",{className:_("animate-pulse rounded-md bg-primary/10",s),...n})}function hu(){return e.jsxs(Be,{children:[e.jsxs(es,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(oe,{className:"h-4 w-[120px]"}),e.jsx(oe,{className:"h-4 w-4"})]}),e.jsxs(ss,{children:[e.jsx(oe,{className:"h-8 w-[140px] mb-2"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),e.jsx(oe,{className:"h-4 w-[100px]"})]})]})]})}function pu(){return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:Array.from({length:8}).map((s,n)=>e.jsx(hu,{},n))})}var re=(s=>(s[s.PENDING=0]="PENDING",s[s.PROCESSING=1]="PROCESSING",s[s.CANCELLED=2]="CANCELLED",s[s.COMPLETED=3]="COMPLETED",s[s.DISCOUNTED=4]="DISCOUNTED",s))(re||{});const ot={0:"待支付",1:"开通中",2:"已取消",3:"已完成",4:"已折抵"},ct={0:"yellow-500",1:"blue-500",2:"red-500",3:"green-500",4:"green-500"};var is=(s=>(s[s.NEW=1]="NEW",s[s.RENEWAL=2]="RENEWAL",s[s.UPGRADE=3]="UPGRADE",s[s.RESET_FLOW=4]="RESET_FLOW",s))(is||{}),me=(s=>(s[s.PENDING=0]="PENDING",s[s.PROCESSING=1]="PROCESSING",s[s.VALID=2]="VALID",s[s.INVALID=3]="INVALID",s))(me||{});const wt={0:"待确认",1:"发放中",2:"有效",3:"无效"},Ct={0:"yellow-500",1:"blue-500",2:"green-500",3:"red-500"};var De=(s=>(s.MONTH_PRICE="month_price",s.QUARTER_PRICE="quarter_price",s.HALF_YEAR_PRICE="half_year_price",s.YEAR_PRICE="year_price",s.TWO_YEAR_PRICE="two_year_price",s.THREE_YEAR_PRICE="three_year_price",s.ONETIME_PRICE="onetime_price",s.RESET_PRICE="reset_price",s))(De||{});const fu={month_price:"月付",quarter_price:"季付",half_year_price:"半年付",year_price:"年付",two_year_price:"两年付",three_year_price:"三年付",onetime_price:"一次性",reset_price:"流量重置包"};var Te=(s=>(s.Shadowsocks="shadowsocks",s.Vmess="vmess",s.Trojan="trojan",s.Hysteria="hysteria",s.Vless="vless",s.Tuic="tuic",s))(Te||{});const Os=[{type:"shadowsocks",label:"Shadowsocks"},{type:"vmess",label:"VMess"},{type:"trojan",label:"Trojan"},{type:"hysteria",label:"Hysteria"},{type:"vless",label:"VLess"},{type:"tuic",label:"TUIC"}],_s={shadowsocks:"#489851",vmess:"#CB3180",trojan:"#EBB749",hysteria:"#5684e6",vless:"#1a1a1a",tuic:"#00C853"};var Ue=(s=>(s[s.AMOUNT=1]="AMOUNT",s[s.PERCENTAGE=2]="PERCENTAGE",s))(Ue||{});const gu={1:"按金额优惠",2:"按比例优惠"};var Is=(s=>(s[s.OPENING=0]="OPENING",s[s.CLOSED=1]="CLOSED",s))(Is||{}),Me=(s=>(s[s.LOW=0]="LOW",s[s.MIDDLE=1]="MIDDLE",s[s.HIGH=2]="HIGH",s))(Me||{}),xt=(s=>(s.MONTH="monthly",s.QUARTER="quarterly",s.HALF_YEAR="half_yearly",s.YEAR="yearly",s.TWO_YEAR="two_yearly",s.THREE_YEAR="three_yearly",s.ONETIME="onetime",s.RESET="reset_traffic",s))(xt||{});function Es({title:s,value:n,icon:a,trend:r,description:l,onClick:c,highlight:o,className:u}){return e.jsxs(Be,{className:_("transition-colors",c&&"cursor-pointer hover:bg-muted/50",o&&"border-primary/50",u),onClick:c,children:[e.jsxs(es,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ws,{className:"text-sm font-medium",children:s}),a]}),e.jsxs(ss,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n}),r?e.jsxs("div",{className:"flex items-center pt-1",children:[e.jsx(ro,{className:_("h-4 w-4",r.isPositive?"text-emerald-500":"text-red-500")}),e.jsxs("span",{className:_("ml-1 text-xs",r.isPositive?"text-emerald-500":"text-red-500"),children:[r.isPositive?"+":"-",Math.abs(r.value),"%"]}),e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:r.label})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:l})]})]})}function ju({className:s}){const n=ks(),{t:a}=M(),{data:r,isLoading:l}=ie({queryKey:["dashboardStats"],queryFn:async()=>(await bc()).data,refetchInterval:1e3*60*5});if(l||!r)return e.jsx(pu,{});const c=()=>{const o=new URLSearchParams;o.set("commission_status",me.PENDING.toString()),o.set("status",re.COMPLETED.toString()),o.set("commission_balance","gt:0"),n(`/finance/order?${o.toString()}`)};return e.jsxs("div",{className:_("grid gap-4 md:grid-cols-2 lg:grid-cols-4",s),children:[e.jsx(Es,{title:a("dashboard:stats.todayIncome"),value:Fs(r.todayIncome),icon:e.jsx(eo,{className:"h-4 w-4 text-emerald-500"}),trend:{value:r.dayIncomeGrowth,label:a("dashboard:stats.vsYesterday"),isPositive:r.dayIncomeGrowth>0}}),e.jsx(Es,{title:a("dashboard:stats.monthlyIncome"),value:Fs(r.currentMonthIncome),icon:e.jsx(so,{className:"h-4 w-4 text-blue-500"}),trend:{value:r.monthIncomeGrowth,label:a("dashboard:stats.vsLastMonth"),isPositive:r.monthIncomeGrowth>0}}),e.jsx(Es,{title:a("dashboard:stats.pendingTickets"),value:r.ticketPendingTotal,icon:e.jsx(to,{className:_("h-4 w-4",r.ticketPendingTotal>0?"text-orange-500":"text-muted-foreground")}),description:r.ticketPendingTotal>0?a("dashboard:stats.hasPendingTickets"):a("dashboard:stats.noPendingTickets"),onClick:()=>n("/user/ticket"),highlight:r.ticketPendingTotal>0}),e.jsx(Es,{title:a("dashboard:stats.pendingCommission"),value:r.commissionPendingTotal,icon:e.jsx(ao,{className:_("h-4 w-4",r.commissionPendingTotal>0?"text-blue-500":"text-muted-foreground")}),description:r.commissionPendingTotal>0?a("dashboard:stats.hasPendingCommission"):a("dashboard:stats.noPendingCommission"),onClick:c,highlight:r.commissionPendingTotal>0}),e.jsx(Es,{title:a("dashboard:stats.monthlyNewUsers"),value:r.currentMonthNewUsers,icon:e.jsx(pa,{className:"h-4 w-4 text-blue-500"}),trend:{value:r.userGrowth,label:a("dashboard:stats.vsLastMonth"),isPositive:r.userGrowth>0}}),e.jsx(Es,{title:a("dashboard:stats.totalUsers"),value:r.totalUsers,icon:e.jsx(pa,{className:"h-4 w-4 text-muted-foreground"}),description:a("dashboard:stats.activeUsers",{count:r.activeUsers})}),e.jsx(Es,{title:a("dashboard:stats.monthlyUpload"),value:hs(r.monthTraffic.upload),icon:e.jsx(pt,{className:"h-4 w-4 text-emerald-500"}),description:a("dashboard:stats.todayTraffic",{value:hs(r.todayTraffic.upload)})}),e.jsx(Es,{title:a("dashboard:stats.monthlyDownload"),value:hs(r.monthTraffic.download),icon:e.jsx(no,{className:"h-4 w-4 text-blue-500"}),description:a("dashboard:stats.todayTraffic",{value:hs(r.todayTraffic.download)})})]})}const Na={today:{getValue:()=>{const s=io();return{start:s,end:oo(s,1)}}},last7days:{getValue:()=>{const s=new Date;return{start:ls(s,7),end:s}}},last30days:{getValue:()=>{const s=new Date;return{start:ls(s,30),end:s}}},custom:{getValue:()=>null}};function ln({selectedRange:s,customDateRange:n,onRangeChange:a,onCustomRangeChange:r}){const{t:l}=M(),c={today:l("dashboard:trafficRank.today"),last7days:l("dashboard:trafficRank.last7days"),last30days:l("dashboard:trafficRank.last30days"),custom:l("dashboard:trafficRank.customRange")};return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[e.jsxs(J,{value:s,onValueChange:a,children:[e.jsx(W,{className:"w-[120px]",children:e.jsx(Z,{placeholder:l("dashboard:trafficRank.selectTimeRange")})}),e.jsx(Y,{position:"popper",className:"z-50",children:Object.entries(Na).map(([o])=>e.jsx(q,{value:o,children:c[o]},o))})]}),s==="custom"&&e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(X,{variant:"outline",className:_("min-w-0 justify-start text-left font-normal",!n&&"text-muted-foreground"),children:[e.jsx(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:n?.from?n.to?e.jsxs(e.Fragment,{children:[Je(n.from,"yyyy-MM-dd")," -"," ",Je(n.to,"yyyy-MM-dd")]}):Je(n.from,"yyyy-MM-dd"):e.jsx("span",{children:l("dashboard:trafficRank.selectDateRange")})})]})}),e.jsx(ms,{className:"w-auto p-0",align:"end",children:e.jsx(Bs,{mode:"range",defaultMonth:n?.from,selected:{from:n?.from,to:n?.to},onSelect:o=>{o?.from&&o?.to&&r({from:o.from,to:o.to})},numberOfMonths:2})})]})]})}const Ws=s=>`${(s/1024/1024/1024).toFixed(2)} GB`;function vu({className:s}){const{t:n}=M(),[a,r]=m.useState("today"),[l,c]=m.useState({from:ls(new Date,7),to:new Date}),[o,u]=m.useState("today"),[x,i]=m.useState({from:ls(new Date,7),to:new Date}),d=m.useMemo(()=>a==="custom"?{start:l.from,end:l.to}:Na[a].getValue(),[a,l]),f=m.useMemo(()=>o==="custom"?{start:x.from,end:x.to}:Na[o].getValue(),[o,x]),{data:w}=ie({queryKey:["nodeTrafficRank",d.start,d.end],queryFn:()=>tn({type:"node",start_time:Ce.round(d.start.getTime()/1e3),end_time:Ce.round(d.end.getTime()/1e3)}),refetchInterval:3e4}),{data:P}=ie({queryKey:["userTrafficRank",f.start,f.end],queryFn:()=>tn({type:"user",start_time:Ce.round(f.start.getTime()/1e3),end_time:Ce.round(f.end.getTime()/1e3)}),refetchInterval:3e4});return e.jsxs("div",{className:_("grid gap-4 md:grid-cols-2",s),children:[e.jsxs(Be,{children:[e.jsx(es,{className:"flex-none pb-2",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(ws,{className:"flex items-center text-base font-medium",children:[e.jsx(lo,{className:"mr-2 h-4 w-4"}),n("dashboard:trafficRank.nodeTrafficRank")]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(ln,{selectedRange:a,customDateRange:l,onRangeChange:r,onCustomRangeChange:c}),e.jsx(Ya,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})]})}),e.jsx(ss,{className:"flex-1",children:w?.data?e.jsxs(zs,{className:"h-[400px] pr-4",children:[e.jsx("div",{className:"space-y-3",children:w.data.map(C=>e.jsx(je,{delayDuration:200,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx("div",{className:"flex cursor-pointer items-center justify-between space-x-2 rounded-lg bg-muted/50 p-2 transition-colors hover:bg-muted/70",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:C.name}),e.jsxs("span",{className:_("ml-2 flex items-center text-xs font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?e.jsx(fa,{className:"mr-1 h-3 w-3"}):e.jsx(ga,{className:"mr-1 h-3 w-3"}),Math.abs(C.change),"%"]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${C.value/w.data[0].value*100}%`}})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ws(C.value)})]})]})})}),e.jsx(ce,{side:"right",className:"space-y-2 p-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.currentTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Ws(C.value)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.previousTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Ws(C.previousValue)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.changeRate"),":"]}),e.jsxs("span",{className:_("font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?"+":"",C.change,"%"]})]})})]})},C.id))}),e.jsx(At,{orientation:"vertical"})]}):e.jsx("div",{className:"flex h-[400px] items-center justify-center",children:e.jsx("div",{className:"animate-pulse",children:n("common:loading")})})})]}),e.jsxs(Be,{children:[e.jsx(es,{className:"flex-none pb-2",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(ws,{className:"flex items-center text-base font-medium",children:[e.jsx(pa,{className:"mr-2 h-4 w-4"}),n("dashboard:trafficRank.userTrafficRank")]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(ln,{selectedRange:o,customDateRange:x,onRangeChange:u,onCustomRangeChange:i}),e.jsx(Ya,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})]})}),e.jsx(ss,{className:"flex-1",children:P?.data?e.jsxs(zs,{className:"h-[400px] pr-4",children:[e.jsx("div",{className:"space-y-3",children:P.data.map(C=>e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx("div",{className:"flex cursor-pointer items-center justify-between space-x-2 rounded-lg bg-muted/50 p-2 transition-colors hover:bg-muted/70",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:C.name}),e.jsxs("span",{className:_("ml-2 flex items-center text-xs font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?e.jsx(fa,{className:"mr-1 h-3 w-3"}):e.jsx(ga,{className:"mr-1 h-3 w-3"}),Math.abs(C.change),"%"]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${C.value/P.data[0].value*100}%`}})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ws(C.value)})]})]})})}),e.jsx(ce,{side:"right",className:"space-y-2 p-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.currentTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Ws(C.value)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.previousTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Ws(C.previousValue)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.changeRate"),":"]}),e.jsxs("span",{className:_("font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?"+":"",C.change,"%"]})]})})]})},C.id))}),e.jsx(At,{orientation:"vertical"})]}):e.jsx("div",{className:"flex h-[400px] items-center justify-center",children:e.jsx("div",{className:"animate-pulse",children:n("common:loading")})})})]})]})}const Et=m.forwardRef(({className:s,value:n,...a},r)=>e.jsx(sr,{ref:r,className:_("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",s),...a,children:e.jsx(co,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(n||0)}%)`}})}));Et.displayName=sr.displayName;function bu(){const{t:s}=M(),[n,a]=m.useState(null),[r,l]=m.useState(null),[c,o]=m.useState(!0),[u,x]=m.useState(!1),i=async()=>{try{x(!0);const[w,P]=await Promise.all([rn.getSystemStatus(),rn.getQueueStats()]);a(w.data),l(P.data)}catch(w){console.error("Error fetching system data:",w)}finally{o(!1),x(!1)}};m.useEffect(()=>{i();const w=setInterval(i,3e4);return()=>clearInterval(w)},[]);const d=()=>{i()};if(c)return e.jsx("div",{className:"flex items-center justify-center p-6",children:e.jsx(Pa,{className:"h-6 w-6 animate-spin"})});const f=w=>w?e.jsx(tr,{className:"h-5 w-5 text-green-500"}):e.jsx(ar,{className:"h-5 w-5 text-red-500"});return e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(Be,{children:[e.jsxs(es,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(uo,{className:"h-5 w-5"}),s("dashboard:queue.title")]}),e.jsx(Zs,{children:s("dashboard:queue.status.description")})]}),e.jsx(X,{variant:"outline",size:"icon",onClick:d,disabled:u,children:e.jsx(mo,{className:_("h-4 w-4",u&&"animate-spin")})})]}),e.jsx(ss,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[f(r?.status||!1),e.jsx("span",{className:"font-medium",children:s("dashboard:queue.status.running")})]}),e.jsx(K,{variant:r?.status?"secondary":"destructive",children:r?.status?s("dashboard:queue.status.normal"):s("dashboard:queue.status.abnormal")})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.status.waitTime",{seconds:r?.wait?.default||0})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.recentJobs")}),e.jsx("p",{className:"text-2xl font-bold",children:r?.recentJobs||0}),e.jsx(Et,{value:(r?.recentJobs||0)/(r?.periods?.recentJobs||1)*100,className:"h-1"})]})}),e.jsx(ce,{children:e.jsx("p",{children:s("dashboard:queue.details.statisticsPeriod",{hours:r?.periods?.recentJobs||0})})})]})}),e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.jobsPerMinute")}),e.jsx("p",{className:"text-2xl font-bold",children:r?.jobsPerMinute||0}),e.jsx(Et,{value:(r?.jobsPerMinute||0)/(r?.queueWithMaxThroughput?.throughput||1)*100,className:"h-1"})]})}),e.jsx(ce,{children:e.jsx("p",{children:s("dashboard:queue.details.maxThroughput",{value:r?.queueWithMaxThroughput?.throughput||0})})})]})})]})]})})]}),e.jsxs(Be,{children:[e.jsxs(es,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5"}),s("dashboard:queue.jobDetails")]}),e.jsx(Zs,{children:s("dashboard:queue.details.description")})]}),e.jsx(ss,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.failedJobs7Days")}),e.jsx("p",{className:"text-2xl font-bold text-destructive",children:r?.failedJobs||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("dashboard:queue.details.retentionPeriod",{hours:r?.periods?.failedJobs||0})})]}),e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.longestRunningQueue")}),e.jsxs("p",{className:"text-2xl font-bold",children:[r?.queueWithMaxRuntime?.runtime||0,"s"]}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:r?.queueWithMaxRuntime?.name||"N/A"})]})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.activeProcesses")}),e.jsxs("span",{className:"font-medium",children:[r?.processes||0," /"," ",(r?.processes||0)+(r?.pausedMasters||0)]})]}),e.jsx(Et,{value:(r?.processes||0)/((r?.processes||0)+(r?.pausedMasters||0))*100,className:"mt-2 h-1"})]})]})})]})]})}function yu(){const{t:s}=M();return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx("div",{className:"flex items-center",children:e.jsx("h1",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:s("dashboard:title")})}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(qe,{}),e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsx(Ve,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6",children:[e.jsx(ju,{}),e.jsx(xu,{}),e.jsx(vu,{}),e.jsx(bu,{})]})})})]})}const Nu=Object.freeze(Object.defineProperty({__proto__:null,default:yu},Symbol.toStringTag,{value:"Module"}));function _u({className:s,items:n,...a}){const{pathname:r}=wa(),l=ks(),[c,o]=m.useState(r??"/settings"),u=i=>{o(i),l(i)},{t:x}=M("settings");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-1 md:hidden",children:e.jsxs(J,{value:c,onValueChange:u,children:[e.jsx(W,{className:"h-12 sm:w-48",children:e.jsx(Z,{placeholder:"Theme"})}),e.jsx(Y,{children:n.map(i=>e.jsx(q,{value:i.href,children:e.jsxs("div",{className:"flex gap-x-4 px-2 py-1",children:[e.jsx("span",{className:"scale-125",children:i.icon}),e.jsx("span",{className:"text-md",children:x(i.title)})]})},i.href))})]})}),e.jsx("div",{className:"hidden w-full overflow-x-auto bg-background px-1 py-2 md:block",children:e.jsx("nav",{className:_("flex space-x-2 lg:flex-col lg:space-x-0 lg:space-y-1",s),...a,children:n.map(i=>e.jsxs($s,{to:i.href,className:_(tt({variant:"ghost"}),r===i.href?"bg-muted hover:bg-muted":"hover:bg-transparent hover:underline","justify-start"),children:[e.jsx("span",{className:"mr-2",children:i.icon}),x(i.title)]},i.href))})})]})}const wu=[{title:"site.title",key:"site",icon:e.jsx(ho,{size:18}),href:"/config/system",description:"site.description"},{title:"safe.title",key:"safe",icon:e.jsx(zn,{size:18}),href:"/config/system/safe",description:"safe.description"},{title:"subscribe.title",key:"subscribe",icon:e.jsx(Ln,{size:18}),href:"/config/system/subscribe",description:"subscribe.description"},{title:"invite.title",key:"invite",icon:e.jsx(po,{size:18}),href:"/config/system/invite",description:"invite.description"},{title:"server.title",key:"server",icon:e.jsx(On,{size:18}),href:"/config/system/server",description:"server.description"},{title:"email.title",key:"email",icon:e.jsx(fo,{size:18}),href:"/config/system/email",description:"email.description"},{title:"telegram.title",key:"telegram",icon:e.jsx(go,{size:18}),href:"/config/system/telegram",description:"telegram.description"},{title:"app.title",key:"app",icon:e.jsx(Fn,{size:18}),href:"/config/system/app",description:"app.description"},{title:"subscribe_template.title",key:"subscribe_template",icon:e.jsx(jo,{size:18}),href:"/config/system/subscribe-template",description:"subscribe_template.description"}];function Cu(){const{t:s}=M("settings");return e.jsxs(Pe,{fadedBelow:!0,fixedHeight:!0,children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:s("title")}),e.jsx("div",{className:"text-muted-foreground",children:s("description")})]}),e.jsx(Se,{className:"my-6"}),e.jsxs("div",{className:"flex flex-1 flex-col space-y-8 overflow-auto lg:flex-row lg:space-x-12 lg:space-y-0",children:[e.jsx("aside",{className:"sticky top-0 lg:w-1/5",children:e.jsx(_u,{items:wu})}),e.jsx("div",{className:"flex-1 w-full p-1 pr-4",children:e.jsx("div",{className:"pb-16",children:e.jsx(Ca,{})})})]})]})]})}const Su=Object.freeze(Object.defineProperty({__proto__:null,default:Cu},Symbol.toStringTag,{value:"Module"})),Q=m.forwardRef(({className:s,...n},a)=>e.jsx(nr,{className:_("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...n,ref:a,children:e.jsx(vo,{className:_("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Q.displayName=nr.displayName;const bs=m.forwardRef(({className:s,...n},a)=>e.jsx("textarea",{className:_("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:a,...n}));bs.displayName="Textarea";const ku=h.object({logo:h.string().nullable().default(""),force_https:h.number().nullable().default(0),stop_register:h.number().nullable().default(0),app_name:h.string().nullable().default(""),app_description:h.string().nullable().default(""),app_url:h.string().nullable().default(""),subscribe_url:h.string().nullable().default(""),try_out_plan_id:h.number().nullable().default(0),try_out_hour:h.coerce.number().nullable().default(0),tos_url:h.string().nullable().default(""),currency:h.string().nullable().default(""),currency_symbol:h.string().nullable().default("")});function Tu(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),{data:l}=ie({queryKey:["settings","site"],queryFn:()=>fs("site")}),{data:c}=ie({queryKey:["plans"],queryFn:()=>Hs()}),o=fe({resolver:ye(ku),defaultValues:{},mode:"onBlur"}),{mutateAsync:u}=Ze({mutationFn:gs,onSuccess:d=>{d.data&&A.success(s("common.autoSaved"))}});m.useEffect(()=>{if(l?.data?.site){const d=l?.data?.site;Object.entries(d).forEach(([f,w])=>{o.setValue(f,w)}),r.current=d}},[l]);const x=m.useCallback(Ce.debounce(async d=>{if(!Ce.isEqual(d,r.current)){a(!0);try{const f=Object.entries(d).reduce((w,[P,C])=>(w[P]=C===null?"":C,w),{});await u(f),r.current=d}finally{a(!1)}}},1e3),[u]),i=m.useCallback(d=>{x(d)},[x]);return m.useEffect(()=>{const d=o.watch(f=>{i(f)});return()=>d.unsubscribe()},[o.watch,i]),e.jsx(Ne,{...o,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:o.control,name:"app_name",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.siteName.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.siteName.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.siteName.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"app_description",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.siteDescription.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.siteDescription.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.siteDescription.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"app_url",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.siteUrl.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.siteUrl.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.siteUrl.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"force_https",render:({field:d})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("site.form.forceHttps.label")}),e.jsx(z,{children:s("site.form.forceHttps.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:!!d.value,onCheckedChange:f=>{d.onChange(Number(f)),i(o.getValues())}})})]})}),e.jsx(b,{control:o.control,name:"logo",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.logo.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.logo.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.logo.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"subscribe_url",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.subscribeUrl.label")}),e.jsx(N,{children:e.jsx(bs,{placeholder:s("site.form.subscribeUrl.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.subscribeUrl.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"tos_url",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.tosUrl.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.tosUrl.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.tosUrl.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"stop_register",render:({field:d})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("site.form.stopRegister.label")}),e.jsx(z,{children:s("site.form.stopRegister.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:!!d.value,onCheckedChange:f=>{d.onChange(Number(f)),i(o.getValues())}})})]})}),e.jsx(b,{control:o.control,name:"try_out_plan_id",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.tryOut.label")}),e.jsx(N,{children:e.jsxs(J,{value:d.value?.toString(),onValueChange:f=>{d.onChange(Number(f)),i(o.getValues())},children:[e.jsx(W,{children:e.jsx(Z,{placeholder:s("site.form.tryOut.placeholder")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("site.form.tryOut.placeholder")}),c?.data?.map(f=>e.jsx(q,{value:f.id.toString(),children:f.name},f.id.toString()))]})]})}),e.jsx(z,{children:s("site.form.tryOut.description")}),e.jsx(k,{})]})}),!!o.watch("try_out_plan_id")&&e.jsx(b,{control:o.control,name:"try_out_hour",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"",children:s("site.form.tryOut.duration.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.tryOut.duration.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.tryOut.duration.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"currency",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.currency.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.currency.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.currency.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:o.control,name:"currency_symbol",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("site.form.currencySymbol.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("site.form.currencySymbol.placeholder"),...d,value:d.value||"",onChange:f=>{d.onChange(f),i(o.getValues())}})}),e.jsx(z,{children:s("site.form.currencySymbol.description")}),e.jsx(k,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("site.form.saving")})]})})}function Du(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("site.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("site.description")})]}),e.jsx(Se,{}),e.jsx(Tu,{})]})}const Pu=Object.freeze(Object.defineProperty({__proto__:null,default:Du},Symbol.toStringTag,{value:"Module"})),Eu=h.object({email_verify:h.boolean().nullable(),safe_mode_enable:h.boolean().nullable(),secure_path:h.string().nullable(),email_whitelist_enable:h.boolean().nullable(),email_whitelist_suffix:h.array(h.string().nullable()).nullable(),email_gmail_limit_enable:h.boolean().nullable(),recaptcha_enable:h.boolean().nullable(),recaptcha_key:h.string().nullable(),recaptcha_site_key:h.string().nullable(),register_limit_by_ip_enable:h.boolean().nullable(),register_limit_count:h.coerce.string().transform(s=>s===""?null:s).nullable(),register_limit_expire:h.coerce.string().transform(s=>s===""?null:s).nullable(),password_limit_enable:h.boolean().nullable(),password_limit_count:h.coerce.string().transform(s=>s===""?null:s).nullable(),password_limit_expire:h.coerce.string().transform(s=>s===""?null:s).nullable()}),Ru={email_verify:!1,safe_mode_enable:!1,secure_path:"",email_whitelist_enable:!1,email_whitelist_suffix:[],email_gmail_limit_enable:!1,recaptcha_enable:!1,recaptcha_key:"",recaptcha_site_key:"",register_limit_by_ip_enable:!1,register_limit_count:"",register_limit_expire:"",password_limit_enable:!1,password_limit_count:"",password_limit_expire:""};function Iu(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),l=fe({resolver:ye(Eu),defaultValues:Ru,mode:"onBlur"}),{data:c}=ie({queryKey:["settings","safe"],queryFn:()=>fs("safe")}),{mutateAsync:o}=Ze({mutationFn:gs,onSuccess:i=>{i.data&&A.success(s("common.autoSaved"))}});m.useEffect(()=>{if(c?.data.safe){const i=c.data.safe;Object.entries(i).forEach(([d,f])=>{typeof f=="number"?l.setValue(d,String(f)):l.setValue(d,f)}),r.current=i}},[c]);const u=m.useCallback(Ce.debounce(async i=>{if(!Ce.isEqual(i,r.current)){a(!0);try{await o(i),r.current=i}finally{a(!1)}}},1e3),[o]),x=m.useCallback(i=>{u(i)},[u]);return m.useEffect(()=>{const i=l.watch(d=>{x(d)});return()=>i.unsubscribe()},[l.watch,x]),e.jsx(Ne,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:l.control,name:"email_verify",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.emailVerify.label")}),e.jsx(z,{children:s("safe.form.emailVerify.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"email_gmail_limit_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.gmailLimit.label")}),e.jsx(z,{children:s("safe.form.gmailLimit.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"safe_mode_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.safeMode.label")}),e.jsx(z,{children:s("safe.form.safeMode.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"secure_path",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.securePath.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.securePath.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.securePath.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"email_whitelist_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.emailWhitelist.label")}),e.jsx(z,{children:s("safe.form.emailWhitelist.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),l.watch("email_whitelist_enable")&&e.jsx(b,{control:l.control,name:"email_whitelist_suffix",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.emailWhitelist.suffixes.label")}),e.jsx(N,{children:e.jsx(bs,{placeholder:s("safe.form.emailWhitelist.suffixes.placeholder"),...i,value:(i.value||[]).join(` -`),onChange:d=>{const f=d.target.value.split(` -`).filter(Boolean);i.onChange(f),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.emailWhitelist.suffixes.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"recaptcha_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.recaptcha.enable.label")}),e.jsx(z,{children:s("safe.form.recaptcha.enable.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),l.watch("recaptcha_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(b,{control:l.control,name:"recaptcha_site_key",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.recaptcha.siteKey.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.recaptcha.siteKey.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.recaptcha.siteKey.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"recaptcha_key",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.recaptcha.key.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.recaptcha.key.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.recaptcha.key.description")}),e.jsx(k,{})]})})]}),e.jsx(b,{control:l.control,name:"register_limit_by_ip_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.registerLimit.enable.label")}),e.jsx(z,{children:s("safe.form.registerLimit.enable.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),l.watch("register_limit_by_ip_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(b,{control:l.control,name:"register_limit_count",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.registerLimit.count.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.registerLimit.count.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.registerLimit.count.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"register_limit_expire",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.registerLimit.expire.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.registerLimit.expire.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.registerLimit.expire.description")}),e.jsx(k,{})]})})]}),e.jsx(b,{control:l.control,name:"password_limit_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("safe.form.passwordLimit.enable.label")}),e.jsx(z,{children:s("safe.form.passwordLimit.enable.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),l.watch("password_limit_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(b,{control:l.control,name:"password_limit_count",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.passwordLimit.count.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.passwordLimit.count.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.passwordLimit.count.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"password_limit_expire",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("safe.form.passwordLimit.expire.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("safe.form.passwordLimit.expire.placeholder"),...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(z,{children:s("safe.form.passwordLimit.expire.description")}),e.jsx(k,{})]})})]}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("safe.form.saving")})]})})}function Vu(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("safe.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("safe.description")})]}),e.jsx(Se,{}),e.jsx(Iu,{})]})}const Mu=Object.freeze(Object.defineProperty({__proto__:null,default:Vu},Symbol.toStringTag,{value:"Module"})),Fu=h.object({plan_change_enable:h.boolean().nullable().default(!1),reset_traffic_method:h.coerce.number().nullable().default(0),surplus_enable:h.boolean().nullable().default(!1),new_order_event_id:h.coerce.number().nullable().default(0),renew_order_event_id:h.coerce.number().nullable().default(0),change_order_event_id:h.coerce.number().nullable().default(0),show_info_to_server_enable:h.boolean().nullable().default(!1),show_protocol_to_server_enable:h.boolean().nullable().default(!1),default_remind_expire:h.boolean().nullable().default(!1),default_remind_traffic:h.boolean().nullable().default(!1),subscribe_path:h.string().nullable().default("s")}),Ou={plan_change_enable:!1,reset_traffic_method:0,surplus_enable:!1,new_order_event_id:0,renew_order_event_id:0,change_order_event_id:0,show_info_to_server_enable:!1,show_protocol_to_server_enable:!1,default_remind_expire:!1,default_remind_traffic:!1,subscribe_path:"s"};function zu(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),l=fe({resolver:ye(Fu),defaultValues:Ou,mode:"onBlur"}),{data:c}=ie({queryKey:["settings","subscribe"],queryFn:()=>fs("subscribe")}),{mutateAsync:o}=Ze({mutationFn:gs,onSuccess:i=>{i.data&&A.success(s("common.autoSaved"))}});m.useEffect(()=>{if(c?.data?.subscribe){const i=c?.data?.subscribe;Object.entries(i).forEach(([d,f])=>{l.setValue(d,f)}),r.current=i}},[c]);const u=m.useCallback(Ce.debounce(async i=>{if(!Ce.isEqual(i,r.current)){a(!0);try{await o(i),r.current=i}finally{a(!1)}}},1e3),[o]),x=m.useCallback(i=>{u(i)},[u]);return m.useEffect(()=>{const i=l.watch(d=>{x(d)});return()=>i.unsubscribe()},[l.watch,x]),e.jsx(Ne,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:l.control,name:"plan_change_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.plan_change_enable.title")}),e.jsx(z,{children:s("subscribe.plan_change_enable.description")}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"reset_traffic_method",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.reset_traffic_method.title")}),e.jsxs(J,{onValueChange:i.onChange,value:i.value?.toString()||"0",children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:"请选择重置方式"})})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("subscribe.reset_traffic_method.options.monthly_first")}),e.jsx(q,{value:"1",children:s("subscribe.reset_traffic_method.options.monthly_reset")}),e.jsx(q,{value:"2",children:s("subscribe.reset_traffic_method.options.no_reset")}),e.jsx(q,{value:"3",children:s("subscribe.reset_traffic_method.options.yearly_first")}),e.jsx(q,{value:"4",children:s("subscribe.reset_traffic_method.options.yearly_reset")})]})]}),e.jsx(z,{children:s("subscribe.reset_traffic_method.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"surplus_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.surplus_enable.title")}),e.jsx(z,{children:s("subscribe.surplus_enable.description")}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"new_order_event_id",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.new_order_event.title")}),e.jsx("div",{className:"relative w-max",children:e.jsx(N,{children:e.jsxs(J,{onValueChange:i.onChange,value:i.value?.toString(),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:"请选择"})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("subscribe.new_order_event.options.no_action")}),e.jsx(q,{value:"1",children:s("subscribe.new_order_event.options.reset_traffic")})]})]})})}),e.jsx(z,{children:s("subscribe.new_order_event.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"renew_order_event_id",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.renew_order_event.title")}),e.jsx("div",{className:"relative w-max",children:e.jsx(N,{children:e.jsxs(J,{onValueChange:i.onChange,value:i.value?.toString(),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:"请选择"})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("subscribe.renew_order_event.options.no_action")}),e.jsx(q,{value:"1",children:s("subscribe.renew_order_event.options.reset_traffic")})]})]})})}),e.jsx(z,{children:s("renew_order_event.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"change_order_event_id",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.change_order_event.title")}),e.jsx("div",{className:"relative w-max",children:e.jsx(N,{children:e.jsxs(J,{onValueChange:i.onChange,value:i.value?.toString(),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:"请选择"})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("subscribe.change_order_event.options.no_action")}),e.jsx(q,{value:"1",children:s("subscribe.change_order_event.options.reset_traffic")})]})]})})}),e.jsx(z,{children:s("subscribe.change_order_event.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"subscribe_path",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("subscribe.subscribe_path.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:"subscribe",...i,value:i.value||"",onChange:d=>{i.onChange(d),x(l.getValues())}})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[s("subscribe.subscribe_path.description"),e.jsx("br",{}),s("subscribe.subscribe_path.current_format",{path:i.value||"s"})]}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"show_info_to_server_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("subscribe.show_info_to_server.title")}),e.jsx(z,{children:s("subscribe.show_info_to_server.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"show_protocol_to_server_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("subscribe.show_protocol_to_server.title")}),e.jsx(z,{children:s("subscribe.show_protocol_to_server.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value||!1,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function Lu(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("subscribe.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("subscribe.description")})]}),e.jsx(Se,{}),e.jsx(zu,{})]})}const Au=Object.freeze(Object.defineProperty({__proto__:null,default:Lu},Symbol.toStringTag,{value:"Module"})),$u=h.object({invite_force:h.boolean().default(!1),invite_commission:h.coerce.string().default("0"),invite_gen_limit:h.coerce.string().default("0"),invite_never_expire:h.boolean().default(!1),commission_first_time_enable:h.boolean().default(!1),commission_auto_check_enable:h.boolean().default(!1),commission_withdraw_limit:h.coerce.string().default("0"),commission_withdraw_method:h.array(h.string()).default(["支付宝","USDT","Paypal"]),withdraw_close_enable:h.boolean().default(!1),commission_distribution_enable:h.boolean().default(!1),commission_distribution_l1:h.coerce.number().default(0),commission_distribution_l2:h.coerce.number().default(0),commission_distribution_l3:h.coerce.number().default(0)}),qu={invite_force:!1,invite_commission:"0",invite_gen_limit:"0",invite_never_expire:!1,commission_first_time_enable:!1,commission_auto_check_enable:!1,commission_withdraw_limit:"0",commission_withdraw_method:["支付宝","USDT","Paypal"],withdraw_close_enable:!1,commission_distribution_enable:!1,commission_distribution_l1:0,commission_distribution_l2:0,commission_distribution_l3:0};function Hu(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),l=fe({resolver:ye($u),defaultValues:qu,mode:"onBlur"}),{data:c}=ie({queryKey:["settings","invite"],queryFn:()=>fs("invite")}),{mutateAsync:o}=Ze({mutationFn:gs,onSuccess:i=>{i.data&&A.success(s("common.autoSaved"))}});m.useEffect(()=>{if(c?.data?.invite){const i=c?.data?.invite;Object.entries(i).forEach(([d,f])=>{typeof f=="number"?l.setValue(d,String(f)):l.setValue(d,f)}),r.current=i}},[c]);const u=m.useCallback(Ce.debounce(async i=>{if(!Ce.isEqual(i,r.current)){a(!0);try{await o(i),r.current=i}finally{a(!1)}}},1e3),[o]),x=m.useCallback(i=>{u(i)},[u]);return m.useEffect(()=>{const i=l.watch(d=>{x(d)});return()=>i.unsubscribe()},[l.watch,x]),e.jsx(Ne,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:l.control,name:"invite_force",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("invite.invite_force.title")}),e.jsx(z,{children:s("invite.invite_force.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"invite_commission",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("invite.invite_commission.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("invite.invite_commission.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("invite.invite_commission.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"invite_gen_limit",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("invite.invite_gen_limit.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("invite.invite_gen_limit.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("invite.invite_gen_limit.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"invite_never_expire",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("invite.invite_never_expire.title")}),e.jsx(z,{children:s("invite.invite_never_expire.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"commission_first_time_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("invite.commission_first_time.title")}),e.jsx(z,{children:s("invite.commission_first_time.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"commission_auto_check_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("invite.commission_auto_check.title")}),e.jsx(z,{children:s("invite.commission_auto_check.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"commission_withdraw_limit",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("invite.commission_withdraw_limit.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("invite.commission_withdraw_limit.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("invite.commission_withdraw_limit.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"commission_withdraw_method",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("invite.commission_withdraw_method.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("invite.commission_withdraw_method.placeholder"),...i,value:Array.isArray(i.value)?i.value.join(","):"",onChange:d=>{const f=d.target.value.split(",").filter(Boolean);i.onChange(f),x(l.getValues())}})}),e.jsx(z,{children:s("invite.commission_withdraw_method.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"withdraw_close_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("invite.withdraw_close.title")}),e.jsx(z,{children:s("invite.withdraw_close.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),e.jsx(b,{control:l.control,name:"commission_distribution_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("invite.commission_distribution.title")}),e.jsx(z,{children:s("invite.commission_distribution.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:d=>{i.onChange(d),x(l.getValues())}})})]})}),l.watch("commission_distribution_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(b,{control:l.control,name:"commission_distribution_l1",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:s("invite.commission_distribution.l1")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:s("invite.commission_distribution.placeholder"),...i,value:i.value||"",onChange:d=>{const f=d.target.value?Number(d.target.value):0;i.onChange(f),x(l.getValues())}})}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"commission_distribution_l2",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:s("invite.commission_distribution.l2")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:s("invite.commission_distribution.placeholder"),...i,value:i.value||"",onChange:d=>{const f=d.target.value?Number(d.target.value):0;i.onChange(f),x(l.getValues())}})}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"commission_distribution_l3",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:s("invite.commission_distribution.l3")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:s("invite.commission_distribution.placeholder"),...i,value:i.value||"",onChange:d=>{const f=d.target.value?Number(d.target.value):0;i.onChange(f),x(l.getValues())}})}),e.jsx(k,{})]})})]}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("invite.saving")})]})})}function Uu(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("invite.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("invite.description")})]}),e.jsx(Se,{}),e.jsx(Hu,{})]})}const Ku=Object.freeze(Object.defineProperty({__proto__:null,default:Uu},Symbol.toStringTag,{value:"Module"})),Bu=h.object({frontend_theme:h.string().nullable(),frontend_theme_sidebar:h.string().nullable(),frontend_theme_header:h.string().nullable(),frontend_theme_color:h.string().nullable(),frontend_background_url:h.string().url().nullable()}),Gu={frontend_theme:"",frontend_theme_sidebar:"",frontend_theme_header:"",frontend_theme_color:"",frontend_background_url:""};function Wu(){const{data:s}=ie({queryKey:["settings","frontend"],queryFn:()=>fs("frontend")}),n=fe({resolver:ye(Bu),defaultValues:Gu,mode:"onChange"});m.useEffect(()=>{if(s?.data?.frontend){const r=s?.data?.frontend;Object.entries(r).forEach(([l,c])=>{n.setValue(l,c)})}},[s]);function a(r){gs(r).then(({data:l})=>{l&&A.success("更新成功")})}return e.jsx(Ne,{...n,children:e.jsxs("form",{onSubmit:n.handleSubmit(a),className:"space-y-8",children:[e.jsx(b,{control:n.control,name:"frontend_theme_sidebar",render:({field:r})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:"边栏风格"}),e.jsx(z,{children:"边栏风格"})]}),e.jsx(N,{children:e.jsx(Q,{checked:r.value,onCheckedChange:r.onChange})})]})}),e.jsx(b,{control:n.control,name:"frontend_theme_header",render:({field:r})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:"头部风格"}),e.jsx(z,{children:"边栏风格"})]}),e.jsx(N,{children:e.jsx(Q,{checked:r.value,onCheckedChange:r.onChange})})]})}),e.jsx(b,{control:n.control,name:"frontend_theme_color",render:({field:r})=>e.jsxs(v,{children:[e.jsx(y,{children:"主题色"}),e.jsxs("div",{className:"relative w-max",children:[e.jsx(N,{children:e.jsxs("select",{className:_(tt({variant:"outline"}),"w-[200px] appearance-none font-normal"),...r,children:[e.jsx("option",{value:"default",children:"默认"}),e.jsx("option",{value:"black",children:"黑色"}),e.jsx("option",{value:"blackblue",children:"暗蓝色"}),e.jsx("option",{value:"green",children:"奶绿色"})]})}),e.jsx(Da,{className:"absolute right-3 top-2.5 h-4 w-4 opacity-50"})]}),e.jsx(z,{children:"主题色"}),e.jsx(k,{})]})}),e.jsx(b,{control:n.control,name:"frontend_background_url",render:({field:r})=>e.jsxs(v,{children:[e.jsx(y,{children:"背景"}),e.jsx(N,{children:e.jsx(T,{placeholder:"请输入图片地址",...r})}),e.jsx(z,{children:"将会在后台登录页面进行展示。"}),e.jsx(k,{})]})}),e.jsx(D,{type:"submit",children:"保存设置"})]})})}function Yu(){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:"个性化设置"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"自定义系统界面外观,包括主题风格、布局、颜色方案、背景图等个性化选项。"})]}),e.jsx(Se,{}),e.jsx(Wu,{})]})}const Qu=Object.freeze(Object.defineProperty({__proto__:null,default:Yu},Symbol.toStringTag,{value:"Module"})),Ju=h.object({server_pull_interval:h.coerce.number().nullable(),server_push_interval:h.coerce.number().nullable(),server_token:h.string().nullable(),device_limit_mode:h.coerce.number().nullable()}),Zu={server_pull_interval:0,server_push_interval:0,server_token:"",device_limit_mode:0};function Xu(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),l=fe({resolver:ye(Ju),defaultValues:Zu,mode:"onBlur"}),{data:c}=ie({queryKey:["settings","server"],queryFn:()=>fs("server")}),{mutateAsync:o}=Ze({mutationFn:gs,onSuccess:d=>{d.data&&A.success(s("common.AutoSaved"))}});m.useEffect(()=>{if(c?.data.server){const d=c.data.server;Object.entries(d).forEach(([f,w])=>{l.setValue(f,w)}),r.current=d}},[c]);const u=m.useCallback(Ce.debounce(async d=>{if(!Ce.isEqual(d,r.current)){a(!0);try{await o(d),r.current=d}finally{a(!1)}}},1e3),[o]),x=m.useCallback(d=>{u(d)},[u]);m.useEffect(()=>{const d=l.watch(f=>{x(f)});return()=>d.unsubscribe()},[l.watch,x]);const i=()=>{const d=Math.floor(Math.random()*17)+16,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let w="";for(let P=0;Pe.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("server.server_token.title")}),e.jsx(N,{children:e.jsxs("div",{className:"relative",children:[e.jsx(T,{placeholder:s("server.server_token.placeholder"),...d,value:d.value||"",className:"pr-10"}),e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(X,{type:"button",variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full px-3 py-2",onClick:f=>{f.preventDefault(),i()},children:e.jsx(bo,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"})})}),e.jsx(ce,{children:e.jsx("p",{children:s("server.server_token.generate_tooltip")})})]})})]})}),e.jsx(z,{children:s("server.server_token.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"server_pull_interval",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("server.server_pull_interval.title")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:s("server.server_pull_interval.placeholder"),...d,value:d.value||"",onChange:f=>{const w=f.target.value?Number(f.target.value):null;d.onChange(w)}})}),e.jsx(z,{children:s("server.server_pull_interval.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"server_push_interval",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("server.server_push_interval.title")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:s("server.server_push_interval.placeholder"),...d,value:d.value||"",onChange:f=>{const w=f.target.value?Number(f.target.value):null;d.onChange(w)}})}),e.jsx(z,{children:s("server.server_push_interval.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"device_limit_mode",render:({field:d})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("server.device_limit_mode.title")}),e.jsxs(J,{onValueChange:d.onChange,value:d.value?.toString()||"0",children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:s("server.device_limit_mode.placeholder")})})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("server.device_limit_mode.strict")}),e.jsx(q,{value:"1",children:s("server.device_limit_mode.relaxed")})]})]}),e.jsx(z,{children:s("server.device_limit_mode.description")}),e.jsx(k,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("server.saving")})]})})}function em(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("server.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("server.description")})]}),e.jsx(Se,{}),e.jsx(Xu,{})]})}const sm=Object.freeze(Object.defineProperty({__proto__:null,default:em},Symbol.toStringTag,{value:"Module"}));function tm({open:s,onOpenChange:n,result:a}){const r=!a.error;return e.jsx(ve,{open:s,onOpenChange:n,children:e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(tr,{className:"h-5 w-5 text-green-500"}):e.jsx(ar,{className:"h-5 w-5 text-destructive"}),e.jsx(be,{children:r?"邮件发送成功":"邮件发送失败"})]}),e.jsx(ke,{children:r?"测试邮件已成功发送,请检查收件箱":"发送测试邮件时遇到错误"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"font-medium",children:"发送详情"}),e.jsxs("div",{className:"grid grid-cols-[100px_1fr] items-center gap-2 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:"收件地址"}),e.jsx("div",{children:a.email}),e.jsx("div",{className:"text-muted-foreground",children:"邮件主题"}),e.jsx("div",{children:a.subject}),e.jsx("div",{className:"text-muted-foreground",children:"模板名称"}),e.jsx("div",{children:a.template_name})]})]}),a.error&&e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"font-medium text-destructive",children:"错误信息"}),e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive break-all",children:a.error})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"font-medium",children:"配置信息"}),e.jsx(zs,{className:"h-[200px] rounded-md border p-4",children:e.jsx("div",{className:"grid gap-2 text-sm",children:e.jsxs("div",{className:"grid grid-cols-[100px_1fr] items-center gap-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"驱动"}),e.jsx("div",{children:a.config.driver}),e.jsx("div",{className:"text-muted-foreground",children:"服务器"}),e.jsx("div",{children:a.config.host}),e.jsx("div",{className:"text-muted-foreground",children:"端口"}),e.jsx("div",{children:a.config.port}),e.jsx("div",{className:"text-muted-foreground",children:"加密方式"}),e.jsx("div",{children:a.config.encryption||"无"}),e.jsx("div",{className:"text-muted-foreground",children:"发件人"}),e.jsx("div",{children:a.config.from.address?`${a.config.from.address}${a.config.from.name?` (${a.config.from.name})`:""}`:"未设置"}),e.jsx("div",{className:"text-muted-foreground",children:"用户名"}),e.jsx("div",{children:a.config.username||"未设置"})]})})})]})]})]})})}const am=h.object({email_template:h.string().nullable().default("classic"),email_host:h.string().nullable().default(""),email_port:h.coerce.number().nullable().default(465),email_username:h.string().nullable().default(""),email_password:h.string().nullable().default(""),email_encryption:h.string().nullable().default(""),email_from_address:h.string().email().nullable().default(""),remind_mail_enable:h.boolean().nullable().default(!1)});function nm(){const{t:s}=M("settings"),[n,a]=m.useState(null),[r,l]=m.useState(!1),c=m.useRef(null),[o,u]=m.useState(!1),x=fe({resolver:ye(am),defaultValues:{},mode:"onBlur"}),{data:i}=ie({queryKey:["settings","email"],queryFn:()=>fs("email")}),{data:d}=ie({queryKey:["emailTemplate"],queryFn:()=>jd()}),{mutateAsync:f}=Ze({mutationFn:gs,onSuccess:g=>{g.data&&A.success(s("common.autoSaved"))}}),{mutate:w,isPending:P}=Ze({mutationFn:vd,onMutate:()=>{a(null),l(!1)},onSuccess:g=>{a(g.data),l(!0),g.data.error?A.error(s("email.test.error")):A.success(s("email.test.success"))}});m.useEffect(()=>{if(i?.data.email){const g=i.data.email;Object.entries(g).forEach(([j,S])=>{x.setValue(j,S)}),c.current=g}},[i]);const C=m.useCallback(Ce.debounce(async g=>{if(!Ce.isEqual(g,c.current)){u(!0);try{await f(g),c.current=g}finally{u(!1)}}},1e3),[f]),p=m.useCallback(g=>{C(g)},[C]);return m.useEffect(()=>{const g=x.watch(j=>{p(j)});return()=>g.unsubscribe()},[x.watch,p]),e.jsxs(e.Fragment,{children:[e.jsx(Ne,{...x,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:x.control,name:"email_host",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_host.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...g,value:g.value||""})}),e.jsx(z,{children:s("email.email_host.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"email_port",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_port.title")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:s("common.placeholder"),...g,value:g.value||"",onChange:j=>{const S=j.target.value?Number(j.target.value):null;g.onChange(S)}})}),e.jsx(z,{children:s("email.email_port.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"email_encryption",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_encryption.title")}),e.jsxs(J,{onValueChange:g.onChange,value:g.value||"none",children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:"请选择加密方式"})})}),e.jsxs(Y,{children:[e.jsx(q,{value:"none",children:s("email.email_encryption.none")}),e.jsx(q,{value:"ssl",children:s("email.email_encryption.ssl")}),e.jsx(q,{value:"tls",children:s("email.email_encryption.tls")})]})]}),e.jsx(z,{children:s("email.email_encryption.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"email_username",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_username.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...g,value:g.value||""})}),e.jsx(z,{children:s("email.email_username.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"email_password",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_password.title")}),e.jsx(N,{children:e.jsx(T,{type:"password",placeholder:s("common.placeholder"),...g,value:g.value||""})}),e.jsx(z,{children:s("email.email_password.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"email_from_address",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_from.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...g,value:g.value||""})}),e.jsx(z,{children:s("email.email_from.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"email_template",render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("email.email_template.title")}),e.jsxs(J,{onValueChange:j=>{g.onChange(j),p(x.getValues())},value:g.value||void 0,children:[e.jsx(N,{children:e.jsx(W,{className:"w-[200px]",children:e.jsx(Z,{placeholder:s("email.email_template.placeholder")})})}),e.jsx(Y,{children:d?.data?.map(j=>e.jsx(q,{value:j,children:j},j))})]}),e.jsx(z,{children:s("email.email_template.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"remind_mail_enable",render:({field:g})=>e.jsxs(v,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:s("email.remind_mail.title")}),e.jsx(z,{children:s("email.remind_mail.description")})]}),e.jsx(N,{children:e.jsx(Q,{checked:g.value||!1,onCheckedChange:j=>{g.onChange(j),p(x.getValues())}})})]})}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(D,{onClick:()=>w(),loading:P,disabled:P,children:s(P?"test.sending":"test.title")})})]})}),o&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("saving")}),n&&e.jsx(tm,{open:r,onOpenChange:l,result:n})]})}function rm(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("email.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("email.description")})]}),e.jsx(Se,{}),e.jsx(nm,{})]})}const lm=Object.freeze(Object.defineProperty({__proto__:null,default:rm},Symbol.toStringTag,{value:"Module"})),im=h.object({telegram_bot_enable:h.boolean().nullable(),telegram_bot_token:h.string().nullable(),telegram_discuss_link:h.string().nullable()}),om={telegram_bot_enable:!1,telegram_bot_token:"",telegram_discuss_link:""};function cm(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),l=fe({resolver:ye(im),defaultValues:om,mode:"onBlur"}),{data:c}=ie({queryKey:["settings","telegram"],queryFn:()=>fs("telegram")}),{mutateAsync:o}=Ze({mutationFn:gs,onSuccess:f=>{f.data&&A.success(s("common.autoSaved"))}}),{mutate:u,isPending:x}=Ze({mutationFn:bd,onSuccess:f=>{f.data&&A.success(s("telegram.webhook.success"))}});m.useEffect(()=>{if(c?.data.telegram){const f=c.data.telegram;Object.entries(f).forEach(([w,P])=>{l.setValue(w,P)}),r.current=f}},[c]);const i=m.useCallback(Ce.debounce(async f=>{if(!Ce.isEqual(f,r.current)){a(!0);try{await o(f),r.current=f}finally{a(!1)}}},1e3),[o]),d=m.useCallback(f=>{i(f)},[i]);return m.useEffect(()=>{const f=l.watch(w=>{d(w)});return()=>f.unsubscribe()},[l.watch,d]),e.jsx(Ne,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:l.control,name:"telegram_bot_token",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("telegram.bot_token.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("telegram.bot_token.placeholder"),...f,value:f.value||""})}),e.jsx(z,{children:s("telegram.bot_token.description")}),e.jsx(k,{})]})}),l.watch("telegram_bot_token")&&e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("telegram.webhook.title")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(D,{loading:x,disabled:x,onClick:()=>u(),children:s(x?"telegram.webhook.setting":"telegram.webhook.button")}),n&&e.jsx("span",{className:"text-sm text-muted-foreground",children:s("common.saving")})]}),e.jsx(z,{children:s("telegram.webhook.description")}),e.jsx(k,{})]}),e.jsx(b,{control:l.control,name:"telegram_bot_enable",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("telegram.bot_enable.title")}),e.jsx(z,{children:s("telegram.bot_enable.description")}),e.jsx(N,{children:e.jsx(Q,{checked:f.value||!1,onCheckedChange:w=>{f.onChange(w),d(l.getValues())}})}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"telegram_discuss_link",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("telegram.discuss_link.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("telegram.discuss_link.placeholder"),...f,value:f.value||""})}),e.jsx(z,{children:s("telegram.discuss_link.description")}),e.jsx(k,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function dm(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("telegram.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("telegram.description")})]}),e.jsx(Se,{}),e.jsx(cm,{})]})}const um=Object.freeze(Object.defineProperty({__proto__:null,default:dm},Symbol.toStringTag,{value:"Module"})),mm=h.object({windows_version:h.string().nullable(),windows_download_url:h.string().nullable(),macos_version:h.string().nullable(),macos_download_url:h.string().nullable(),android_version:h.string().nullable(),android_download_url:h.string().nullable()}),xm={windows_version:"",windows_download_url:"",macos_version:"",macos_download_url:"",android_version:"",android_download_url:""};function hm(){const{t:s}=M("settings"),[n,a]=m.useState(!1),r=m.useRef(null),l=fe({resolver:ye(mm),defaultValues:xm,mode:"onBlur"}),{data:c}=ie({queryKey:["settings","app"],queryFn:()=>fs("app")}),{mutateAsync:o}=Ze({mutationFn:gs,onSuccess:i=>{i.data&&A.success(s("app.save_success"))}});m.useEffect(()=>{if(c?.data.app){const i=c.data.app;Object.entries(i).forEach(([d,f])=>{l.setValue(d,f)}),r.current=i}},[c]);const u=m.useCallback(Ce.debounce(async i=>{if(!Ce.isEqual(i,r.current)){a(!0);try{await o(i),r.current=i}finally{a(!1)}}},1e3),[o]),x=m.useCallback(i=>{u(i)},[u]);return m.useEffect(()=>{const i=l.watch(d=>{x(d)});return()=>i.unsubscribe()},[l.watch,x]),e.jsx(Ne,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:l.control,name:"windows_version",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("app.windows.version.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("app.windows.version.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"windows_download_url",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("app.windows.download.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("app.windows.download.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"macos_version",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("app.macos.version.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("app.macos.version.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"macos_download_url",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("app.macos.download.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("app.macos.download.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"android_version",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("app.android.version.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("app.android.version.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"android_download_url",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{className:"text-base",children:s("app.android.download.title")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("common.placeholder"),...i,value:i.value||""})}),e.jsx(z,{children:s("app.android.download.description")}),e.jsx(k,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function pm(){const{t:s}=M("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("app.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("app.description")})]}),e.jsx(Se,{}),e.jsx(hm,{})]})}const fm=Object.freeze(Object.defineProperty({__proto__:null,default:pm},Symbol.toStringTag,{value:"Module"})),Va=m.forwardRef(({className:s,...n},a)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:a,className:_("w-full caption-bottom text-sm",s),...n})}));Va.displayName="Table";const Ma=m.forwardRef(({className:s,...n},a)=>e.jsx("thead",{ref:a,className:_("[&_tr]:border-b",s),...n}));Ma.displayName="TableHeader";const Fa=m.forwardRef(({className:s,...n},a)=>e.jsx("tbody",{ref:a,className:_("[&_tr:last-child]:border-0",s),...n}));Fa.displayName="TableBody";const gm=m.forwardRef(({className:s,...n},a)=>e.jsx("tfoot",{ref:a,className:_("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...n}));gm.displayName="TableFooter";const Rs=m.forwardRef(({className:s,...n},a)=>e.jsx("tr",{ref:a,className:_("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",s),...n}));Rs.displayName="TableRow";const Oa=m.forwardRef(({className:s,...n},a)=>e.jsx("th",{ref:a,className:_("h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",s),...n}));Oa.displayName="TableHead";const Js=m.forwardRef(({className:s,...n},a)=>e.jsx("td",{ref:a,className:_("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",s),...n}));Js.displayName="TableCell";const jm=m.forwardRef(({className:s,...n},a)=>e.jsx("caption",{ref:a,className:_("mt-4 text-sm text-muted-foreground",s),...n}));jm.displayName="TableCaption";function vm({table:s}){const[n,a]=m.useState(""),{t:r}=M("common");m.useEffect(()=>{a((s.getState().pagination.pageIndex+1).toString())},[s.getState().pagination.pageIndex]);const l=c=>{const o=parseInt(c);!isNaN(o)&&o>=1&&o<=s.getPageCount()?s.setPageIndex(o-1):a((s.getState().pagination.pageIndex+1).toString())};return e.jsxs("div",{className:"flex flex-col-reverse gap-4 px-2 py-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:r("table.pagination.selected",{selected:s.getFilteredSelectedRowModel().rows.length,total:s.getFilteredRowModel().rows.length})}),e.jsxs("div",{className:"flex flex-col-reverse items-center gap-4 sm:flex-row sm:gap-6 lg:gap-8",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("p",{className:"text-sm font-medium",children:r("table.pagination.itemsPerPage")}),e.jsxs(J,{value:`${s.getState().pagination.pageSize}`,onValueChange:c=>{s.setPageSize(Number(c))},children:[e.jsx(W,{className:"h-8 w-[70px]",children:e.jsx(Z,{placeholder:s.getState().pagination.pageSize})}),e.jsx(Y,{side:"top",children:[10,20,30,40,50,100,500].map(c=>e.jsx(q,{value:`${c}`,children:c},c))})]})]}),e.jsxs("div",{className:"flex items-center justify-center space-x-2 text-sm font-medium",children:[e.jsx("span",{children:r("table.pagination.page")}),e.jsx(T,{type:"text",value:n,onChange:c=>a(c.target.value),onBlur:c=>l(c.target.value),onKeyDown:c=>{c.key==="Enter"&&l(c.currentTarget.value)},className:"h-8 w-[50px] text-center"}),e.jsx("span",{children:r("table.pagination.pageOf",{total:s.getPageCount()})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs(D,{variant:"outline",className:"hidden h-8 w-8 p-0 lg:flex",onClick:()=>s.setPageIndex(0),disabled:!s.getCanPreviousPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.firstPage")}),e.jsx(yo,{className:"h-4 w-4"})]}),e.jsxs(D,{variant:"outline",className:"h-8 w-8 p-0",onClick:()=>s.previousPage(),disabled:!s.getCanPreviousPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.previousPage")}),e.jsx(Xn,{className:"h-4 w-4"})]}),e.jsxs(D,{variant:"outline",className:"h-8 w-8 p-0",onClick:()=>s.nextPage(),disabled:!s.getCanNextPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.nextPage")}),e.jsx(ka,{className:"h-4 w-4"})]}),e.jsxs(D,{variant:"outline",className:"hidden h-8 w-8 p-0 lg:flex",onClick:()=>s.setPageIndex(s.getPageCount()-1),disabled:!s.getCanNextPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.lastPage")}),e.jsx(No,{className:"h-4 w-4"})]})]})]})]})}function xs({table:s,toolbar:n,draggable:a=!1,onDragStart:r,onDragEnd:l,onDragOver:c,onDragLeave:o,onDrop:u,showPagination:x=!0,isLoading:i=!1}){const{t:d}=M("common"),f=m.useRef(null),w=s.getAllColumns().filter(g=>g.getIsPinned()==="left"),P=s.getAllColumns().filter(g=>g.getIsPinned()==="right"),C=g=>w.slice(0,g).reduce((j,S)=>j+(S.getSize()??0),0),p=g=>P.slice(g+1).reduce((j,S)=>j+(S.getSize()??0),0);return e.jsxs("div",{className:"space-y-4",children:[typeof n=="function"?n(s):n,e.jsx("div",{ref:f,className:"relative overflow-auto rounded-md border bg-card",children:e.jsx("div",{className:"overflow-auto",children:e.jsxs(Va,{children:[e.jsx(Ma,{children:s.getHeaderGroups().map(g=>e.jsx(Rs,{className:"hover:bg-transparent",children:g.headers.map((j,S)=>{const R=j.column.getIsPinned()==="left",E=j.column.getIsPinned()==="right",F=R?C(w.indexOf(j.column)):void 0,H=E?p(P.indexOf(j.column)):void 0;return e.jsx(Oa,{colSpan:j.colSpan,style:{width:j.getSize(),...R&&{left:F},...E&&{right:H}},className:_("h-11 bg-card px-4 text-muted-foreground",(R||E)&&["sticky z-20","before:absolute before:bottom-0 before:top-0 before:w-[1px] before:bg-border",R&&"before:right-0",E&&"before:left-0"]),children:j.isPlaceholder?null:Vt(j.column.columnDef.header,j.getContext())},j.id)})},g.id))}),e.jsx(Fa,{children:s.getRowModel().rows?.length?s.getRowModel().rows.map((g,j)=>e.jsx(Rs,{"data-state":g.getIsSelected()&&"selected",className:"hover:bg-muted/50",draggable:a,onDragStart:S=>r?.(S,j),onDragEnd:l,onDragOver:c,onDragLeave:o,onDrop:S=>u?.(S,j),children:g.getVisibleCells().map((S,R)=>{const E=S.column.getIsPinned()==="left",F=S.column.getIsPinned()==="right",H=E?C(w.indexOf(S.column)):void 0,te=F?p(P.indexOf(S.column)):void 0;return e.jsx(Js,{style:{width:S.column.getSize(),...E&&{left:H},...F&&{right:te}},className:_("bg-card",(E||F)&&["sticky z-20","before:absolute before:bottom-0 before:top-0 before:w-[1px] before:bg-border",E&&"before:right-0",F&&"before:left-0"]),children:Vt(S.column.columnDef.cell,S.getContext())},S.id)})},g.id)):e.jsx(Rs,{children:e.jsx(Js,{colSpan:s.getAllColumns().length,className:"h-24 text-center",children:d("table.noData")})})})]})})}),x&&e.jsx(vm,{table:s})]})}const bm=s=>h.object({id:h.number().nullable(),name:h.string().min(2,s("form.validation.name.min")).max(30,s("form.validation.name.max")),icon:h.string().optional().nullable(),notify_domain:h.string().refine(a=>!a||/^https?:\/\/\S+/.test(a),s("form.validation.notify_domain.url")).optional().nullable(),handling_fee_fixed:h.coerce.number().min(0).optional().nullable(),handling_fee_percent:h.coerce.number().min(0).max(100).optional().nullable(),payment:h.string().min(1,s("form.validation.payment.required")),config:h.record(h.string(),h.string())}),on={id:null,name:"",icon:"",notify_domain:"",handling_fee_fixed:0,handling_fee_percent:0,payment:"",config:{}};function Ur({refetch:s,dialogTrigger:n,type:a="add",defaultFormValues:r=on}){const{t:l}=M("payment"),[c,o]=m.useState(!1),[u,x]=m.useState(!1),[i,d]=m.useState([]),[f,w]=m.useState([]),P=bm(l),C=fe({resolver:ye(P),defaultValues:r,mode:"onChange"}),p=C.watch("payment");m.useEffect(()=>{c&&(async()=>{const{data:S}=await Oc();d(S)})()},[c]),m.useEffect(()=>{if(!p||!c)return;(async()=>{const S={payment:p,...a==="edit"&&{id:Number(C.getValues("id"))}};zc(S).then(({data:R})=>{w(R);const E=R.reduce((F,H)=>(H.field_name&&(F[H.field_name]=H.value??""),F),{});C.setValue("config",E)})})()},[p,c,C,a]);const g=async j=>{x(!0);try{(await Lc(j)).data&&(A.success(l("form.messages.success")),C.reset(on),s(),o(!1))}finally{x(!1)}};return e.jsxs(ve,{open:c,onOpenChange:o,children:[e.jsx(Ye,{asChild:!0,children:n||e.jsxs(D,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Re,{icon:"ion:add"})," ",e.jsx("div",{children:l("form.add.button")})]})}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsx(we,{children:e.jsx(be,{children:l(a==="add"?"form.add.title":"form.edit.title")})}),e.jsx(Ne,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(g),className:"space-y-4",children:[e.jsx(b,{control:C.control,name:"name",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:l("form.fields.name.placeholder"),...j})}),e.jsx(z,{children:l("form.fields.name.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"icon",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.icon.label")}),e.jsx(N,{children:e.jsx(T,{...j,value:j.value||"",placeholder:l("form.fields.icon.placeholder")})}),e.jsx(z,{children:l("form.fields.icon.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"notify_domain",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.notify_domain.label")}),e.jsx(N,{children:e.jsx(T,{...j,value:j.value||"",placeholder:l("form.fields.notify_domain.placeholder")})}),e.jsx(z,{children:l("form.fields.notify_domain.description")}),e.jsx(k,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(b,{control:C.control,name:"handling_fee_percent",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.handling_fee_percent.label")}),e.jsx(N,{children:e.jsx(T,{type:"number",...j,value:j.value||"",placeholder:l("form.fields.handling_fee_percent.placeholder")})}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"handling_fee_fixed",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.handling_fee_fixed.label")}),e.jsx(N,{children:e.jsx(T,{type:"number",...j,value:j.value||"",placeholder:l("form.fields.handling_fee_fixed.placeholder")})}),e.jsx(k,{})]})})]}),e.jsx(b,{control:C.control,name:"payment",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.payment.label")}),e.jsxs(J,{onValueChange:j.onChange,defaultValue:j.value,children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:l("form.fields.payment.placeholder")})})}),e.jsx(Y,{children:i.map(S=>e.jsx(q,{value:S,children:S},S))})]}),e.jsx(z,{children:l("form.fields.payment.description")}),e.jsx(k,{})]})}),f.length>0&&e.jsx("div",{className:"space-y-4",children:f.map(j=>e.jsx(b,{control:C.control,name:`config.${j.field_name}`,render:({field:S})=>e.jsxs(v,{children:[e.jsx(y,{children:j.label}),e.jsx(N,{children:e.jsx(T,{...S,value:S.value||""})}),e.jsx(k,{})]})},j.field_name))}),e.jsxs(Oe,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(D,{type:"button",variant:"outline",children:l("form.buttons.cancel")})}),e.jsx(D,{type:"submit",disabled:u,children:l("form.buttons.submit")})]})]})})]})]})}function L({column:s,title:n,tooltip:a,className:r}){return s.getCanSort()?e.jsx("div",{className:"flex items-center gap-1",children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(D,{variant:"ghost",size:"default",className:_("-ml-3 flex h-8 items-center gap-2 text-nowrap font-medium hover:bg-muted/60",r),onClick:()=>s.toggleSorting(s.getIsSorted()==="asc"),children:[e.jsx("span",{children:n}),a&&e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(Qa,{className:"h-4 w-4 cursor-pointer text-muted-foreground"})}),e.jsx(ce,{children:a})]})}),s.getIsSorted()==="asc"?e.jsx(fa,{className:"h-4 w-4 text-foreground/70"}):s.getIsSorted()==="desc"?e.jsx(ga,{className:"h-4 w-4 text-foreground/70"}):e.jsx(_o,{className:"h-4 w-4 text-muted-foreground/70 transition-colors hover:text-foreground/70"})]})})}):e.jsxs("div",{className:_("flex items-center space-x-1 text-nowrap py-2 font-medium text-muted-foreground",r),children:[e.jsx("span",{children:n}),a&&e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{children:e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(ce,{children:a})]})})]})}const za=wo,Kr=Co,ym=So,Br=m.forwardRef(({className:s,...n},a)=>e.jsx(rr,{className:_("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...n,ref:a}));Br.displayName=rr.displayName;const Qt=m.forwardRef(({className:s,...n},a)=>e.jsxs(ym,{children:[e.jsx(Br,{}),e.jsx(lr,{ref:a,className:_("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...n})]}));Qt.displayName=lr.displayName;const Jt=({className:s,...n})=>e.jsx("div",{className:_("flex flex-col space-y-2 text-center sm:text-left",s),...n});Jt.displayName="AlertDialogHeader";const Zt=({className:s,...n})=>e.jsx("div",{className:_("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...n});Zt.displayName="AlertDialogFooter";const Xt=m.forwardRef(({className:s,...n},a)=>e.jsx(ir,{ref:a,className:_("text-lg font-semibold",s),...n}));Xt.displayName=ir.displayName;const ea=m.forwardRef(({className:s,...n},a)=>e.jsx(or,{ref:a,className:_("text-sm text-muted-foreground",s),...n}));ea.displayName=or.displayName;const sa=m.forwardRef(({className:s,...n},a)=>e.jsx(cr,{ref:a,className:_(Xs(),s),...n}));sa.displayName=cr.displayName;const ta=m.forwardRef(({className:s,...n},a)=>e.jsx(dr,{ref:a,className:_(Xs({variant:"outline"}),"mt-2 sm:mt-0",s),...n}));ta.displayName=dr.displayName;function We({onConfirm:s,children:n,title:a="确认操作",description:r="确定要执行此操作吗?",cancelText:l="取消",confirmText:c="确认",variant:o="default",className:u}){return e.jsxs(za,{children:[e.jsx(Kr,{asChild:!0,children:n}),e.jsxs(Qt,{className:_("sm:max-w-[425px]",u),children:[e.jsxs(Jt,{children:[e.jsx(Xt,{children:a}),e.jsx(ea,{children:r})]}),e.jsxs(Zt,{children:[e.jsx(ta,{asChild:!0,children:e.jsx(D,{variant:"outline",children:l})}),e.jsx(sa,{asChild:!0,children:e.jsx(D,{variant:o,onClick:s,children:c})})]})]})]})}const Gr=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M11.29 15.29a2 2 0 0 0-.12.15a.8.8 0 0 0-.09.18a.6.6 0 0 0-.06.18a1.4 1.4 0 0 0 0 .2a.84.84 0 0 0 .08.38a.9.9 0 0 0 .54.54a.94.94 0 0 0 .76 0a.9.9 0 0 0 .54-.54A1 1 0 0 0 13 16a1 1 0 0 0-.29-.71a1 1 0 0 0-1.42 0M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2m0 18a8 8 0 1 1 8-8a8 8 0 0 1-8 8m0-13a3 3 0 0 0-2.6 1.5a1 1 0 1 0 1.73 1A1 1 0 0 1 12 9a1 1 0 0 1 0 2a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-.18A3 3 0 0 0 12 7"})}),Nm=({refetch:s,isSortMode:n=!1})=>{const{t:a}=M("payment");return[{id:"drag-handle",header:()=>null,cell:()=>e.jsx("div",{className:n?"cursor-move":"opacity-0",children:e.jsx(Kt,{className:"size-4"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:r})=>e.jsx(L,{column:r,title:a("table.columns.id")}),cell:({row:r})=>e.jsx(K,{variant:"outline",children:r.getValue("id")}),enableSorting:!0,size:60},{accessorKey:"enable",header:({column:r})=>e.jsx(L,{column:r,title:a("table.columns.enable")}),cell:({row:r})=>e.jsx(Q,{defaultChecked:r.getValue("enable"),onCheckedChange:async()=>{const{data:l}=await $c({id:r.original.id});l||s()}}),enableSorting:!1,size:100},{accessorKey:"name",header:({column:r})=>e.jsx(L,{column:r,title:a("table.columns.name")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{className:"max-w-[200px] truncate font-medium",children:r.getValue("name")})}),enableSorting:!1,size:200},{accessorKey:"payment",header:({column:r})=>e.jsx(L,{column:r,title:a("table.columns.payment")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{className:"max-w-[200px] truncate font-medium",children:r.getValue("payment")})}),enableSorting:!1,size:200},{accessorKey:"notify_url",header:({column:r})=>e.jsxs("div",{className:"flex items-center",children:[e.jsx(L,{column:r,title:a("table.columns.notify_url")}),e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{className:"ml-1",children:e.jsx(Gr,{className:"h-4 w-4"})}),e.jsx(ce,{children:a("table.columns.notify_url_tooltip")})]})})]}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{className:"max-w-[300px] truncate font-medium",children:r.getValue("notify_url")})}),enableSorting:!1,size:3e3},{id:"actions",header:({column:r})=>e.jsx(L,{className:"justify-end",column:r,title:a("table.columns.actions")}),cell:({row:r})=>e.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[e.jsx(Ur,{refetch:s,dialogTrigger:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:a("table.actions.edit")})]}),type:"edit",defaultFormValues:r.original}),e.jsx(We,{title:a("table.actions.delete.title"),description:a("table.actions.delete.description"),onConfirm:async()=>{const{data:l}=await Ac({id:r.original.id});l&&s()},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-destructive/10",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-destructive"}),e.jsx("span",{className:"sr-only",children:a("table.actions.delete.title")})]})})]}),size:100}]};function _m({table:s,refetch:n,saveOrder:a,isSortMode:r}){const{t:l}=M("payment"),c=s.getState().columnFilters.length>0;return e.jsxs("div",{className:"flex items-center justify-between",children:[r?e.jsx("p",{className:"text-sm text-muted-foreground",children:l("table.toolbar.sort.hint")}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ur,{refetch:n}),e.jsx(T,{placeholder:l("table.toolbar.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:o=>s.getColumn("name")?.setFilterValue(o.target.value),className:"h-8 w-[250px]"}),c&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),children:[l("table.toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(D,{variant:r?"default":"outline",onClick:a,size:"sm",children:l(r?"table.toolbar.sort.save":"table.toolbar.sort.edit")})})]})}function wm(){const[s,n]=m.useState([]),[a,r]=m.useState([]),[l,c]=m.useState(!1),[o,u]=m.useState([]),[x,i]=m.useState({"drag-handle":!1}),[d,f]=m.useState({pageSize:20,pageIndex:0}),{refetch:w}=ie({queryKey:["paymentList"],queryFn:async()=>{const{data:j}=await Fc();return u(j?.map(S=>({...S,enable:!!S.enable}))||[]),j}});m.useEffect(()=>{i({"drag-handle":l,actions:!l}),f({pageSize:l?99999:10,pageIndex:0})},[l]);const P=(j,S)=>{l&&(j.dataTransfer.setData("text/plain",S.toString()),j.currentTarget.classList.add("opacity-50"))},C=(j,S)=>{if(!l)return;j.preventDefault(),j.currentTarget.classList.remove("bg-muted");const R=parseInt(j.dataTransfer.getData("text/plain"));if(R===S)return;const E=[...o],[F]=E.splice(R,1);E.splice(S,0,F),u(E)},p=async()=>{l?qc({ids:o.map(j=>j.id)}).then(()=>{w(),c(!1),A.success("排序保存成功")}):c(!0)},g=ts({data:o,columns:Nm({refetch:w,isSortMode:l}),state:{sorting:a,columnFilters:s,columnVisibility:x,pagination:d},onSortingChange:r,onColumnFiltersChange:n,onColumnVisibilityChange:i,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),initialState:{columnPinning:{right:["actions"]}},pageCount:l?1:void 0});return e.jsx(xs,{table:g,toolbar:j=>e.jsx(_m,{table:j,refetch:w,saveOrder:p,isSortMode:l}),draggable:l,onDragStart:P,onDragEnd:j=>j.currentTarget.classList.remove("opacity-50"),onDragOver:j=>{j.preventDefault(),j.currentTarget.classList.add("bg-muted")},onDragLeave:j=>j.currentTarget.classList.remove("bg-muted"),onDrop:C,showPagination:!l})}function Cm(){const{t:s}=M("payment");return e.jsxs(Pe,{children:[e.jsxs(Ee,{className:"flex items-center justify-between",children:[e.jsx(qe,{}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{children:[e.jsx("header",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("div",{className:"mb-2",children:e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")})}),e.jsx("p",{className:"text-muted-foreground",children:s("description")})]})}),e.jsx("section",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(wm,{})})]})]})}const Sm=Object.freeze(Object.defineProperty({__proto__:null,default:Cm},Symbol.toStringTag,{value:"Module"}));function km({pluginName:s,onClose:n,onSuccess:a}){const{t:r}=M("plugin"),[l,c]=m.useState(!0),[o,u]=m.useState(!1),[x,i]=m.useState(null),d=ko({config:To(Do())}),f=fe({resolver:ye(d),defaultValues:{config:{}}});m.useEffect(()=>{(async()=>{try{const{data:p}=await ys.getPluginConfig(s);i(p),f.reset({config:Object.fromEntries(Object.entries(p).map(([g,j])=>[g,j.value]))})}catch{A.error(r("messages.configLoadError"))}finally{c(!1)}})()},[s]);const w=async C=>{u(!0);try{await ys.updatePluginConfig(s,C.config),A.success(r("messages.configSaveSuccess")),a()}catch{A.error(r("messages.configSaveError"))}finally{u(!1)}},P=(C,p)=>{switch(p.type){case"string":return e.jsx(b,{control:f.control,name:`config.${C}`,render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{children:p.label||p.description}),e.jsx(N,{children:e.jsx(T,{placeholder:p.placeholder,...g})}),p.description&&p.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description}),e.jsx(k,{})]})},C);case"number":case"percentage":return e.jsx(b,{control:f.control,name:`config.${C}`,render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{children:p.label||p.description}),e.jsx(N,{children:e.jsxs("div",{className:"relative",children:[e.jsx(T,{type:"number",placeholder:p.placeholder,...g,onChange:j=>{const S=Number(j.target.value);p.type==="percentage"?g.onChange(Math.min(100,Math.max(0,S))):g.onChange(S)},className:p.type==="percentage"?"pr-8":"",min:p.type==="percentage"?0:void 0,max:p.type==="percentage"?100:void 0,step:p.type==="percentage"?1:void 0}),p.type==="percentage"&&e.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3",children:e.jsx(Po,{className:"h-4 w-4 text-muted-foreground"})})]})}),p.description&&p.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description}),e.jsx(k,{})]})},C);case"select":return e.jsx(b,{control:f.control,name:`config.${C}`,render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{children:p.label||p.description}),e.jsxs(J,{onValueChange:g.onChange,defaultValue:g.value,children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:p.placeholder})})}),e.jsx(Y,{children:p.options?.map(j=>e.jsx(q,{value:j.value,children:j.label},j.value))})]}),p.description&&p.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description}),e.jsx(k,{})]})},C);case"boolean":return e.jsx(b,{control:f.control,name:`config.${C}`,render:({field:g})=>e.jsxs(v,{className:"flex flex-row items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(y,{className:"text-base",children:p.label||p.description}),p.description&&p.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description})]}),e.jsx(N,{children:e.jsx(Q,{checked:g.value,onCheckedChange:g.onChange})})]})},C);case"text":return e.jsx(b,{control:f.control,name:`config.${C}`,render:({field:g})=>e.jsxs(v,{children:[e.jsx(y,{children:p.label||p.description}),e.jsx(N,{children:e.jsx(bs,{placeholder:p.placeholder,...g})}),p.description&&p.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description}),e.jsx(k,{})]})},C);default:return null}};return l?e.jsxs("div",{className:"space-y-4",children:[e.jsx(oe,{className:"h-4 w-[200px]"}),e.jsx(oe,{className:"h-10 w-full"}),e.jsx(oe,{className:"h-4 w-[200px]"}),e.jsx(oe,{className:"h-10 w-full"})]}):e.jsx(Ne,{...f,children:e.jsxs("form",{onSubmit:f.handleSubmit(w),className:"space-y-4",children:[x&&Object.entries(x).map(([C,p])=>P(C,p)),e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(D,{type:"button",variant:"outline",onClick:n,disabled:o,children:r("config.cancel")}),e.jsx(D,{type:"submit",loading:o,disabled:o,children:r("config.save")})]})]})})}function Tm(){const{t:s}=M("plugin"),[n,a]=m.useState(null),[r,l]=m.useState(!1),[c,o]=m.useState(null),[u,x]=m.useState(""),[i,d]=m.useState("all"),[f,w]=m.useState(!1),[P,C]=m.useState(!1),[p,g]=m.useState(!1),j=m.useRef(null),{data:S,isLoading:R,refetch:E}=ie({queryKey:["pluginList"],queryFn:async()=>{const{data:I}=await ys.getPluginList();return I}});S&&[...new Set(S.map(I=>I.category||"other"))];const F=S?.filter(I=>{const B=I.name.toLowerCase().includes(u.toLowerCase())||I.description.toLowerCase().includes(u.toLowerCase())||I.code.toLowerCase().includes(u.toLowerCase()),ne=i==="all"||I.category===i;return B&&ne}),H=async I=>{a(I),ys.installPlugin(I).then(()=>{A.success(s("messages.installSuccess")),E()}).catch(B=>{A.error(B.message||s("messages.installError"))}).finally(()=>{a(null)})},te=async I=>{a(I),ys.uninstallPlugin(I).then(()=>{A.success(s("messages.uninstallSuccess")),E()}).catch(B=>{A.error(B.message||s("messages.uninstallError"))}).finally(()=>{a(null)})},O=async(I,B)=>{a(I),(B?ys.disablePlugin:ys.enablePlugin)(I).then(()=>{A.success(s(B?"messages.disableSuccess":"messages.enableSuccess")),E()}).catch(Qe=>{A.error(Qe.message||s(B?"messages.disableError":"messages.enableError"))}).finally(()=>{a(null)})},se=I=>{S?.find(B=>B.code===I),o(I),l(!0)},He=async I=>{if(!I.name.endsWith(".zip")){A.error(s("upload.error.format"));return}w(!0),ys.uploadPlugin(I).then(()=>{A.success(s("messages.uploadSuccess")),C(!1),E()}).catch(B=>{A.error(B.message||s("messages.uploadError"))}).finally(()=>{w(!1),j.current&&(j.current.value="")})},G=I=>{I.preventDefault(),I.stopPropagation(),I.type==="dragenter"||I.type==="dragover"?g(!0):I.type==="dragleave"&&g(!1)},ae=I=>{I.preventDefault(),I.stopPropagation(),g(!1),I.dataTransfer.files&&I.dataTransfer.files[0]&&He(I.dataTransfer.files[0])},$=async I=>{a(I),ys.deletePlugin(I).then(()=>{A.success(s("messages.deleteSuccess")),E()}).catch(B=>{A.error(B.message||s("messages.deleteError"))}).finally(()=>{a(null)})};return e.jsxs(Pe,{children:[e.jsxs(Ee,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(Ta,{className:"h-6 w-6"}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:s("title")})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{children:[e.jsxs("div",{className:"mb-8 space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(An,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(T,{placeholder:s("search.placeholder"),value:u,onChange:I=>x(I.target.value),className:"pl-9"})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(D,{onClick:()=>C(!0),variant:"outline",className:"shrink-0",size:"sm",children:[e.jsx(pt,{className:"mr-2 h-4 w-4"}),s("upload.button")]})})]}),e.jsxs(Wt,{defaultValue:"all",className:"w-full",children:[e.jsxs(bt,{children:[e.jsx(Ke,{value:"all",children:s("tabs.all")}),e.jsx(Ke,{value:"installed",children:s("tabs.installed")}),e.jsx(Ke,{value:"available",children:s("tabs.available")})]}),e.jsx(Ns,{value:"all",className:"mt-6",children:e.jsx("div",{className:"space-y-4",children:R?e.jsxs(e.Fragment,{children:[e.jsx(ca,{}),e.jsx(ca,{}),e.jsx(ca,{})]}):F?.map(I=>e.jsx(oa,{plugin:I,onInstall:H,onUninstall:te,onToggleEnable:O,onOpenConfig:se,onDelete:$,isLoading:n===I.name},I.name))})}),e.jsx(Ns,{value:"installed",className:"mt-6",children:e.jsx("div",{className:"space-y-4",children:F?.filter(I=>I.is_installed).map(I=>e.jsx(oa,{plugin:I,onInstall:H,onUninstall:te,onToggleEnable:O,onOpenConfig:se,onDelete:$,isLoading:n===I.name},I.name))})}),e.jsx(Ns,{value:"available",className:"mt-6",children:e.jsx("div",{className:"space-y-4",children:F?.filter(I=>!I.is_installed).map(I=>e.jsx(oa,{plugin:I,onInstall:H,onUninstall:te,onToggleEnable:O,onOpenConfig:se,onDelete:$,isLoading:n===I.name},I.code))})})]})]}),e.jsx(ve,{open:r,onOpenChange:l,children:e.jsxs(pe,{className:"sm:max-w-lg",children:[e.jsxs(we,{children:[e.jsxs(be,{children:[S?.find(I=>I.code===c)?.name," ",s("config.title")]}),e.jsx(ke,{children:s("config.description")})]}),c&&e.jsx(km,{pluginName:c,onClose:()=>l(!1),onSuccess:()=>{l(!1),E()}})]})}),e.jsx(ve,{open:P,onOpenChange:C,children:e.jsxs(pe,{className:"sm:max-w-md",children:[e.jsxs(we,{children:[e.jsx(be,{children:s("upload.title")}),e.jsx(ke,{children:s("upload.description")})]}),e.jsxs("div",{className:_("relative mt-4 flex h-64 flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 px-5 py-10 text-center transition-colors",p&&"border-primary/50 bg-muted/50"),onDragEnter:G,onDragLeave:G,onDragOver:G,onDrop:ae,children:[e.jsx("input",{type:"file",ref:j,className:"hidden",accept:".zip",onChange:I=>{const B=I.target.files?.[0];B&&He(B)}}),f?e.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-b-2 border-primary"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s("upload.uploading")})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[e.jsx("div",{className:"rounded-full border-2 border-muted-foreground/25 p-3",children:e.jsx(pt,{className:"h-6 w-6 text-muted-foreground/50"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[s("upload.dragText")," ",e.jsx("button",{type:"button",onClick:()=>j.current?.click(),className:"mx-1 text-primary hover:underline",children:s("upload.clickText")})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("upload.supportText")})]})]})})]})]})})]})]})}function oa({plugin:s,onInstall:n,onUninstall:a,onToggleEnable:r,onOpenConfig:l,onDelete:c,isLoading:o}){const{t:u}=M("plugin");return e.jsxs(Be,{className:"group relative overflow-hidden transition-all hover:shadow-md",children:[e.jsxs(es,{children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{children:s.name}),s.is_installed&&e.jsx(K,{variant:s.is_enabled?"success":"secondary",children:s.is_enabled?u("status.enabled"):u("status.disabled")})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("code",{className:"rounded bg-muted px-1 py-0.5",children:s.code})]}),e.jsxs("div",{children:["v",s.version]})]})]})}),e.jsx(Zs,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"mt-2",children:s.description}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1",children:[u("author"),": ",s.author]})})]})})]}),e.jsx(ss,{children:e.jsx("div",{className:"flex items-center justify-end space-x-2",children:s.is_installed?e.jsxs(e.Fragment,{children:[e.jsxs(D,{variant:"outline",size:"sm",onClick:()=>l(s.code),disabled:!s.is_enabled||o,children:[e.jsx(Eo,{className:"mr-2 h-4 w-4"}),u("button.config")]}),e.jsxs(D,{variant:s.is_enabled?"destructive":"default",size:"sm",onClick:()=>r(s.code,s.is_enabled),disabled:o,children:[e.jsx(Ro,{className:"mr-2 h-4 w-4"}),s.is_enabled?u("button.disable"):u("button.enable")]}),e.jsx(We,{title:u("uninstall.title"),description:u("uninstall.description"),cancelText:u("common:cancel"),confirmText:u("uninstall.button"),variant:"destructive",onConfirm:()=>a(s.code),children:e.jsxs(D,{variant:"outline",size:"sm",className:"text-muted-foreground hover:text-destructive",disabled:o,children:[e.jsx(os,{className:"mr-2 h-4 w-4"}),u("button.uninstall")]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(D,{onClick:()=>n(s.code),disabled:o,loading:o,children:u("button.install")}),e.jsx(We,{title:u("delete.title"),description:u("delete.description"),cancelText:u("common:cancel"),confirmText:u("delete.button"),variant:"destructive",onConfirm:()=>c(s.code),children:e.jsx(D,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",disabled:o,children:e.jsx(os,{className:"h-4 w-4"})})})]})})})]})}function ca(){return e.jsxs(Be,{children:[e.jsxs(es,{children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-6 w-[200px]"}),e.jsx(oe,{className:"h-6 w-[80px]"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(oe,{className:"h-5 w-[120px]"}),e.jsx(oe,{className:"h-5 w-[60px]"})]})]})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(oe,{className:"h-4 w-[300px]"}),e.jsx(oe,{className:"h-4 w-[150px]"})]})]}),e.jsx(ss,{children:e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(oe,{className:"h-9 w-[100px]"}),e.jsx(oe,{className:"h-9 w-[100px]"}),e.jsx(oe,{className:"h-8 w-8"})]})})]})}const Dm=Object.freeze(Object.defineProperty({__proto__:null,default:Tm},Symbol.toStringTag,{value:"Module"})),Pm=(s,n)=>{let a=null;switch(s.field_type){case"input":a=e.jsx(T,{placeholder:s.placeholder,...n});break;case"textarea":a=e.jsx(bs,{placeholder:s.placeholder,...n});break;case"select":a=e.jsx("select",{className:_(Xs({variant:"outline"}),"w-full appearance-none font-normal"),...n,children:s.select_options&&Object.keys(s.select_options).map(r=>e.jsx("option",{value:r,children:s.select_options?.[r]},r))});break;default:a=null;break}return a};function Em({themeKey:s,themeInfo:n}){const{t:a}=M("theme"),[r,l]=m.useState(!1),[c,o]=m.useState(!1),[u,x]=m.useState(!1),i=fe({defaultValues:n.configs.reduce((w,P)=>(w[P.field_name]="",w),{})}),d=async()=>{o(!0),Nc(s).then(({data:w})=>{Object.entries(w).forEach(([P,C])=>{i.setValue(P,C)})}).finally(()=>{o(!1)})},f=async w=>{x(!0),_c(s,w).then(()=>{A.success(a("config.success")),l(!1)}).finally(()=>{x(!1)})};return e.jsxs(ve,{open:r,onOpenChange:w=>{l(w),w?d():i.reset()},children:[e.jsx(Ye,{asChild:!0,children:e.jsx(D,{variant:"outline",children:a("card.configureTheme")})}),e.jsxs(pe,{className:"max-h-[90vh] overflow-auto sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:a("config.title",{name:n.name})}),e.jsx(ke,{children:a("config.description")})]}),c?e.jsx("div",{className:"flex h-40 items-center justify-center",children:e.jsx(Pa,{className:"h-6 w-6 animate-spin"})}):e.jsx(Ne,{...i,children:e.jsxs("form",{onSubmit:i.handleSubmit(f),className:"space-y-4",children:[n.configs.map(w=>e.jsx(b,{control:i.control,name:w.field_name,render:({field:P})=>e.jsxs(v,{children:[e.jsx(y,{children:w.label}),e.jsx(N,{children:Pm(w,P)}),e.jsx(k,{})]})},w.field_name)),e.jsxs(Oe,{className:"mt-6 gap-2",children:[e.jsx(D,{type:"button",variant:"secondary",onClick:()=>l(!1),children:a("config.cancel")}),e.jsx(D,{type:"submit",loading:u,children:a("config.save")})]})]})})]})]})}function Rm(){const{t:s}=M("theme"),[n,a]=m.useState(null),[r,l]=m.useState(!1),[c,o]=m.useState(!1),[u,x]=m.useState(!1),[i,d]=m.useState(null),f=m.useRef(null),[w,P]=m.useState(0),{data:C,isLoading:p,refetch:g}=ie({queryKey:["themeList"],queryFn:async()=>{const{data:O}=await yc();return O}}),j=async O=>{a(O),Sc({frontend_theme:O}).then(()=>{A.success("主题切换成功"),g()}).finally(()=>{a(null)})},S=async O=>{if(!O.name.endsWith(".zip")){A.error(s("upload.error.format"));return}l(!0),wc(O).then(()=>{A.success("主题上传成功"),o(!1),g()}).finally(()=>{l(!1),f.current&&(f.current.value="")})},R=O=>{O.preventDefault(),O.stopPropagation(),O.type==="dragenter"||O.type==="dragover"?x(!0):O.type==="dragleave"&&x(!1)},E=O=>{O.preventDefault(),O.stopPropagation(),x(!1),O.dataTransfer.files&&O.dataTransfer.files[0]&&S(O.dataTransfer.files[0])},F=()=>{i&&P(O=>O===0?i.images.length-1:O-1)},H=()=>{i&&P(O=>O===i.images.length-1?0:O+1)},te=(O,se)=>{P(0),d({name:O,images:se})};return e.jsxs(Pe,{children:[e.jsxs(Ee,{className:"flex items-center justify-between",children:[e.jsx(qe,{}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"",children:[e.jsxs("header",{className:"mb-8",children:[e.jsx("div",{className:"mb-2",children:e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:s("title")})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-muted-foreground",children:s("description")}),e.jsxs(D,{onClick:()=>o(!0),variant:"outline",className:"ml-4 shrink-0",size:"sm",children:[e.jsx(pt,{className:"mr-2 h-4 w-4"}),s("upload.button")]})]})]}),e.jsx("section",{className:"grid gap-6 md:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3",children:p?e.jsxs(e.Fragment,{children:[e.jsx(cn,{}),e.jsx(cn,{})]}):C?.themes&&Object.entries(C.themes).map(([O,se])=>e.jsx(Be,{className:"group relative overflow-hidden transition-all hover:shadow-md",style:{backgroundImage:se.background_url?`url(${se.background_url})`:"none",backgroundSize:"cover",backgroundPosition:"center"},children:e.jsxs("div",{className:_("relative z-10 h-full transition-colors",se.background_url?"group-hover:from-background/98 bg-gradient-to-t from-background/95 via-background/80 to-background/60 backdrop-blur-[1px] group-hover:via-background/90 group-hover:to-background/70":"bg-background"),children:[!!se.can_delete&&e.jsx("div",{className:"absolute right-2 top-2",children:e.jsx(We,{title:s("card.delete.title"),description:s("card.delete.description"),confirmText:s("card.delete.button"),variant:"destructive",onConfirm:async()=>{if(O===C?.active){A.error(s("card.delete.error.active"));return}a(O),Cc(O).then(()=>{A.success("主题删除成功"),g()}).finally(()=>{a(null)})},children:e.jsx(D,{disabled:n===O,loading:n===O,variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",children:e.jsx(os,{className:"h-4 w-4"})})})}),e.jsxs(es,{children:[e.jsx(ws,{children:se.name}),e.jsx(Zs,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{children:se.description}),se.version&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("card.version",{version:se.version})})]})})]}),e.jsxs(ss,{className:"flex items-center justify-end space-x-3",children:[se.images&&Array.isArray(se.images)&&se.images.length>0&&e.jsx(D,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>te(se.name,se.images),children:e.jsx(Io,{className:"h-4 w-4"})}),e.jsx(Em,{themeKey:O,themeInfo:se}),e.jsx(D,{onClick:()=>j(O),disabled:n===O||O===C.active,loading:n===O,variant:O===C.active?"secondary":"default",children:O===C.active?s("card.currentTheme"):s("card.activateTheme")})]})]})},O))}),e.jsx(ve,{open:c,onOpenChange:o,children:e.jsxs(pe,{className:"sm:max-w-md",children:[e.jsxs(we,{children:[e.jsx(be,{children:s("upload.title")}),e.jsx(ke,{children:s("upload.description")})]}),e.jsxs("div",{className:_("relative mt-4 flex h-64 flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 px-5 py-10 text-center transition-colors",u&&"border-primary/50 bg-muted/50"),onDragEnter:R,onDragLeave:R,onDragOver:R,onDrop:E,children:[e.jsx("input",{type:"file",ref:f,className:"hidden",accept:".zip",onChange:O=>{const se=O.target.files?.[0];se&&S(se)}}),r?e.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-b-2 border-primary"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s("upload.uploading")})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[e.jsx("div",{className:"rounded-full border-2 border-muted-foreground/25 p-3",children:e.jsx(pt,{className:"h-6 w-6 text-muted-foreground/50"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[s("upload.dragText")," ",e.jsx("button",{type:"button",onClick:()=>f.current?.click(),className:"mx-1 text-primary hover:underline",children:s("upload.clickText")})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("upload.supportText")})]})]})})]})]})}),e.jsx(ve,{open:!!i,onOpenChange:O=>{O||(d(null),P(0))},children:e.jsxs(pe,{className:"max-w-4xl",children:[e.jsxs(we,{children:[e.jsxs(be,{children:[i?.name," ",s("preview.title")]}),e.jsx(ke,{className:"text-center",children:i&&s("preview.imageCount",{current:w+1,total:i.images.length})})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[16/9] overflow-hidden rounded-lg border bg-muted",children:i?.images[w]&&e.jsx("img",{src:i.images[w],alt:`${i.name} 预览图 ${w+1}`,className:"h-full w-full object-contain"})}),i&&i.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(D,{variant:"outline",size:"icon",className:"absolute left-4 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full bg-background/80 hover:bg-background",onClick:F,children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsx(D,{variant:"outline",size:"icon",className:"absolute right-4 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full bg-background/80 hover:bg-background",onClick:H,children:e.jsx(Mo,{className:"h-4 w-4"})})]})]}),i&&i.images.length>1&&e.jsx("div",{className:"mt-4 flex gap-2 overflow-x-auto pb-2",children:i.images.map((O,se)=>e.jsx("button",{onClick:()=>P(se),className:_("relative h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border-2",w===se?"border-primary":"border-transparent"),children:e.jsx("img",{src:O,alt:`缩略图 ${se+1}`,className:"h-full w-full object-cover"})},se))})]})})]})]})}function cn(){return e.jsxs(Be,{children:[e.jsxs(es,{children:[e.jsx(oe,{className:"h-6 w-[200px]"}),e.jsx(oe,{className:"h-4 w-[300px]"})]}),e.jsxs(ss,{className:"flex items-center justify-end space-x-3",children:[e.jsx(oe,{className:"h-10 w-[100px]"}),e.jsx(oe,{className:"h-10 w-[100px]"})]})]})}const Im=Object.freeze(Object.defineProperty({__proto__:null,default:Rm},Symbol.toStringTag,{value:"Module"})),La=m.forwardRef(({className:s,value:n,onChange:a,...r},l)=>{const[c,o]=m.useState("");m.useEffect(()=>{if(c.includes(",")){const x=new Set([...n,...c.split(",").map(i=>i.trim())]);a(Array.from(x)),o("")}},[c,a,n]);const u=()=>{if(c){const x=new Set([...n,c]);a(Array.from(x)),o("")}};return e.jsxs("div",{className:_(" has-[:focus-visible]:outline-none has-[:focus-visible]:ring-1 has-[:focus-visible]:ring-neutral-950 dark:has-[:focus-visible]:ring-neutral-300 flex w-full flex-wrap gap-2 rounded-md border border-input shadow-sm px-3 py-2 text-sm ring-offset-white disabled:cursor-not-allowed disabled:opacity-50",s),children:[n.map(x=>e.jsxs(K,{variant:"secondary",children:[x,e.jsx(X,{variant:"ghost",size:"icon",className:"ml-2 h-3 w-3",onClick:()=>{a(n.filter(i=>i!==x))},children:e.jsx(ja,{className:"w-3"})})]},x)),e.jsx("input",{className:"flex-1 outline-none placeholder:text-muted-foreground bg-transparent",value:c,onChange:x=>o(x.target.value),onKeyDown:x=>{x.key==="Enter"||x.key===","?(x.preventDefault(),u()):x.key==="Backspace"&&c.length===0&&n.length>0&&(x.preventDefault(),a(n.slice(0,-1)))},...r,ref:l})]})});La.displayName="InputTags";const Vm=h.object({id:h.number().nullable(),title:h.string().min(1).max(250),content:h.string().min(1),show:h.boolean(),tags:h.array(h.string()),img_url:h.string().nullable()}),Mm={id:null,show:!1,tags:[],img_url:"",title:"",content:""};function Wr({refetch:s,dialogTrigger:n,type:a="add",defaultFormValues:r=Mm}){const{t:l}=M("notice"),[c,o]=m.useState(!1),u=fe({resolver:ye(Vm),defaultValues:r,mode:"onChange",shouldFocusError:!0}),x=new Ea({html:!0});return e.jsx(Ne,{...u,children:e.jsxs(ve,{onOpenChange:o,open:c,children:[e.jsx(Ye,{asChild:!0,children:n||e.jsxs(D,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Re,{icon:"ion:add"})," ",e.jsx("div",{children:l("form.add.button")})]})}),e.jsxs(pe,{className:"sm:max-w-[1025px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:l(a==="add"?"form.add.title":"form.edit.title")}),e.jsx(ke,{})]}),e.jsx(b,{control:u.control,name:"title",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.title.label")}),e.jsx("div",{className:"relative ",children:e.jsx(N,{children:e.jsx(T,{placeholder:l("form.fields.title.placeholder"),...i})})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"content",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.content.label")}),e.jsx(N,{children:e.jsx(Ra,{style:{height:"500px"},value:i.value,renderHTML:d=>x.render(d),onChange:({text:d})=>{i.onChange(d)}})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"img_url",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.img_url.label")}),e.jsx("div",{className:"relative",children:e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:l("form.fields.img_url.placeholder"),...i,value:i.value||""})})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"show",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.show.label")}),e.jsx("div",{className:"relative py-2",children:e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:i.onChange})})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"tags",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.fields.tags.label")}),e.jsx(N,{children:e.jsx(La,{value:i.value,onChange:i.onChange,placeholder:l("form.fields.tags.placeholder"),className:"w-full"})}),e.jsx(k,{})]})}),e.jsxs(Oe,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(D,{type:"button",variant:"outline",children:l("form.buttons.cancel")})}),e.jsx(D,{type:"submit",onClick:i=>{i.preventDefault(),u.handleSubmit(async d=>{Hc(d).then(({data:f})=>{f&&(A.success(l("form.buttons.success")),s(),o(!1))})})()},children:l("form.buttons.submit")})]})]})]})})}function Fm({table:s,refetch:n,saveOrder:a,isSortMode:r}){const{t:l}=M("notice"),c=s.getState().columnFilters.length>0;return e.jsxs("div",{className:"flex items-center justify-between space-x-2 ",children:[e.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[!r&&e.jsx(Wr,{refetch:n}),!r&&e.jsx(T,{placeholder:l("table.toolbar.search"),value:s.getColumn("title")?.getFilterValue()??"",onChange:o=>s.getColumn("title")?.setFilterValue(o.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),c&&!r&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-9 px-2 lg:px-3",children:[l("table.toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(D,{variant:r?"default":"outline",onClick:a,className:"h-8",size:"sm",children:l(r?"table.toolbar.sort.save":"table.toolbar.sort.edit")})})]})}const Om=s=>{const{t:n}=M("notice");return[{id:"drag-handle",header:"",cell:()=>e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground cursor-move"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.id")}),cell:({row:a})=>e.jsx(K,{variant:"outline",className:"font-mono",children:a.getValue("id")}),enableSorting:!0,size:60},{accessorKey:"show",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.show")}),cell:({row:a})=>e.jsx("div",{className:"flex items-center",children:e.jsx(Q,{defaultChecked:a.getValue("show"),onCheckedChange:async()=>{const{data:r}=await Kc({id:a.original.id});r||s()}})}),enableSorting:!1,size:100},{accessorKey:"title",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.title")}),cell:({row:a})=>e.jsx("div",{className:"flex max-w-[500px] items-center",children:e.jsx("span",{className:"truncate font-medium",children:a.getValue("title")})}),enableSorting:!1,size:6e3},{id:"actions",header:({column:a})=>e.jsx(L,{className:"justify-end",column:a,title:n("table.columns.actions")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[e.jsx(Wr,{refetch:s,dialogTrigger:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("table.actions.edit")})]}),type:"edit",defaultFormValues:a.original}),e.jsx(We,{title:n("table.actions.delete.title"),description:n("table.actions.delete.description"),onConfirm:async()=>{Uc({id:a.original.id}).then(()=>{A.success(n("table.actions.delete.success")),s()})},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("table.actions.delete.title")})]})})]}),size:100}]};function zm(){const[s,n]=m.useState({}),[a,r]=m.useState({}),[l,c]=m.useState([]),[o,u]=m.useState([]),[x,i]=m.useState(!1),[d,f]=m.useState({}),[w,P]=m.useState({pageSize:50,pageIndex:0}),[C,p]=m.useState([]),{refetch:g}=ie({queryKey:["notices"],queryFn:async()=>{const{data:F}=await nn.getList();return p(F),F}});m.useEffect(()=>{r({"drag-handle":x,content:!x,created_at:!x,actions:!x}),P({pageSize:x?99999:50,pageIndex:0})},[x]);const j=(F,H)=>{x&&(F.dataTransfer.setData("text/plain",H.toString()),F.currentTarget.classList.add("opacity-50"))},S=(F,H)=>{if(!x)return;F.preventDefault(),F.currentTarget.classList.remove("bg-muted");const te=parseInt(F.dataTransfer.getData("text/plain"));if(te===H)return;const O=[...C],[se]=O.splice(te,1);O.splice(H,0,se),p(O)},R=async()=>{if(!x){i(!0);return}nn.sort(C.map(F=>F.id)).then(()=>{A.success("排序保存成功"),i(!1),g()}).finally(()=>{i(!1)})},E=ts({data:C??[],columns:Om(g),state:{sorting:o,columnVisibility:a,rowSelection:s,columnFilters:l,columnSizing:d,pagination:w},enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:u,onColumnFiltersChange:c,onColumnVisibilityChange:r,onColumnSizingChange:f,onPaginationChange:P,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx("div",{className:"space-y-4",children:e.jsx(xs,{table:E,toolbar:F=>e.jsx(Fm,{table:F,refetch:g,saveOrder:R,isSortMode:x}),draggable:x,onDragStart:j,onDragEnd:F=>F.currentTarget.classList.remove("opacity-50"),onDragOver:F=>{F.preventDefault(),F.currentTarget.classList.add("bg-muted")},onDragLeave:F=>F.currentTarget.classList.remove("bg-muted"),onDrop:S,showPagination:!x})})}function Lm(){const{t:s}=M("notice");return e.jsxs(Pe,{children:[e.jsxs(Ee,{className:"flex items-center justify-between",children:[e.jsx(qe,{}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("div",{className:"mb-2",children:e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")})}),e.jsx("p",{className:"text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(zm,{})})]})]})}const Am=Object.freeze(Object.defineProperty({__proto__:null,default:Lm},Symbol.toStringTag,{value:"Module"})),$m=h.object({id:h.number().nullable(),language:h.string().max(250),category:h.string().max(250),title:h.string().min(1).max(250),body:h.string().min(1),show:h.boolean()}),qm={id:null,language:"zh-CN",category:"",title:"",body:"",show:!1};function Yr({refreshData:s,dialogTrigger:n,type:a="add",defaultFormValues:r=qm}){const{t:l}=M("knowledge"),[c,o]=m.useState(!1),u=fe({resolver:ye($m),defaultValues:r,mode:"onChange",shouldFocusError:!0}),x=new Ea({html:!0});return m.useEffect(()=>{c&&r.id&&Gc(r.id).then(({data:i})=>{u.reset(i)})},[r.id,u,c]),e.jsxs(ve,{onOpenChange:o,open:c,children:[e.jsx(Ye,{asChild:!0,children:n||e.jsxs(D,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Re,{icon:"ion:add"})," ",e.jsx("div",{children:l("form.add")})]})}),e.jsxs(pe,{className:"sm:max-w-[1025px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:l(a==="add"?"form.add":"form.edit")}),e.jsx(ke,{})]}),e.jsxs(Ne,{...u,children:[e.jsx(b,{control:u.control,name:"title",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.title")}),e.jsx("div",{className:"relative ",children:e.jsx(N,{children:e.jsx(T,{placeholder:l("form.titlePlaceholder"),...i})})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"category",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.category")}),e.jsx("div",{className:"relative ",children:e.jsx(N,{children:e.jsx(T,{placeholder:l("form.categoryPlaceholder"),...i})})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"language",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.language")}),e.jsx(N,{children:e.jsxs(J,{value:i.value,onValueChange:i.onChange,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:l("form.languagePlaceholder")})}),e.jsx(Y,{children:[{value:"en-US"},{value:"ja-JP"},{value:"ko-KR"},{value:"vi-VN"},{value:"zh-CN"},{value:"zh-TW"}].map(d=>e.jsx(q,{value:d.value,className:"cursor-pointer",children:l(`languages.${d.value}`)},d.value))})]})})]})}),e.jsx(b,{control:u.control,name:"body",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.content")}),e.jsx(N,{children:e.jsx(Ra,{style:{height:"500px"},value:i.value,renderHTML:d=>x.render(d),onChange:({text:d})=>{i.onChange(d)}})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"show",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.show")}),e.jsx("div",{className:"relative py-2",children:e.jsx(N,{children:e.jsx(Q,{checked:i.value,onCheckedChange:i.onChange})})}),e.jsx(k,{})]})}),e.jsxs(Oe,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(D,{type:"button",variant:"outline",children:l("form.cancel")})}),e.jsx(D,{type:"submit",onClick:()=>{u.handleSubmit(i=>{Wc(i).then(({data:d})=>{d&&(u.reset(),A.success(l("messages.operationSuccess")),o(!1),s())})})()},children:l("form.submit")})]})]})]})]})}function Hm({column:s,title:n,options:a}){const r=s?.getFacetedUniqueValues(),l=new Set(s?.getFilterValue());return e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(vt,{className:"mr-2 h-4 w-4"}),n,l?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:l.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:l.size>2?e.jsxs(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[l.size," selected"]}):a.filter(c=>l.has(c.value)).map(c=>e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:c.label},c.value))})]})]})}),e.jsx(ms,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Vs,{children:[e.jsx(Us,{placeholder:n}),e.jsxs(Ms,{children:[e.jsx(Ks,{children:"No results found."}),e.jsx(Ge,{children:a.map(c=>{const o=l.has(c.value);return e.jsxs(Ie,{onSelect:()=>{o?l.delete(c.value):l.add(c.value);const u=Array.from(l);s?.setFilterValue(u.length?u:void 0)},children:[e.jsx("div",{className:_("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",o?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(As,{className:_("h-4 w-4")})}),c.icon&&e.jsx(c.icon,{className:"mr-2 h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:c.label}),r?.get(c.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(c.value)})]},c.value)})}),l.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(at,{}),e.jsx(Ge,{children:e.jsx(Ie,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}function Um({table:s,refetch:n,saveOrder:a,isSortMode:r}){const l=s.getState().columnFilters.length>0,{t:c}=M("knowledge");return e.jsxs("div",{className:"flex items-center justify-between",children:[r?e.jsx("p",{className:"text-sm text-muted-foreground",children:c("toolbar.sortModeHint")}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yr,{refreshData:n}),e.jsx(T,{placeholder:c("toolbar.searchPlaceholder"),value:s.getColumn("title")?.getFilterValue()??"",onChange:o=>s.getColumn("title")?.setFilterValue(o.target.value),className:"h-8 w-[250px]"}),s.getColumn("category")&&e.jsx(Hm,{column:s.getColumn("category"),title:c("columns.category"),options:Array.from(new Set(s.getCoreRowModel().rows.map(o=>o.getValue("category")))).map(o=>({label:o,value:o}))}),l&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),children:[c("toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(D,{variant:r?"default":"outline",onClick:a,size:"sm",children:c(r?"toolbar.saveSort":"toolbar.editSort")})})]})}const Km=({refetch:s,isSortMode:n=!1})=>{const{t:a}=M("knowledge");return[{id:"drag-handle",header:()=>null,cell:()=>e.jsx("div",{className:n?"cursor-move":"opacity-0",children:e.jsx(Kt,{className:"size-4"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.id")}),cell:({row:r})=>e.jsx(K,{variant:"outline",className:"justify-center",children:r.getValue("id")}),enableSorting:!0,size:70},{accessorKey:"show",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.status")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx(Q,{defaultChecked:r.getValue("show"),onCheckedChange:async()=>{Qc({id:r.original.id}).then(({data:l})=>{l||s()})}})}),enableSorting:!1,size:100},{accessorKey:"title",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.title")}),cell:({row:r})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"line-clamp-2 font-medium",children:r.getValue("title")})}),enableSorting:!0,size:600},{accessorKey:"category",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.category")}),cell:({row:r})=>e.jsx(K,{variant:"secondary",className:"max-w-[180px] truncate",children:r.getValue("category")}),enableSorting:!0,size:1800},{id:"actions",header:({column:r})=>e.jsx(L,{className:"justify-end",column:r,title:a("columns.actions")}),cell:({row:r})=>e.jsxs("div",{className:"flex items-center justify-end space-x-1",children:[e.jsx(Yr,{refreshData:s,dialogTrigger:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:a("form.edit")})]}),type:"edit",defaultFormValues:r.original}),e.jsx(We,{title:a("messages.deleteConfirm"),description:a("messages.deleteDescription"),confirmText:a("messages.deleteButton"),variant:"destructive",onConfirm:async()=>{Yc({id:r.original.id}).then(({data:l})=>{l&&(A.success(a("messages.operationSuccess")),s())})},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:a("messages.deleteButton")})]})})]}),size:100}]};function Bm(){const[s,n]=m.useState([]),[a,r]=m.useState([]),[l,c]=m.useState(!1),[o,u]=m.useState([]),[x,i]=m.useState({"drag-handle":!1}),[d,f]=m.useState({pageSize:20,pageIndex:0}),{refetch:w,isLoading:P,data:C}=ie({queryKey:["knowledge"],queryFn:async()=>{const{data:R}=await Bc();return u(R||[]),R}});m.useEffect(()=>{i({"drag-handle":l,actions:!l}),f({pageSize:l?99999:10,pageIndex:0})},[l]);const p=(R,E)=>{l&&(R.dataTransfer.setData("text/plain",E.toString()),R.currentTarget.classList.add("opacity-50"))},g=(R,E)=>{if(!l)return;R.preventDefault(),R.currentTarget.classList.remove("bg-muted");const F=parseInt(R.dataTransfer.getData("text/plain"));if(F===E)return;const H=[...o],[te]=H.splice(F,1);H.splice(E,0,te),u(H)},j=async()=>{l?Jc({ids:o.map(R=>R.id)}).then(()=>{w(),c(!1),A.success("排序保存成功")}):c(!0)},S=ts({data:o,columns:Km({refetch:w,isSortMode:l}),state:{sorting:a,columnFilters:s,columnVisibility:x,pagination:d},onSortingChange:r,onColumnFiltersChange:n,onColumnVisibilityChange:i,onPaginationChange:f,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(xs,{table:S,toolbar:R=>e.jsx(Um,{table:R,refetch:w,saveOrder:j,isSortMode:l}),draggable:l,onDragStart:p,onDragEnd:R=>R.currentTarget.classList.remove("opacity-50"),onDragOver:R=>{R.preventDefault(),R.currentTarget.classList.add("bg-muted")},onDragLeave:R=>R.currentTarget.classList.remove("bg-muted"),onDrop:g,showPagination:!l})}function Gm(){const{t:s}=M("knowledge");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight mb-2",children:s("title")}),e.jsx("p",{className:"text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Bm,{})})]})]})}const Wm=Object.freeze(Object.defineProperty({__proto__:null,default:Gm},Symbol.toStringTag,{value:"Module"}));function Ym(s,n){const[a,r]=m.useState(s);return m.useEffect(()=>{const l=setTimeout(()=>r(s),n);return()=>{clearTimeout(l)}},[s,n]),a}function da(s,n){if(s.length===0)return{};if(!n)return{"":s};const a={};return s.forEach(r=>{const l=r[n]||"";a[l]||(a[l]=[]),a[l].push(r)}),a}function Qm(s,n){const a=JSON.parse(JSON.stringify(s));for(const[r,l]of Object.entries(a))a[r]=l.filter(c=>!n.find(o=>o.value===c.value));return a}function Jm(s,n){for(const[,a]of Object.entries(s))if(a.some(r=>n.find(l=>l.value===r.value)))return!0;return!1}const Qr=m.forwardRef(({className:s,...n},a)=>Oo(l=>l.filtered.count===0)?e.jsx("div",{ref:a,className:_("py-6 text-center text-sm",s),"cmdk-empty":"",role:"presentation",...n}):null);Qr.displayName="CommandEmpty";const st=m.forwardRef(({value:s,onChange:n,placeholder:a,defaultOptions:r=[],options:l,delay:c,onSearch:o,loadingIndicator:u,emptyIndicator:x,maxSelected:i=Number.MAX_SAFE_INTEGER,onMaxSelected:d,hidePlaceholderWhenSelected:f,disabled:w,groupBy:P,className:C,badgeClassName:p,selectFirstItem:g=!0,creatable:j=!1,triggerSearchOnFocus:S=!1,commandProps:R,inputProps:E,hideClearAllButton:F=!1},H)=>{const te=m.useRef(null),[O,se]=m.useState(!1),He=m.useRef(!1),[G,ae]=m.useState(!1),[$,I]=m.useState(s||[]),[B,ne]=m.useState(da(r,P)),[Qe,nt]=m.useState(""),rt=Ym(Qe,c||500);m.useImperativeHandle(H,()=>({selectedValue:[...$],input:te.current,focus:()=>te.current?.focus()}),[$]);const _t=m.useCallback(ee=>{const de=$.filter(Ae=>Ae.value!==ee.value);I(de),n?.(de)},[n,$]),bl=m.useCallback(ee=>{const de=te.current;de&&((ee.key==="Delete"||ee.key==="Backspace")&&de.value===""&&$.length>0&&($[$.length-1].fixed||_t($[$.length-1])),ee.key==="Escape"&&de.blur())},[_t,$]);m.useEffect(()=>{s&&I(s)},[s]),m.useEffect(()=>{if(!l||o)return;const ee=da(l||[],P);JSON.stringify(ee)!==JSON.stringify(B)&&ne(ee)},[r,l,P,o,B]),m.useEffect(()=>{const ee=async()=>{ae(!0);const Ae=await o?.(rt);ne(da(Ae||[],P)),ae(!1)};(async()=>{!o||!O||(S&&await ee(),rt&&await ee())})()},[rt,P,O,S]);const yl=()=>{if(!j||Jm(B,[{value:Qe,label:Qe}])||$.find(de=>de.value===Qe))return;const ee=e.jsx(Ie,{value:Qe,className:"cursor-pointer",onMouseDown:de=>{de.preventDefault(),de.stopPropagation()},onSelect:de=>{if($.length>=i){d?.($.length);return}nt("");const Ae=[...$,{value:de,label:de}];I(Ae),n?.(Ae)},children:`Create "${Qe}"`});if(!o&&Qe.length>0||o&&rt.length>0&&!G)return ee},Nl=m.useCallback(()=>{if(x)return o&&!j&&Object.keys(B).length===0?e.jsx(Ie,{value:"-",disabled:!0,children:x}):e.jsx(Qr,{children:x})},[j,x,o,B]),_l=m.useMemo(()=>Qm(B,$),[B,$]),wl=m.useCallback(()=>{if(R?.filter)return R.filter;if(j)return(ee,de)=>ee.toLowerCase().includes(de.toLowerCase())?1:-1},[j,R?.filter]),Cl=m.useCallback(()=>{const ee=$.filter(de=>de.fixed);I(ee),n?.(ee)},[n,$]);return e.jsxs(Vs,{...R,onKeyDown:ee=>{bl(ee),R?.onKeyDown?.(ee)},className:_("h-auto overflow-visible bg-transparent",R?.className),shouldFilter:R?.shouldFilter!==void 0?R.shouldFilter:!o,filter:wl(),children:[e.jsx("div",{className:_("rounded-md border border-input text-sm ring-offset-background focus-within:ring-1 focus-within:ring-ring ",{"px-3 py-2":$.length!==0,"cursor-text":!w&&$.length!==0},C),onClick:()=>{w||te.current?.focus()},children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[$.map(ee=>e.jsxs(K,{className:_("data-[disabled]:bg-muted-foreground data-[disabled]:text-muted data-[disabled]:hover:bg-muted-foreground","data-[fixed]:bg-muted-foreground data-[fixed]:text-muted data-[fixed]:hover:bg-muted-foreground",p),"data-fixed":ee.fixed,"data-disabled":w||void 0,children:[ee.label,e.jsx("button",{className:_("ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",(w||ee.fixed)&&"hidden"),onKeyDown:de=>{de.key==="Enter"&&_t(ee)},onMouseDown:de=>{de.preventDefault(),de.stopPropagation()},onClick:()=>_t(ee),children:e.jsx(ja,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},ee.value)),e.jsx(Fe.Input,{...E,ref:te,value:Qe,disabled:w,onValueChange:ee=>{nt(ee),E?.onValueChange?.(ee)},onBlur:ee=>{He.current===!1&&se(!1),E?.onBlur?.(ee)},onFocus:ee=>{se(!0),S&&o?.(rt),E?.onFocus?.(ee)},placeholder:f&&$.length!==0?"":a,className:_("flex-1 bg-transparent outline-none placeholder:text-muted-foreground",{"w-full":f,"px-3 py-2":$.length===0,"ml-1":$.length!==0},E?.className)}),e.jsx("button",{type:"button",onClick:Cl,className:_((F||w||$.length<1||$.filter(ee=>ee.fixed).length===$.length)&&"hidden"),children:e.jsx(ja,{})})]})}),e.jsx("div",{className:"relative",children:O&&e.jsx(Ms,{className:"absolute top-1 z-10 w-full rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in",onMouseLeave:()=>{He.current=!1},onMouseEnter:()=>{He.current=!0},onMouseUp:()=>{te.current?.focus()},children:G?e.jsx(e.Fragment,{children:u}):e.jsxs(e.Fragment,{children:[Nl(),yl(),!g&&e.jsx(Ie,{value:"-",className:"hidden"}),Object.entries(_l).map(([ee,de])=>e.jsx(Ge,{heading:ee,className:"h-full overflow-auto",children:e.jsx(e.Fragment,{children:de.map(Ae=>e.jsx(Ie,{value:Ae.value,disabled:Ae.disable,onMouseDown:lt=>{lt.preventDefault(),lt.stopPropagation()},onSelect:()=>{if($.length>=i){d?.($.length);return}nt("");const lt=[...$,Ae];I(lt),n?.(lt)},className:_("cursor-pointer",Ae.disable&&"cursor-default text-muted-foreground"),children:Ae.label},Ae.value))})},ee))]})})})]})});st.displayName="MultipleSelector";const Zm=s=>h.object({id:h.number().optional(),name:h.string().min(2,s("messages.nameValidation.min")).max(50,s("messages.nameValidation.max")).regex(/^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/,s("messages.nameValidation.pattern"))});function aa({refetch:s,dialogTrigger:n,defaultValues:a={name:""},type:r="add"}){const{t:l}=M("group"),c=fe({resolver:ye(Zm(l)),defaultValues:a,mode:"onChange"}),[o,u]=m.useState(!1),[x,i]=m.useState(!1),d=async f=>{i(!0),Rc(f).then(()=>{A.success(l(r==="edit"?"messages.updateSuccess":"messages.createSuccess")),s&&s(),c.reset(),u(!1)}).finally(()=>{i(!1)})};return e.jsxs(ve,{open:o,onOpenChange:u,children:[e.jsx(Ye,{asChild:!0,children:n||e.jsxs(D,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Re,{icon:"ion:add"}),e.jsx("span",{children:l("form.add")})]})}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:l(r==="edit"?"form.edit":"form.create")}),e.jsx(ke,{children:l(r==="edit"?"form.editDescription":"form.createDescription")})]}),e.jsx(Ne,{...c,children:e.jsxs("form",{onSubmit:c.handleSubmit(d),className:"space-y-4",children:[e.jsx(b,{control:c.control,name:"name",render:({field:f})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.name")}),e.jsx(N,{children:e.jsx(T,{placeholder:l("form.namePlaceholder"),...f,className:"w-full"})}),e.jsx(z,{children:l("form.nameDescription")}),e.jsx(k,{})]})}),e.jsxs(Oe,{className:"gap-2",children:[e.jsx(Nt,{asChild:!0,children:e.jsx(D,{type:"button",variant:"outline",children:l("form.cancel")})}),e.jsxs(D,{type:"submit",disabled:x||!c.formState.isValid,children:[x&&e.jsx(Pa,{className:"mr-2 h-4 w-4 animate-spin"}),l(r==="edit"?"form.update":"form.create")]})]})]})})]})]})}const Jr=m.createContext(void 0);function Xm({children:s,refetch:n}){const[a,r]=m.useState(!1),[l,c]=m.useState(null),[o,u]=m.useState(Te.Shadowsocks);return e.jsx(Jr.Provider,{value:{isOpen:a,setIsOpen:r,editingServer:l,setEditingServer:c,serverType:o,setServerType:u,refetch:n},children:s})}function Zr(){const s=m.useContext(Jr);if(s===void 0)throw new Error("useServerEdit must be used within a ServerEditProvider");return s}function ua({dialogTrigger:s,value:n,setValue:a,templateType:r}){const{t:l}=M("server");m.useEffect(()=>{console.log(n)},[n]);const[c,o]=m.useState(!1),[u,x]=m.useState(()=>{if(!n||Object.keys(n).length===0)return"";try{return JSON.stringify(n,null,2)}catch{return""}}),[i,d]=m.useState(null),f=j=>{if(!j)return null;try{const S=JSON.parse(j);return typeof S!="object"||S===null?l("network_settings.validation.must_be_object"):null}catch{return l("network_settings.validation.invalid_json")}},w={tcp:{label:"TCP",content:{acceptProxyProtocol:!1,header:{type:"none"}}},"tcp-http":{label:"TCP + HTTP",content:{acceptProxyProtocol:!1,header:{type:"http",request:{version:"1.1",method:"GET",path:["/"],headers:{Host:["www.example.com"]}},response:{version:"1.1",status:"200",reason:"OK"}}}},grpc:{label:"gRPC",content:{serviceName:"GunService"}},ws:{label:"WebSocket",content:{path:"/",headers:{Host:"v2ray.com"}}},httpupgrade:{label:"HttpUpgrade",content:{acceptProxyProtocol:!1,path:"/",host:"xray.com",headers:{key:"value"}}},xhttp:{label:"XHTTP",content:{host:"example.com",path:"/yourpath",mode:"auto",extra:{headers:{},xPaddingBytes:"100-1000",noGRPCHeader:!1,noSSEHeader:!1,scMaxEachPostBytes:1e6,scMinPostsIntervalMs:30,scMaxBufferedPosts:30,xmux:{maxConcurrency:"16-32",maxConnections:0,cMaxReuseTimes:"64-128",cMaxLifetimeMs:0,hMaxRequestTimes:"800-900",hKeepAlivePeriod:0},downloadSettings:{address:"",port:443,network:"xhttp",security:"tls",tlsSettings:{},xhttpSettings:{path:"/yourpath"},sockopt:{}}}}}},P=()=>{switch(r){case"tcp":return["tcp","tcp-http"];case"grpc":return["grpc"];case"ws":return["ws"];case"httpupgrade":return["httpupgrade"];case"xhttp":return["xhttp"];default:return[]}},C=()=>{const j=f(u||"");if(j){A.error(j);return}try{if(!u){a(null),o(!1);return}a(JSON.parse(u)),o(!1)}catch{A.error(l("network_settings.errors.save_failed"))}},p=j=>{x(j),d(f(j))},g=j=>{const S=w[j];if(S){const R=JSON.stringify(S.content,null,2);x(R),d(null)}};return m.useEffect(()=>{c&&console.log(n)},[c,n]),m.useEffect(()=>{c&&n&&Object.keys(n).length>0&&x(JSON.stringify(n,null,2))},[c,n]),e.jsxs(ve,{open:c,onOpenChange:j=>{!j&&c&&C(),o(j)},children:[e.jsx(Ye,{asChild:!0,children:s??e.jsx(X,{variant:"link",children:l("network_settings.edit_protocol")})}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsx(we,{children:e.jsx(be,{children:l("network_settings.edit_protocol_config")})}),e.jsxs("div",{className:"space-y-4",children:[P().length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 pt-2",children:P().map(j=>e.jsx(X,{variant:"outline",size:"sm",onClick:()=>g(j),children:l("network_settings.use_template",{template:w[j].label})},j))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(bs,{className:`min-h-[200px] font-mono text-sm ${i?"border-red-500 focus-visible:ring-red-500":""}`,value:u,placeholder:P().length>0?l("network_settings.json_config_placeholder_with_template"):l("network_settings.json_config_placeholder"),onChange:j=>p(j.target.value)}),i&&e.jsx("p",{className:"text-sm text-red-500",children:i})]})]}),e.jsxs(Oe,{className:"gap-2",children:[e.jsx(X,{variant:"outline",onClick:()=>o(!1),children:l("common.cancel")}),e.jsx(X,{onClick:C,disabled:!!i,children:l("common.confirm")})]})]})]})}function up(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}const ex={},sx=Object.freeze(Object.defineProperty({__proto__:null,default:ex},Symbol.toStringTag,{value:"Module"})),mp=Jo(sx),dn=s=>s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),tx=()=>{try{const s=zo.box.keyPair(),n=dn(Ja.encodeBase64(s.secretKey)),a=dn(Ja.encodeBase64(s.publicKey));return{privateKey:n,publicKey:a}}catch(s){throw console.error("Error generating x25519 key pair:",s),s}},ax=()=>{try{return tx()}catch(s){throw console.error("Error generating key pair:",s),s}},nx=s=>{const n=new Uint8Array(Math.ceil(s/2));return window.crypto.getRandomValues(n),Array.from(n).map(a=>a.toString(16).padStart(2,"0")).join("").substring(0,s)},rx=()=>{const s=Math.floor(Math.random()*8)*2+2;return nx(s)},lx=h.object({cipher:h.string().default("aes-128-gcm"),obfs:h.string().default("0"),obfs_settings:h.object({path:h.string().default(""),host:h.string().default("")}).default({})}),ix=h.object({tls:h.coerce.number().default(0),tls_settings:h.object({server_name:h.string().default(""),allow_insecure:h.boolean().default(!1)}).default({}),network:h.string().default("tcp"),network_settings:h.record(h.any()).default({})}),ox=h.object({server_name:h.string().default(""),allow_insecure:h.boolean().default(!1),network:h.string().default("tcp"),network_settings:h.record(h.any()).default({})}),cx=h.object({version:h.coerce.number().default(2),alpn:h.string().default("h2"),obfs:h.object({open:h.coerce.boolean().default(!1),type:h.string().default("salamander"),password:h.string().default("")}).default({}),tls:h.object({server_name:h.string().default(""),allow_insecure:h.boolean().default(!1)}).default({}),bandwidth:h.object({up:h.string().default(""),down:h.string().default("")}).default({})}),dx=h.object({tls:h.coerce.number().default(0),tls_settings:h.object({server_name:h.string().default(""),allow_insecure:h.boolean().default(!1)}).default({}),reality_settings:h.object({server_port:h.coerce.number().default(443),server_name:h.string().default(""),allow_insecure:h.boolean().default(!1),public_key:h.string().default(""),private_key:h.string().default(""),short_id:h.string().default("")}).default({}),network:h.string().default("tcp"),network_settings:h.record(h.any()).default({}),flow:h.string().default("")}),ux=h.object({version:h.coerce.number().default(5),congestion_control:h.string().default("bbr"),alpn:h.array(h.string()).default(["h3"]),udp_relay_mode:h.string().default("native"),tls:h.object({server_name:h.string().default(""),allow_insecure:h.boolean().default(!1)}).default({})}),$e={shadowsocks:{schema:lx,ciphers:["aes-128-gcm","aes-192-gcm","aes-256-gcm","chacha20-ietf-poly1305","2022-blake3-aes-128-gcm","2022-blake3-aes-256-gcm"]},vmess:{schema:ix,networkOptions:[{value:"tcp",label:"TCP"},{value:"ws",label:"Websocket"},{value:"grpc",label:"gRPC"}]},trojan:{schema:ox,networkOptions:[{value:"tcp",label:"TCP"},{value:"ws",label:"Websocket"},{value:"grpc",label:"gRPC"}]},hysteria:{schema:cx,versions:["1","2"],alpnOptions:["hysteria","http/1.1","h2","h3"]},vless:{schema:dx,networkOptions:[{value:"tcp",label:"TCP"},{value:"ws",label:"Websocket"},{value:"grpc",label:"gRPC"},{value:"kcp",label:"mKCP"},{value:"httpupgrade",label:"HttpUpgrade"},{value:"xhttp",label:"XHTTP"}],flowOptions:["none","xtls-rprx-direct","xtls-rprx-splice","xtls-rprx-vision"]},tuic:{schema:ux,versions:["5","4"],congestionControls:["bbr","cubic","new_reno"],alpnOptions:[{value:"h3",label:"HTTP/3"},{value:"h2",label:"HTTP/2"},{value:"http/1.1",label:"HTTP/1.1"}],udpRelayModes:[{value:"native",label:"Native"},{value:"quic",label:"QUIC"}]}},mx=({serverType:s,value:n,onChange:a})=>{const{t:r}=M("server"),l=s?$e[s]:null,c=l?.schema||h.record(h.any()),o=s?c.parse({}):{},u=fe({resolver:ye(c),defaultValues:o,mode:"onChange"});if(m.useEffect(()=>{if(!n||Object.keys(n).length===0){if(s){const p=c.parse({});u.reset(p)}}else u.reset(n)},[s,n,a,u,c]),m.useEffect(()=>{const p=u.watch(g=>{a(g)});return()=>p.unsubscribe()},[u,a]),!s||!l)return null;const C={shadowsocks:()=>e.jsxs(e.Fragment,{children:[e.jsx(b,{control:u.control,name:"cipher",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.shadowsocks.cipher.label")}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.shadowsocks.cipher.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.shadowsocks.ciphers.map(g=>e.jsx(q,{value:g,children:g},g))})})]})})]})}),e.jsx(b,{control:u.control,name:"obfs",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.shadowsocks.obfs.label")}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.shadowsocks.obfs.placeholder")})}),e.jsx(Y,{children:e.jsxs(ns,{children:[e.jsx(q,{value:"0",children:r("dynamic_form.shadowsocks.obfs.none")}),e.jsx(q,{value:"http",children:r("dynamic_form.shadowsocks.obfs.http")})]})})]})})]})}),u.watch("obfs")==="http"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"obfs_settings.path",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:r("dynamic_form.shadowsocks.obfs_settings.path"),...p})}),e.jsx(k,{})]})}),e.jsx(b,{control:u.control,name:"obfs_settings.host",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:r("dynamic_form.shadowsocks.obfs_settings.host"),...p})}),e.jsx(k,{})]})})]})]}),vmess:()=>e.jsxs(e.Fragment,{children:[e.jsx(b,{control:u.control,name:"tls",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vmess.tls.label")}),e.jsx(N,{children:e.jsxs(J,{value:p.value?.toString(),onValueChange:g=>p.onChange(Number(g)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.vmess.tls.placeholder")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:r("dynamic_form.vmess.tls.disabled")}),e.jsx(q,{value:"1",children:r("dynamic_form.vmess.tls.enabled")})]})]})})]})}),u.watch("tls")==1&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"tls_settings.server_name",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.vmess.tls_settings.server_name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.vmess.tls_settings.server_name.placeholder"),...p})})]})}),e.jsx(b,{control:u.control,name:"tls_settings.allow_insecure",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vmess.tls_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),e.jsx(b,{control:u.control,name:"network",render:({field:p})=>e.jsxs(v,{children:[e.jsxs(y,{children:[r("dynamic_form.vmess.network.label"),e.jsx(ua,{value:u.watch("network_settings"),setValue:g=>u.setValue("network_settings",g),templateType:u.watch("network")})]}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.vmess.network.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.vmess.networkOptions.map(g=>e.jsx(q,{value:g.value,className:"cursor-pointer",children:g.label},g.value))})})]})})]})})]}),trojan:()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"server_name",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.trojan.server_name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.trojan.server_name.placeholder"),...p,value:p.value||""})})]})}),e.jsx(b,{control:u.control,name:"allow_insecure",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.trojan.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value||!1,onCheckedChange:p.onChange})})})]})})]}),e.jsx(b,{control:u.control,name:"network",render:({field:p})=>e.jsxs(v,{children:[e.jsxs(y,{children:[r("dynamic_form.trojan.network.label"),e.jsx(ua,{value:u.watch("network_settings")||{},setValue:g=>u.setValue("network_settings",g),templateType:u.watch("network")||"tcp"})]}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value||"tcp",children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.trojan.network.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.trojan.networkOptions.map(g=>e.jsx(q,{value:g.value,className:"cursor-pointer",children:g.label},g.value))})})]})})]})})]}),hysteria:()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"version",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:r("dynamic_form.hysteria.version.label")}),e.jsx(N,{children:e.jsxs(J,{value:(p.value||2).toString(),onValueChange:g=>p.onChange(Number(g)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.hysteria.version.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.hysteria.versions.map(g=>e.jsxs(q,{value:g,className:"cursor-pointer",children:["V",g]},g))})})]})})]})}),u.watch("version")==1&&e.jsx(b,{control:u.control,name:"alpn",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.hysteria.alpn.label")}),e.jsx(N,{children:e.jsxs(J,{value:p.value||"h2",onValueChange:p.onChange,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.hysteria.alpn.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.hysteria.alpnOptions.map(g=>e.jsx(q,{value:g,children:g},g))})})]})})]})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"obfs.open",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.hysteria.obfs.label")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value||!1,onCheckedChange:p.onChange})})})]})}),!!u.watch("obfs.open")&&e.jsxs(e.Fragment,{children:[u.watch("version")=="2"&&e.jsx(b,{control:u.control,name:"obfs.type",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:r("dynamic_form.hysteria.obfs.type.label")}),e.jsx(N,{children:e.jsxs(J,{value:p.value||"salamander",onValueChange:p.onChange,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.hysteria.obfs.type.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:e.jsx(q,{value:"salamander",children:r("dynamic_form.hysteria.obfs.type.salamander")})})})]})})]})}),e.jsx(b,{control:u.control,name:"obfs.password",render:({field:p})=>e.jsxs(v,{className:u.watch("version")==2?"w-full":"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.hysteria.obfs.password.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.hysteria.obfs.password.placeholder"),...p,value:p.value||"",className:"pr-9"})}),e.jsx(X,{type:"button",variant:"ghost",size:"icon",onClick:()=>{const g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",j=Array.from(crypto.getRandomValues(new Uint8Array(16))).map(S=>g[S%g.length]).join("");u.setValue("obfs.password",j),A.success(r("dynamic_form.hysteria.obfs.password.generate_success"))},className:"absolute right-0 top-0 h-full px-2 active:scale-90 transition-transform duration-150",children:e.jsx(Re,{icon:"ion:refresh-outline",className:"h-4 w-4 transition-transform hover:rotate-180 duration-300"})})]})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"tls.server_name",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.hysteria.tls.server_name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.hysteria.tls.server_name.placeholder"),...p,value:p.value||""})})]})}),e.jsx(b,{control:u.control,name:"tls.allow_insecure",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.hysteria.tls.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value||!1,onCheckedChange:p.onChange})})})]})})]}),e.jsx(b,{control:u.control,name:"bandwidth.up",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.hysteria.bandwidth.up.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:r("dynamic_form.hysteria.bandwidth.up.placeholder")+(u.watch("version")==2?r("dynamic_form.hysteria.bandwidth.up.bbr_tip"):""),className:"rounded-br-none rounded-tr-none",...p,value:p.value||""})}),e.jsx("div",{className:"pointer-events-none z-[-1] flex items-center rounded-md rounded-bl-none rounded-tl-none border border-l-0 border-input px-3 shadow-sm",children:e.jsx("span",{className:"text-gray-500",children:r("dynamic_form.hysteria.bandwidth.up.suffix")})})]})]})}),e.jsx(b,{control:u.control,name:"bandwidth.down",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.hysteria.bandwidth.down.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:r("dynamic_form.hysteria.bandwidth.down.placeholder")+(u.watch("version")==2?r("dynamic_form.hysteria.bandwidth.down.bbr_tip"):""),className:"rounded-br-none rounded-tr-none",...p,value:p.value||""})}),e.jsx("div",{className:"pointer-events-none z-[-1] flex items-center rounded-md rounded-bl-none rounded-tl-none border border-l-0 border-input px-3 shadow-sm",children:e.jsx("span",{className:"text-gray-500",children:r("dynamic_form.hysteria.bandwidth.down.suffix")})})]})]})})]}),vless:()=>e.jsxs(e.Fragment,{children:[e.jsx(b,{control:u.control,name:"tls",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vless.tls.label")}),e.jsx(N,{children:e.jsxs(J,{value:p.value?.toString(),onValueChange:g=>p.onChange(Number(g)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.vless.tls.placeholder")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:r("dynamic_form.vless.tls.none")}),e.jsx(q,{value:"1",children:r("dynamic_form.vless.tls.tls")}),e.jsx(q,{value:"2",children:r("dynamic_form.vless.tls.reality")})]})]})})]})}),u.watch("tls")=="1"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"tls_settings.server_name",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.vless.tls_settings.server_name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.vless.tls_settings.server_name.placeholder"),...p})})]})}),e.jsx(b,{control:u.control,name:"tls_settings.allow_insecure",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vless.tls_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),u.watch("tls")==2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"reality_settings.server_name",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.vless.reality_settings.server_name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.vless.reality_settings.server_name.placeholder"),...p})})]})}),e.jsx(b,{control:u.control,name:"reality_settings.server_port",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:r("dynamic_form.vless.reality_settings.server_port.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.vless.reality_settings.server_port.placeholder"),...p})})]})}),e.jsx(b,{control:u.control,name:"reality_settings.allow_insecure",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vless.reality_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),e.jsx("div",{className:"flex items-end gap-2",children:e.jsx(b,{control:u.control,name:"reality_settings.private_key",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:r("dynamic_form.vless.reality_settings.private_key.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(N,{children:e.jsx(T,{...p,className:"pr-9"})}),e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(X,{type:"button",variant:"ghost",size:"icon",onClick:()=>{try{const g=ax();u.setValue("reality_settings.private_key",g.privateKey),u.setValue("reality_settings.public_key",g.publicKey),A.success(r("dynamic_form.vless.reality_settings.key_pair.success"))}catch{A.error(r("dynamic_form.vless.reality_settings.key_pair.error"))}},className:"absolute right-0 top-0 h-full px-2 active:scale-90 transition-transform duration-150",children:e.jsx(Re,{icon:"ion:key-outline",className:"h-4 w-4 transition-transform hover:rotate-180 duration-300"})})}),e.jsx(Mt,{children:e.jsx(ce,{children:e.jsx("p",{children:r("dynamic_form.vless.reality_settings.key_pair.generate")})})})]})]})]})})}),e.jsx(b,{control:u.control,name:"reality_settings.public_key",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vless.reality_settings.public_key.label")}),e.jsx(N,{children:e.jsx(T,{...p})})]})}),e.jsx(b,{control:u.control,name:"reality_settings.short_id",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vless.reality_settings.short_id.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(N,{children:e.jsx(T,{...p,className:"pr-9",placeholder:r("dynamic_form.vless.reality_settings.short_id.placeholder")})}),e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(X,{type:"button",variant:"ghost",size:"icon",onClick:()=>{const g=rx();u.setValue("reality_settings.short_id",g),A.success(r("dynamic_form.vless.reality_settings.short_id.success"))},className:"absolute right-0 top-0 h-full px-2 active:scale-90 transition-transform duration-150",children:e.jsx(Re,{icon:"ion:refresh-outline",className:"h-4 w-4 transition-transform hover:rotate-180 duration-300"})})}),e.jsx(Mt,{children:e.jsx(ce,{children:e.jsx("p",{children:r("dynamic_form.vless.reality_settings.short_id.generate")})})})]})]}),e.jsx(z,{className:"text-xs text-muted-foreground",children:r("dynamic_form.vless.reality_settings.short_id.description")})]})})]}),e.jsx(b,{control:u.control,name:"network",render:({field:p})=>e.jsxs(v,{children:[e.jsxs(y,{children:[r("dynamic_form.vless.network.label"),e.jsx(ua,{value:u.watch("network_settings"),setValue:g=>u.setValue("network_settings",g),templateType:u.watch("network")})]}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.vless.network.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.vless.networkOptions.map(g=>e.jsx(q,{value:g.value,className:"cursor-pointer",children:g.label},g.value))})})]})})]})}),e.jsx(b,{control:u.control,name:"flow",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.vless.flow.label")}),e.jsx(N,{children:e.jsxs(J,{onValueChange:g=>p.onChange(g==="none"?null:g),value:p.value||"none",children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.vless.flow.placeholder")})}),e.jsx(Y,{children:$e.vless.flowOptions.map(g=>e.jsx(q,{value:g,children:g},g))})]})})]})})]}),tuic:()=>e.jsxs(e.Fragment,{children:[e.jsx(b,{control:u.control,name:"version",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.tuic.version.label")}),e.jsx(N,{children:e.jsxs(J,{value:p.value?.toString(),onValueChange:g=>p.onChange(Number(g)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.tuic.version.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.tuic.versions.map(g=>e.jsxs(q,{value:g,children:["V",g]},g))})})]})})]})}),e.jsx(b,{control:u.control,name:"congestion_control",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.tuic.congestion_control.label")}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.tuic.congestion_control.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.tuic.congestionControls.map(g=>e.jsx(q,{value:g,children:g.toUpperCase()},g))})})]})})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:u.control,name:"tls.server_name",render:({field:p})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:r("dynamic_form.tuic.tls.server_name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dynamic_form.tuic.tls.server_name.placeholder"),...p})})]})}),e.jsx(b,{control:u.control,name:"tls.allow_insecure",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.tuic.tls.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(N,{children:e.jsx(Q,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),e.jsx(b,{control:u.control,name:"alpn",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.tuic.tls.alpn.label")}),e.jsx(N,{children:e.jsx(st,{options:$e.tuic.alpnOptions,onChange:g=>p.onChange(g.map(j=>j.value)),value:$e.tuic.alpnOptions.filter(g=>p.value?.includes(g.value)),placeholder:r("dynamic_form.tuic.tls.alpn.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-lg leading-10 text-gray-600 dark:text-gray-400",children:r("dynamic_form.tuic.tls.alpn.empty")})})})]})}),e.jsx(b,{control:u.control,name:"udp_relay_mode",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dynamic_form.tuic.udp_relay_mode.label")}),e.jsx(N,{children:e.jsxs(J,{onValueChange:p.onChange,value:p.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dynamic_form.tuic.udp_relay_mode.placeholder")})}),e.jsx(Y,{children:e.jsx(ns,{children:$e.tuic.udpRelayModes.map(g=>e.jsx(q,{value:g.value,children:g.label},g.value))})})]})})]})})]})};return e.jsx(je,{children:C[s]?.()})},xx=h.object({id:h.number().optional().nullable(),code:h.string().optional(),name:h.string().min(1,"form.name.error"),rate:h.string().min(1,"form.rate.error"),tags:h.array(h.string()).default([]),excludes:h.array(h.string()).default([]),ips:h.array(h.string()).default([]),group_ids:h.array(h.string()).default([]),host:h.string().min(1,"form.host.error"),port:h.string().min(1,"form.port.error"),server_port:h.string().min(1,"form.server_port.error"),parent_id:h.string().default("0").nullable(),route_ids:h.array(h.string()).default([]),protocol_settings:h.record(h.any()).default({}).nullable()}),St={id:null,code:"",name:"",rate:"1",tags:[],excludes:[],ips:[],group_ids:[],host:"",port:"",server_port:"",parent_id:"0",route_ids:[],protocol_settings:null};function hx(){const{t:s}=M("server"),{isOpen:n,setIsOpen:a,editingServer:r,setEditingServer:l,serverType:c,setServerType:o,refetch:u}=Zr(),[x,i]=m.useState([]),[d,f]=m.useState([]),[w,P]=m.useState([]),C=fe({resolver:ye(xx),defaultValues:St,mode:"onChange"});m.useEffect(()=>{p()},[n]),m.useEffect(()=>{r?.type&&r.type!==c&&o(r.type)},[r,c,o]),m.useEffect(()=>{r?r.type===c&&C.reset({...St,...r}):C.reset({...St,protocol_settings:$e[c].schema.parse({})})},[r,C,c]);const p=async()=>{if(!n)return;const[E,F,H]=await Promise.all([yt(),Sr(),Cr()]);i(E.data?.map(te=>({label:te.name,value:te.id.toString()}))||[]),f(F.data?.map(te=>({label:te.remarks,value:te.id.toString()}))||[]),P(H.data||[])},g=m.useMemo(()=>w?.filter(E=>(E.parent_id===0||E.parent_id===null)&&E.type===c&&E.id!==C.watch("id")),[c,w,C]),j=()=>e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Re,{icon:"ion:add"}),e.jsx("div",{children:s("form.add_node")})]})}),e.jsx(ps,{align:"start",children:e.jsx(Od,{children:Os.map(({type:E,label:F})=>e.jsx(ge,{onClick:()=>{o(E),a(!0)},className:"cursor-pointer",children:e.jsx(K,{variant:"outline",className:"text-white",style:{background:_s[E]},children:F})},E))})})]}),S=()=>{a(!1),l(null),C.reset(St)},R=async()=>{const E=C.getValues();(await kc({...E,type:c})).data&&(S(),A.success(s("form.success")),u())};return e.jsxs(ve,{open:n,onOpenChange:S,children:[j(),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:s(r?"form.edit_node":"form.new_node")}),e.jsx(ke,{})]}),e.jsxs(Ne,{...C,children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(b,{control:C.control,name:"name",render:({field:E})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:s("form.name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("form.name.placeholder"),...E})}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"rate",render:({field:E})=>e.jsxs(v,{className:"flex-[1]",children:[e.jsx(y,{children:s("form.rate.label")}),e.jsx("div",{className:"relative flex",children:e.jsx(N,{children:e.jsx(T,{type:"number",min:"0",step:"0.1",...E})})}),e.jsx(k,{})]})})]}),e.jsx(b,{control:C.control,name:"code",render:({field:E})=>e.jsxs(v,{children:[e.jsxs(y,{children:[s("form.code.label"),e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:s("form.code.optional")})]}),e.jsx(N,{children:e.jsx(T,{placeholder:s("form.code.placeholder"),...E,value:E.value||""})}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"tags",render:({field:E})=>e.jsxs(v,{children:[e.jsx(y,{children:s("form.tags.label")}),e.jsx(N,{children:e.jsx(La,{value:E.value,onChange:E.onChange,placeholder:s("form.tags.placeholder"),className:"w-full"})}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"group_ids",render:({field:E})=>e.jsxs(v,{children:[e.jsxs(y,{className:"flex items-center justify-between",children:[s("form.groups.label"),e.jsx(aa,{dialogTrigger:e.jsx(D,{variant:"link",children:s("form.groups.add")}),refetch:p})]}),e.jsx(N,{children:e.jsx(st,{options:x,onChange:F=>E.onChange(F.map(H=>H.value)),value:x?.filter(F=>E.value.includes(F.value)),placeholder:s("form.groups.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-lg leading-10 text-gray-600 dark:text-gray-400",children:s("form.groups.empty")})})}),e.jsx(k,{})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:C.control,name:"host",render:({field:E})=>e.jsxs(v,{children:[e.jsx(y,{children:s("form.host.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:s("form.host.placeholder"),...E})}),e.jsx(k,{})]})}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(b,{control:C.control,name:"port",render:({field:E})=>e.jsxs(v,{className:"flex-1",children:[e.jsxs(y,{className:"flex items-center gap-1.5",children:[s("form.port.label"),e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(Re,{icon:"ph:info-light",className:"size-3.5 cursor-help text-muted-foreground"})}),e.jsx(Mt,{children:e.jsx(ce,{side:"top",sideOffset:8,className:"max-w-80 p-3",children:e.jsx("p",{children:s("form.port.tooltip")})})})]})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(N,{children:e.jsx(T,{placeholder:s("form.port.placeholder"),...E})}),e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(D,{type:"button",variant:"ghost",size:"icon",className:"size-6 shrink-0 text-muted-foreground/50 hover:text-muted-foreground",onClick:()=>{const F=E.value;F&&C.setValue("server_port",F)},children:e.jsx(Re,{icon:"tabler:arrows-right",className:"size-3"})})}),e.jsx(ce,{side:"right",children:e.jsx("p",{children:s("form.port.sync")})})]})})]}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"server_port",render:({field:E})=>e.jsxs(v,{className:"flex-1",children:[e.jsxs(y,{className:"flex items-center gap-1.5",children:[s("form.server_port.label"),e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(Re,{icon:"ph:info-light",className:"size-3.5 cursor-help text-muted-foreground"})}),e.jsx(Mt,{children:e.jsx(ce,{side:"top",sideOffset:8,className:"max-w-80 p-3",children:e.jsx("p",{children:s("form.server_port.tooltip")})})})]})})]}),e.jsx(N,{children:e.jsx(T,{placeholder:s("form.server_port.placeholder"),...E})}),e.jsx(k,{})]})})]})]}),n&&e.jsx(mx,{serverType:c,value:C.watch("protocol_settings"),onChange:E=>C.setValue("protocol_settings",E,{shouldDirty:!0,shouldTouch:!0,shouldValidate:!0})}),e.jsx(b,{control:C.control,name:"parent_id",render:({field:E})=>e.jsxs(v,{children:[e.jsx(y,{children:s("form.parent.label")}),e.jsxs(J,{onValueChange:E.onChange,value:E.value?.toString()||"0",children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:s("form.parent.placeholder")})})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:s("form.parent.none")}),g?.map(F=>e.jsx(q,{value:F.id.toString(),className:"cursor-pointer",children:F.name},F.id))]})]}),e.jsx(k,{})]})}),e.jsx(b,{control:C.control,name:"route_ids",render:({field:E})=>e.jsxs(v,{children:[e.jsx(y,{children:s("form.route.label")}),e.jsx(N,{children:e.jsx(st,{options:d,onChange:F=>E.onChange(F.map(H=>H.value)),value:d?.filter(F=>E.value.includes(F.value)),placeholder:s("form.route.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-lg leading-10 text-gray-600 dark:text-gray-400",children:s("form.route.empty")})})}),e.jsx(k,{})]})})]}),e.jsxs(Oe,{className:"mt-6",children:[e.jsx(D,{type:"button",variant:"outline",onClick:S,children:s("form.cancel")}),e.jsx(D,{type:"submit",onClick:R,children:s("form.submit")})]})]})]})]})}function un({column:s,title:n,options:a}){const r=s?.getFacetedUniqueValues(),l=new Set(s?.getFilterValue());return e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(vt,{className:"mr-2 h-4 w-4"}),n,l?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:l.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:l.size>2?e.jsxs(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[l.size," selected"]}):a.filter(c=>l.has(c.value)).map(c=>e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:c.label},c.value))})]})]})}),e.jsx(ms,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Vs,{children:[e.jsx(Us,{placeholder:n}),e.jsxs(Ms,{children:[e.jsx(Ks,{children:"No results found."}),e.jsx(Ge,{children:a.map(c=>{const o=l.has(c.value);return e.jsxs(Ie,{onSelect:()=>{o?l.delete(c.value):l.add(c.value);const u=Array.from(l);s?.setFilterValue(u.length?u:void 0)},className:"cursor-pointer",children:[e.jsx("div",{className:_("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",o?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(As,{className:_("h-4 w-4")})}),c.icon&&e.jsx(c.icon,{className:`mr-2 h-4 w-4 text-muted-foreground text-${c.color}`}),e.jsx("span",{children:c.label}),r?.get(c.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(c.value)})]},c.value)})}),l.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(at,{}),e.jsx(Ge,{children:e.jsx(Ie,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center cursor-pointer",children:"Clear filters"})})]})]})]})})]})}const px=[{value:Te.Shadowsocks,label:Os.find(s=>s.type===Te.Shadowsocks)?.label,color:_s[Te.Shadowsocks]},{value:Te.Vmess,label:Os.find(s=>s.type===Te.Vmess)?.label,color:_s[Te.Vmess]},{value:Te.Trojan,label:Os.find(s=>s.type===Te.Trojan)?.label,color:_s[Te.Trojan]},{value:Te.Hysteria,label:Os.find(s=>s.type===Te.Hysteria)?.label,color:_s[Te.Hysteria]},{value:Te.Vless,label:Os.find(s=>s.type===Te.Vless)?.label,color:_s[Te.Vless]}];function fx({table:s,saveOrder:n,isSortMode:a,groups:r}){const l=s.getState().columnFilters.length>0,{t:c}=M("server");return e.jsxs("div",{className:"flex items-center justify-between ",children:[e.jsxs("div",{className:"flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-2",children:[!a&&e.jsxs(e.Fragment,{children:[e.jsx(hx,{}),e.jsx(T,{placeholder:c("toolbar.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:o=>s.getColumn("name")?.setFilterValue(o.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),e.jsxs("div",{className:"flex gap-x-2",children:[s.getColumn("type")&&e.jsx(un,{column:s.getColumn("type"),title:c("toolbar.type"),options:px}),s.getColumn("group_ids")&&e.jsx(un,{column:s.getColumn("group_ids"),title:c("columns.groups.title"),options:r.map(o=>({label:o.name,value:o.id.toString()}))})]}),l&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[c("toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]}),a&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:c("toolbar.sort.tip")})})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(D,{variant:a?"default":"outline",onClick:n,size:"sm",children:c(a?"toolbar.sort.save":"toolbar.sort.edit")})})]})}const gt=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M15.71 12.71a6 6 0 1 0-7.42 0a10 10 0 0 0-6.22 8.18a1 1 0 0 0 2 .22a8 8 0 0 1 15.9 0a1 1 0 0 0 1 .89h.11a1 1 0 0 0 .88-1.1a10 10 0 0 0-6.25-8.19M12 12a4 4 0 1 1 4-4a4 4 0 0 1-4 4"})}),kt={0:"bg-destructive/80 shadow-sm shadow-destructive/50",1:"bg-yellow-500/80 shadow-sm shadow-yellow-500/50",2:"bg-emerald-500/80 shadow-sm shadow-emerald-500/50"},gx=s=>{const{t:n}=M("server");return[{id:"drag-handle",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.sort")}),cell:()=>e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Kt,{className:"size-4 cursor-move text-muted-foreground transition-colors hover:text-primary","aria-hidden":"true"})}),size:50},{accessorKey:"id",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.nodeId")}),cell:({row:a})=>{const r=a.getValue("id"),l=a.original.code;return e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsxs("div",{className:"group/id flex items-center space-x-2",children:[e.jsxs(K,{variant:"outline",className:_("border-2 font-medium transition-all duration-200 hover:opacity-80","flex items-center gap-1.5"),style:{borderColor:_s[a.original.type]},children:[e.jsx(ur,{className:"size-3"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"flex items-center gap-0.5",children:l??r}),a.original.parent?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground/30",children:"→"}),e.jsx("span",{children:a.original.parent?.code||a.original.parent?.id})]}):""]})]}),e.jsx(D,{variant:"ghost",size:"icon",className:"size-5 text-muted-foreground/40 opacity-0 transition-all duration-200 hover:text-muted-foreground group-hover/id:opacity-100",onClick:c=>{c.stopPropagation(),zt(l||r.toString()).then(()=>{A.success(n("common:copy.success"))})},children:e.jsx(Za,{className:"size-3"})})]})}),e.jsxs(ce,{side:"top",className:"flex flex-col gap-1 p-3",children:[e.jsxs("p",{className:"font-medium",children:[Os.find(c=>c.type===a.original.type)?.label,a.original.parent_id?" (子节点)":""]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"点击括号内容或复制按钮可复制节点代码":"点击复制按钮可复制节点ID"})]})]})})},size:50,enableSorting:!0},{accessorKey:"show",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.show")}),cell:({row:a})=>{const[r,l]=m.useState(!!a.getValue("show"));return e.jsx(Q,{checked:r,onCheckedChange:async c=>{l(c),Pc({id:a.original.id,type:a.original.type,show:c?1:0}).catch(()=>{l(!c),s()})},style:{backgroundColor:r?_s[a.original.type]:void 0}})},size:50,enableSorting:!1},{accessorKey:"name",header:({column:a})=>e.jsx("div",{className:"flex items-center",children:e.jsx(L,{column:a,title:n("columns.node"),tooltip:e.jsxs("div",{className:"grid grid-cols-1 gap-3 p-2",children:[e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:_("h-2.5 w-2.5 rounded-full",kt[0])}),e.jsx("span",{className:"text-sm font-medium",children:n("columns.status.0")})]}),e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:_("h-2.5 w-2.5 rounded-full",kt[1])}),e.jsx("span",{className:"text-sm font-medium",children:n("columns.status.1")})]}),e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:_("h-2.5 w-2.5 rounded-full",kt[2])}),e.jsx("span",{className:"text-sm font-medium",children:n("columns.status.2")})]})]})})}),cell:({row:a})=>e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{children:e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:_("size-2.5 flex-shrink-0 rounded-full transition-all duration-200",kt[a.original.available_status])}),e.jsx("span",{className:"text-left font-medium transition-colors hover:text-primary",children:a.getValue("name")})]})}),e.jsx(ce,{children:e.jsx("p",{className:"font-medium",children:n(`columns.status.${a.original.available_status}`)})})]})}),enableSorting:!1,size:200},{accessorKey:"host",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.address")}),cell:({row:a})=>{const r=`${a.original.host}:${a.original.port}`,l=a.original.port!==a.original.server_port;return e.jsxs("div",{className:"group relative flex min-w-0 items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-baseline gap-x-1 gap-y-0.5 pr-7",children:[e.jsx("div",{className:"flex items-center ",children:e.jsxs("span",{className:"font-mono text-sm font-medium text-foreground/90",children:[a.original.host,":",a.original.port]})}),l&&e.jsxs("span",{className:"whitespace-nowrap text-[0.7rem] tracking-tight text-muted-foreground/40",children:["(",n("columns.internalPort")," ",a.original.server_port,")"]})]}),e.jsx("div",{className:"absolute right-0 top-0",children:e.jsx(je,{delayDuration:0,children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"icon",className:"size-6 text-muted-foreground/40 opacity-0 transition-all duration-200 hover:bg-muted/50 hover:text-muted-foreground group-hover:opacity-100",onClick:c=>{c.stopPropagation(),zt(r).then(()=>{A.success(n("common:copy.success"))})},children:e.jsx(Za,{className:"size-3"})})}),e.jsx(ce,{side:"top",sideOffset:10,children:n("columns.copyAddress")})]})})})]})},enableSorting:!1,enableHiding:!0},{accessorKey:"online",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.onlineUsers.title"),tooltip:n("columns.onlineUsers.tooltip")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center space-x-2 px-4",children:[e.jsx(gt,{className:"size-4"}),e.jsx("span",{className:"font-medium",children:a.getValue("online")})]}),size:80,enableSorting:!0,enableHiding:!0},{accessorKey:"rate",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.rate.title"),tooltip:n("columns.rate.tooltip")}),cell:({row:a})=>e.jsxs(K,{variant:"secondary",className:"font-medium",children:[a.getValue("rate")," x"]}),size:80,enableSorting:!1,enableHiding:!0},{accessorKey:"group_ids",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.groups.title"),tooltip:n("columns.groups.tooltip")}),cell:({row:a})=>{const r=a.original.groups||[];return e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.map((l,c)=>e.jsx(K,{variant:"secondary",className:_("px-2 py-0.5 font-medium","bg-secondary/50 hover:bg-secondary/70","border border-border/50","transition-all duration-200","cursor-default select-none","flex items-center gap-1.5"),children:l.name},c)),r.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:n("columns.groups.empty")})]})},enableSorting:!1,filterFn:(a,r,l)=>{const c=a.getValue(r);return c?l.some(o=>c.includes(o)):!1}},{accessorKey:"type",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.type")}),cell:({row:a})=>{const r=a.getValue("type");return e.jsx(K,{variant:"outline",className:"border-2 font-medium transition-colors",style:{borderColor:_s[r]},children:r})},enableSorting:!1,enableHiding:!0,enableColumnFilter:!1,size:8e3},{id:"actions",header:({column:a})=>e.jsx(L,{className:"justify-end",column:a,title:n("columns.actions")}),cell:({row:a})=>{const{setIsOpen:r,setEditingServer:l,setServerType:c}=Zr();return e.jsx("div",{className:"flex justify-center",children:e.jsxs(Cs,{modal:!1,children:[e.jsx(Ss,{asChild:!0,children:e.jsx(D,{variant:"ghost",className:"h-8 w-8 p-0 hover:bg-muted","aria-label":n("columns.actions"),children:e.jsx(Ft,{className:"size-4"})})}),e.jsxs(ps,{align:"end",className:"w-40",children:[e.jsx(ge,{className:"cursor-pointer",onClick:()=>{c(a.original.type),l(a.original),r(!0)},children:e.jsxs("div",{className:"flex w-full items-center",children:[e.jsx(Lo,{className:"mr-2 size-4"}),n("columns.actions_dropdown.edit")]})}),e.jsxs(ge,{className:"cursor-pointer",onClick:async()=>{Dc({id:a.original.id}).then(({data:o})=>{o&&(A.success(n("columns.actions_dropdown.copy_success")),s())})},children:[e.jsx(Ao,{className:"mr-2 size-4"}),n("columns.actions_dropdown.copy")]}),e.jsx(et,{}),e.jsx(ge,{className:"cursor-pointer text-destructive focus:text-destructive",onSelect:o=>o.preventDefault(),children:e.jsx(We,{title:n("columns.actions_dropdown.delete.title"),description:n("columns.actions_dropdown.delete.description"),confirmText:n("columns.actions_dropdown.delete.confirm"),variant:"destructive",onConfirm:async()=>{Tc({id:a.original.id}).then(({data:o})=>{o&&(A.success(n("columns.actions_dropdown.delete_success")),s())})},children:e.jsxs("div",{className:"flex w-full items-center",children:[e.jsx(os,{className:"mr-2 size-4"}),n("columns.actions_dropdown.delete.confirm")]})})})]})]})})},size:50}]};function jx(){const[s,n]=m.useState({}),[a,r]=m.useState({"drag-handle":!1}),[l,c]=m.useState([]),[o,u]=m.useState({pageSize:500,pageIndex:0}),[x,i]=m.useState([]),[d,f]=m.useState(!1),[w,P]=m.useState({}),[C,p]=m.useState([]),{refetch:g}=ie({queryKey:["nodeList"],queryFn:async()=>{const{data:H}=await Cr();return p(H),H}}),{data:j}=ie({queryKey:["groups"],queryFn:async()=>{const{data:H}=await yt();return H}});m.useEffect(()=>{r({"drag-handle":d,show:!d,host:!d,online:!d,rate:!d,groups:!d,type:!1,actions:!d}),P({name:d?2e3:200}),u({pageSize:d?99999:500,pageIndex:0})},[d]);const S=(H,te)=>{d&&(H.dataTransfer.setData("text/plain",te.toString()),H.currentTarget.classList.add("opacity-50"))},R=(H,te)=>{if(!d)return;H.preventDefault(),H.currentTarget.classList.remove("bg-muted");const O=parseInt(H.dataTransfer.getData("text/plain"));if(O===te)return;const se=[...C],[He]=se.splice(O,1);se.splice(te,0,He),p(se)},E=async()=>{if(!d){f(!0);return}const H=C?.map((te,O)=>({id:te.id,order:O+1}));Ec(H).then(()=>{A.success("排序保存成功"),f(!1),g()}).finally(()=>{f(!1)})},F=ts({data:C||[],columns:gx(g),state:{sorting:x,columnVisibility:a,rowSelection:s,columnFilters:l,columnSizing:w,pagination:o},enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:i,onColumnFiltersChange:c,onColumnVisibilityChange:r,onColumnSizingChange:P,onPaginationChange:u,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(Xm,{refetch:g,children:e.jsx("div",{className:"space-y-4",children:e.jsx(xs,{table:F,toolbar:H=>e.jsx(fx,{table:H,refetch:g,saveOrder:E,isSortMode:d,groups:j||[]}),draggable:d,onDragStart:S,onDragEnd:H=>H.currentTarget.classList.remove("opacity-50"),onDragOver:H=>{H.preventDefault(),H.currentTarget.classList.add("bg-muted")},onDragLeave:H=>H.currentTarget.classList.remove("bg-muted"),onDrop:R,showPagination:!d})})})}function vx(){const{t:s}=M("server");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("manage.title")}),e.jsx("p",{className:"text-muted-foreground mt-2",children:s("manage.description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(jx,{})})]})]})}const bx=Object.freeze(Object.defineProperty({__proto__:null,default:vx},Symbol.toStringTag,{value:"Module"}));function yx({table:s,refetch:n}){const a=s.getState().columnFilters.length>0,{t:r}=M("group");return e.jsx("div",{className:"flex items-center justify-between space-x-4",children:e.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[e.jsx(aa,{refetch:n}),e.jsx(T,{placeholder:r("toolbar.searchPlaceholder"),value:s.getColumn("name")?.getFilterValue()??"",onChange:l=>s.getColumn("name")?.setFilterValue(l.target.value),className:_("h-8 w-[150px] lg:w-[250px]",a&&"border-primary/50 ring-primary/20")}),a&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[r("toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]})})}const Nx=s=>{const{t:n}=M("group");return[{accessorKey:"id",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.id")}),cell:({row:a})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(K,{variant:"outline",children:a.getValue("id")})}),enableSorting:!0},{accessorKey:"name",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.name")}),cell:({row:a})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium",children:a.getValue("name")})})},{accessorKey:"users_count",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.usersCount")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center space-x-2 px-4",children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:a.getValue("users_count")})]}),enableSorting:!0},{accessorKey:"server_count",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.serverCount")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center space-x-2 px-4",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:a.getValue("server_count")})]}),enableSorting:!0,size:8e3},{id:"actions",header:({column:a})=>e.jsx(L,{className:"justify-end",column:a,title:n("columns.actions")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(aa,{defaultValues:a.original,refetch:s,type:"edit",dialogTrigger:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("form.edit")})]})}),e.jsx(We,{title:n("messages.deleteConfirm"),description:n("messages.deleteDescription"),confirmText:n("messages.deleteButton"),variant:"destructive",onConfirm:async()=>{Ic({id:a.original.id}).then(({data:r})=>{r&&(A.success(n("messages.updateSuccess")),s())})},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("messages.deleteButton")})]})})]})}]};function _x(){const[s,n]=m.useState({}),[a,r]=m.useState({}),[l,c]=m.useState([]),[o,u]=m.useState([]),{data:x,refetch:i,isLoading:d}=ie({queryKey:["serverGroupList"],queryFn:async()=>{const{data:w}=await yt();return w}}),f=ts({data:x||[],columns:Nx(i),state:{sorting:o,columnVisibility:a,rowSelection:s,columnFilters:l},enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:u,onColumnFiltersChange:c,onColumnVisibilityChange:r,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(xs,{table:f,toolbar:w=>e.jsx(yx,{table:w,refetch:i}),isLoading:d})}function wx(){const{t:s}=M("group");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(_x,{})})]})]})}const Cx=Object.freeze(Object.defineProperty({__proto__:null,default:wx},Symbol.toStringTag,{value:"Module"})),Sx=s=>h.object({remarks:h.string().min(1,s("form.validation.remarks")),match:h.array(h.string()),action:h.enum(["block","dns"]),action_value:h.string().optional()});function Xr({refetch:s,dialogTrigger:n,defaultValues:a={remarks:"",match:[],action:"block",action_value:""},type:r="add"}){const{t:l}=M("route"),c=fe({resolver:ye(Sx(l)),defaultValues:a,mode:"onChange"}),[o,u]=m.useState(!1);return e.jsxs(ve,{open:o,onOpenChange:u,children:[e.jsx(Ye,{asChild:!0,children:n||e.jsxs(D,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Re,{icon:"ion:add"})," ",e.jsx("div",{children:l("form.add")})]})}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:l(r==="edit"?"form.edit":"form.create")}),e.jsx(ke,{})]}),e.jsxs(Ne,{...c,children:[e.jsx(b,{control:c.control,name:"remarks",render:({field:x})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:l("form.remarks")}),e.jsx("div",{className:"relative",children:e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:l("form.remarksPlaceholder"),...x})})}),e.jsx(k,{})]})}),e.jsx(b,{control:c.control,name:"match",render:({field:x})=>e.jsxs(v,{className:"flex-[2]",children:[e.jsx(y,{children:l("form.match")}),e.jsx("div",{className:"relative",children:e.jsx(N,{children:e.jsx(bs,{className:"min-h-[120px]",placeholder:l("form.matchPlaceholder"),value:x.value.join(` -`),onChange:i=>{x.onChange(i.target.value.split(` -`))}})})}),e.jsx(k,{})]})}),e.jsx(b,{control:c.control,name:"action",render:({field:x})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.action")}),e.jsx("div",{className:"relative",children:e.jsx(N,{children:e.jsxs(J,{onValueChange:x.onChange,defaultValue:x.value,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:l("form.actionPlaceholder")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"block",children:l("actions.block")}),e.jsx(q,{value:"dns",children:l("actions.dns")})]})]})})}),e.jsx(k,{})]})}),c.watch("action")==="dns"&&e.jsx(b,{control:c.control,name:"action_value",render:({field:x})=>e.jsxs(v,{children:[e.jsx(y,{children:l("form.dns")}),e.jsx("div",{className:"relative",children:e.jsx(N,{children:e.jsx(T,{type:"text",placeholder:l("form.dnsPlaceholder"),...x})})})]})}),e.jsxs(Oe,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(D,{variant:"outline",children:l("form.cancel")})}),e.jsx(D,{type:"submit",onClick:()=>{Vc(c.getValues()).then(({data:x})=>{x&&(u(!1),s&&s(),toast.success(l(r==="edit"?"messages.updateSuccess":"messages.createSuccess")),c.reset())})},children:l("form.submit")})]})]})]})]})}function kx({table:s,refetch:n}){const a=s.getState().columnFilters.length>0,{t:r}=M("route");return e.jsx("div",{className:"flex items-center justify-between ",children:e.jsxs("div",{className:"flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-2",children:[e.jsx(Xr,{refetch:n}),e.jsx(T,{placeholder:r("toolbar.searchPlaceholder"),value:s.getColumn("remarks")?.getFilterValue()??"",onChange:l=>s.getColumn("remarks")?.setFilterValue(l.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),a&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[r("toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]})})}function Tx({columns:s,data:n,refetch:a}){const[r,l]=m.useState({}),[c,o]=m.useState({}),[u,x]=m.useState([]),[i,d]=m.useState([]),f=ts({data:n,columns:s,state:{sorting:i,columnVisibility:c,rowSelection:r,columnFilters:u},enableRowSelection:!0,onRowSelectionChange:l,onSortingChange:d,onColumnFiltersChange:x,onColumnVisibilityChange:o,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(xs,{table:f,toolbar:w=>e.jsx(kx,{table:w,refetch:a})})}const Dx=s=>{const{t:n}=M("route"),a={block:{icon:$o,variant:"destructive",className:"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-800"},dns:{icon:qo,variant:"secondary",className:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-800"}};return[{accessorKey:"id",header:({column:r})=>e.jsx(L,{column:r,title:n("columns.id")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(K,{variant:"outline",children:r.getValue("id")})}),enableSorting:!0,enableHiding:!1},{accessorKey:"remarks",header:({column:r})=>e.jsx(L,{column:r,title:n("columns.remarks")}),cell:({row:r})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium sm:max-w-72 md:max-w-[31rem]",children:r.original.remarks})}),enableHiding:!1,enableSorting:!1},{accessorKey:"action_value",header:({column:r})=>e.jsx(L,{column:r,title:n("columns.action_value.title")}),cell:({row:r})=>{const l=r.original.action,c=r.original.action_value,o=r.original.match?.length||0;return e.jsxs("div",{className:"flex flex-col space-y-1",children:[e.jsx("span",{className:"text-sm font-medium",children:l==="dns"&&c?n("columns.action_value.dns",{value:c}):l==="block"?e.jsx("span",{className:"text-destructive",children:n("columns.action_value.block")}):n("columns.action_value.direct")}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n("columns.matchRules",{count:o})})]})},enableHiding:!1,enableSorting:!1,size:300},{accessorKey:"action",header:({column:r})=>e.jsx(L,{column:r,title:n("columns.action")}),cell:({row:r})=>{const l=r.getValue("action"),c=a[l]?.icon;return e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs(K,{variant:a[l]?.variant||"default",className:_("flex items-center gap-1.5 px-3 py-1 capitalize",a[l]?.className),children:[c&&e.jsx(c,{className:"h-3.5 w-3.5"}),n(`actions.${l}`)]})})},enableSorting:!1,size:9e3},{id:"actions",header:()=>e.jsx("div",{className:"text-right",children:n("columns.actions")}),cell:({row:r})=>e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(Xr,{defaultValues:r.original,refetch:s,type:"edit",dialogTrigger:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("form.edit")})]})}),e.jsx(We,{title:n("messages.deleteConfirm"),description:n("messages.deleteDescription"),confirmText:n("messages.deleteButton"),variant:"destructive",onConfirm:async()=>{Mc({id:r.original.id}).then(({data:l})=>{l&&(A.success(n("messages.deleteSuccess")),s())})},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("messages.deleteButton")})]})})]})}]};function Px(){const{t:s}=M("route"),[n,a]=m.useState([]);function r(){Sr().then(({data:l})=>{a(l)})}return m.useEffect(()=>{r()},[]),e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Tx,{data:n,columns:Dx(r),refetch:r})})]})]})}const Ex=Object.freeze(Object.defineProperty({__proto__:null,default:Px},Symbol.toStringTag,{value:"Module"})),el=m.createContext(void 0);function Rx({children:s,refreshData:n}){const[a,r]=m.useState(!1),[l,c]=m.useState(null);return e.jsx(el.Provider,{value:{isOpen:a,setIsOpen:r,editingPlan:l,setEditingPlan:c,refreshData:n},children:s})}function Aa(){const s=m.useContext(el);if(s===void 0)throw new Error("usePlanEdit must be used within a PlanEditProvider");return s}function Ix({table:s,saveOrder:n,isSortMode:a}){const{setIsOpen:r}=Aa(),{t:l}=M("subscribe");return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[e.jsxs(D,{variant:"outline",className:"space-x-2",size:"sm",onClick:()=>r(!0),children:[e.jsx(Re,{icon:"ion:add"}),e.jsx("div",{children:l("plan.add")})]}),e.jsx(T,{placeholder:l("plan.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:c=>s.getColumn("name")?.setFilterValue(c.target.value),className:"h-8 w-[150px] lg:w-[250px]"})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(D,{variant:a?"default":"outline",onClick:n,size:"sm",children:l(a?"plan.sort.save":"plan.sort.edit")})})]})}const mn={monthly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},quarterly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},half_yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},two_yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},three_yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},onetime:{color:"text-slate-700",bgColor:"bg-slate-100/80"},reset_traffic:{color:"text-slate-700",bgColor:"bg-slate-100/80"}},Vx=s=>{const{t:n}=M("subscribe");return[{id:"drag-handle",header:()=>null,cell:()=>e.jsx("div",{className:"cursor-move",children:e.jsx(Kt,{className:"size-4"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.id")}),cell:({row:a})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(K,{variant:"outline",children:a.getValue("id")})}),enableSorting:!0,enableHiding:!1},{accessorKey:"show",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.show")}),cell:({row:a})=>e.jsx(Q,{defaultChecked:a.getValue("show"),onCheckedChange:r=>{na({id:a.original.id,show:r}).then(({data:l})=>{!l&&s()})}}),enableSorting:!1,enableHiding:!1},{accessorKey:"sell",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.sell")}),cell:({row:a})=>e.jsx(Q,{defaultChecked:a.getValue("sell"),onCheckedChange:r=>{na({id:a.original.id,sell:r}).then(({data:l})=>{!l&&s()})}}),enableSorting:!1,enableHiding:!1},{accessorKey:"renew",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.renew"),tooltip:n("plan.columns.renew_tooltip")}),cell:({row:a})=>e.jsx(Q,{defaultChecked:a.getValue("renew"),onCheckedChange:r=>{na({id:a.original.id,renew:r}).then(({data:l})=>{!l&&s()})}}),enableSorting:!1,enableHiding:!1},{accessorKey:"name",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.name")}),cell:({row:a})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium sm:max-w-72 md:max-w-[31rem]",children:a.getValue("name")})}),enableSorting:!1,enableHiding:!1,size:900},{accessorKey:"users_count",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.stats")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center space-x-2 px-2",children:[e.jsx(gt,{}),e.jsx("span",{className:"max-w-32 truncate font-medium sm:max-w-72 md:max-w-[31rem]",children:a.getValue("users_count")})]}),enableSorting:!0},{accessorKey:"group",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.group")}),cell:({row:a})=>e.jsx("div",{className:"flex max-w-[600px] flex-wrap items-center gap-1.5 text-nowrap",children:e.jsx(K,{variant:"secondary",className:_("px-2 py-0.5 font-medium","bg-secondary/50 hover:bg-secondary/70","border border-border/50","transition-all duration-200","cursor-default select-none","flex items-center gap-1.5"),children:a.getValue("group")?.name})}),enableSorting:!1,enableHiding:!1},{accessorKey:"prices",header:({column:a})=>e.jsx(L,{column:a,title:n("plan.columns.price")}),cell:({row:a})=>{const r=a.getValue("prices"),l=[{period:n("plan.columns.price_period.monthly"),key:"monthly",unit:n("plan.columns.price_period.unit.month")},{period:n("plan.columns.price_period.quarterly"),key:"quarterly",unit:n("plan.columns.price_period.unit.quarter")},{period:n("plan.columns.price_period.half_yearly"),key:"half_yearly",unit:n("plan.columns.price_period.unit.half_year")},{period:n("plan.columns.price_period.yearly"),key:"yearly",unit:n("plan.columns.price_period.unit.year")},{period:n("plan.columns.price_period.two_yearly"),key:"two_yearly",unit:n("plan.columns.price_period.unit.two_year")},{period:n("plan.columns.price_period.three_yearly"),key:"three_yearly",unit:n("plan.columns.price_period.unit.three_year")},{period:n("plan.columns.price_period.onetime"),key:"onetime",unit:""},{period:n("plan.columns.price_period.reset_traffic"),key:"reset_traffic",unit:n("plan.columns.price_period.unit.times")}];return e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:l.map(({period:c,key:o,unit:u})=>r[o]!=null&&e.jsxs(K,{variant:"secondary",className:_("px-2 py-0.5 font-medium transition-colors text-nowrap",mn[o].color,mn[o].bgColor,"border border-border/50","hover:bg-slate-200/80"),children:[c," ¥",r[o],u]},o))})},enableSorting:!1,size:9e3},{id:"actions",header:({column:a})=>e.jsx(L,{className:"justify-end",column:a,title:n("plan.columns.actions")}),cell:({row:a})=>{const{setIsOpen:r,setEditingPlan:l}=Aa();return e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",onClick:()=>{l(a.original),r(!0)},children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("plan.columns.edit")})]}),e.jsx(We,{title:n("plan.columns.delete_confirm.title"),description:n("plan.columns.delete_confirm.description"),confirmText:n("plan.columns.delete"),variant:"destructive",onConfirm:async()=>{Xc({id:a.original.id}).then(({data:c})=>{c&&(A.success(n("plan.columns.delete_confirm.success")),s())})},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("plan.columns.delete")})]})})]})}}]},Mx=h.object({id:h.number().nullable(),group_id:h.union([h.number(),h.string()]).nullable().optional(),name:h.string().min(1).max(250),content:h.string().nullable().optional(),transfer_enable:h.union([h.number().min(0),h.string().min(1)]),prices:h.object({monthly:h.union([h.number(),h.string()]).nullable().optional(),quarterly:h.union([h.number(),h.string()]).nullable().optional(),half_yearly:h.union([h.number(),h.string()]).nullable().optional(),yearly:h.union([h.number(),h.string()]).nullable().optional(),two_yearly:h.union([h.number(),h.string()]).nullable().optional(),three_yearly:h.union([h.number(),h.string()]).nullable().optional(),onetime:h.union([h.number(),h.string()]).nullable().optional(),reset_traffic:h.union([h.number(),h.string()]).nullable().optional()}).default({}),speed_limit:h.union([h.number(),h.string()]).nullable().optional(),capacity_limit:h.union([h.number(),h.string()]).nullable().optional(),device_limit:h.union([h.number(),h.string()]).nullable().optional(),force_update:h.boolean().optional(),reset_traffic_method:h.number().nullable(),users_count:h.number().optional()}),sl=m.forwardRef(({className:s,...n},a)=>e.jsx(mr,{ref:a,className:_("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",s),...n,children:e.jsx(Ho,{className:_("flex items-center justify-center text-current"),children:e.jsx(As,{className:"h-4 w-4"})})}));sl.displayName=mr.displayName;const Tt={id:null,group_id:null,name:"",content:"",transfer_enable:"",prices:{monthly:"",quarterly:"",half_yearly:"",yearly:"",two_yearly:"",three_yearly:"",onetime:"",reset_traffic:""},speed_limit:"",capacity_limit:"",device_limit:"",force_update:!1,reset_traffic_method:null},Dt={monthly:{label:"月付",months:1,discount:1},quarterly:{label:"季付",months:3,discount:.95},half_yearly:{label:"半年付",months:6,discount:.9},yearly:{label:"年付",months:12,discount:.85},two_yearly:{label:"两年付",months:24,discount:.8},three_yearly:{label:"三年付",months:36,discount:.75},onetime:{label:"流量包",months:1,discount:1},reset_traffic:{label:"重置包",months:1,discount:1}},Fx=[{value:null,label:"follow_system"},{value:0,label:"monthly_first"},{value:1,label:"monthly_reset"},{value:2,label:"no_reset"},{value:3,label:"yearly_first"},{value:4,label:"yearly_reset"}];function Ox(){const{isOpen:s,setIsOpen:n,editingPlan:a,setEditingPlan:r,refreshData:l}=Aa(),[c,o]=m.useState(!1),{t:u}=M("subscribe"),x=fe({resolver:ye(Mx),defaultValues:{...Tt,...a||{}},mode:"onChange"});m.useEffect(()=>{a?x.reset({...Tt,...a}):x.reset(Tt)},[a,x]);const i=new Ea({html:!0}),[d,f]=m.useState();async function w(){yt().then(({data:p})=>{f(p)})}m.useEffect(()=>{s&&w()},[s]);const P=p=>{if(isNaN(p))return;const g=Object.entries(Dt).reduce((j,[S,R])=>{const E=p*R.months*R.discount;return{...j,[S]:E.toFixed(2)}},{});x.setValue("prices",g,{shouldDirty:!0})},C=()=>{n(!1),r(null),x.reset(Tt)};return e.jsx(ve,{open:s,onOpenChange:C,children:e.jsxs(pe,{children:[e.jsxs(we,{children:[e.jsx(be,{children:u(a?"plan.form.edit_title":"plan.form.add_title")}),e.jsx(ke,{})]}),e.jsxs(Ne,{...x,children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{control:x.control,name:"name",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:u("plan.form.name.label")}),e.jsx(N,{children:e.jsx(T,{placeholder:u("plan.form.name.placeholder"),...p})}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"group_id",render:({field:p})=>e.jsxs(v,{children:[e.jsxs(y,{className:"flex items-center justify-between",children:[u("plan.form.group.label"),e.jsx(aa,{dialogTrigger:e.jsx(D,{variant:"link",children:u("plan.form.group.add")}),refetch:w})]}),e.jsxs(J,{value:p.value?.toString()??"",onValueChange:g=>p.onChange(g?Number(g):null),children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:u("plan.form.group.placeholder")})})}),e.jsx(Y,{children:d?.map(g=>e.jsx(q,{value:g.id.toString(),children:g.name},g.id))})]}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"transfer_enable",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:u("plan.form.transfer.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(N,{children:e.jsx(T,{type:"number",min:0,placeholder:u("plan.form.transfer.placeholder"),className:"rounded-r-none",...p})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:u("plan.form.transfer.unit")})]}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"speed_limit",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:u("plan.form.speed.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(N,{children:e.jsx(T,{type:"number",min:0,placeholder:u("plan.form.speed.placeholder"),className:"rounded-r-none",...p,value:p.value??""})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:u("plan.form.speed.unit")})]}),e.jsx(k,{})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-1 items-center",children:[e.jsx("div",{className:"flex-grow border-t border-gray-200 dark:border-gray-700"}),e.jsx("h3",{className:"mx-4 text-sm font-medium text-gray-500 dark:text-gray-400",children:u("plan.form.price.title")}),e.jsx("div",{className:"flex-grow border-t border-gray-200 dark:border-gray-700"})]}),e.jsxs("div",{className:"ml-4 flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2",children:e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"¥"})}),e.jsx(T,{type:"number",placeholder:u("plan.form.price.base_price"),className:"h-7 w-32 border-0 bg-gray-50 pl-6 pr-2 text-sm shadow-none ring-1 ring-gray-200 transition-shadow focus-visible:ring-2 focus-visible:ring-primary dark:bg-gray-800/50 dark:ring-gray-700 dark:placeholder:text-gray-500",onChange:p=>{const g=parseFloat(p.target.value);P(g)}})]}),e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(D,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{const p=Object.keys(Dt).reduce((g,j)=>({...g,[j]:""}),{});x.setValue("prices",p,{shouldDirty:!0})},children:u("plan.form.price.clear.button")})}),e.jsx(ce,{side:"top",align:"end",children:e.jsx("p",{className:"text-xs",children:u("plan.form.price.clear.tooltip")})})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-3",children:Object.entries(Dt).filter(([p])=>!["onetime","reset_traffic"].includes(p)).map(([p,g])=>e.jsx("div",{className:"group relative rounded-md bg-card p-2 ring-1 ring-gray-200 transition-all hover:ring-primary dark:ring-gray-800",children:e.jsx(b,{control:x.control,name:`prices.${p}`,render:({field:j})=>e.jsxs(v,{children:[e.jsxs(y,{className:"text-xs font-medium text-muted-foreground",children:[u(`plan.columns.price_period.${p}`),e.jsxs("span",{className:"ml-1 text-[10px] text-gray-400",children:["(",g.months===1?u("plan.form.price.period.monthly"):u("plan.form.price.period.months",{count:g.months}),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2",children:e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"¥"})}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:"0.00",min:0,...j,value:j.value??"",onChange:S=>j.onChange(S.target.value),className:"h-7 border-0 bg-gray-50 pl-6 pr-2 text-sm shadow-none ring-1 ring-gray-200 transition-shadow focus-visible:ring-2 focus-visible:ring-primary dark:bg-gray-800/50 dark:ring-gray-700 dark:placeholder:text-gray-500"})})]})]})})},p))}),e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:Object.entries(Dt).filter(([p])=>["onetime","reset_traffic"].includes(p)).map(([p,g])=>e.jsx("div",{className:"rounded-md border border-dashed border-gray-200 bg-muted/30 p-3 dark:border-gray-700",children:e.jsx(b,{control:x.control,name:`prices.${p}`,render:({field:j})=>e.jsx(v,{children:e.jsxs("div",{className:"flex flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-0",children:[e.jsx(y,{className:"text-xs font-medium",children:u(`plan.columns.price_period.${p}`)}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:u(p==="onetime"?"plan.form.price.onetime_desc":"plan.form.price.reset_desc")})]}),e.jsxs("div",{className:"relative w-full md:w-32",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2",children:e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"¥"})}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:"0.00",min:0,...j,className:"h-7 border-0 bg-gray-50 pl-6 pr-2 text-sm shadow-none ring-1 ring-gray-200 transition-shadow focus-visible:ring-2 focus-visible:ring-primary dark:bg-gray-800/50 dark:ring-gray-700 dark:placeholder:text-gray-500"})})]})]})})})},p))})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(b,{control:x.control,name:"device_limit",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:u("plan.form.device.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(N,{children:e.jsx(T,{type:"number",min:0,placeholder:u("plan.form.device.placeholder"),className:"rounded-r-none",...p,value:p.value??""})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:u("plan.form.device.unit")})]}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"capacity_limit",render:({field:p})=>e.jsxs(v,{className:"flex-1",children:[e.jsx(y,{children:u("plan.form.capacity.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(N,{children:e.jsx(T,{type:"number",min:0,placeholder:u("plan.form.capacity.placeholder"),className:"rounded-r-none",...p,value:p.value??""})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:u("plan.form.capacity.unit")})]}),e.jsx(k,{})]})})]}),e.jsx(b,{control:x.control,name:"reset_traffic_method",render:({field:p})=>e.jsxs(v,{children:[e.jsx(y,{children:u("plan.form.reset_method.label")}),e.jsxs(J,{value:p.value?.toString()??"null",onValueChange:g=>p.onChange(g=="null"?null:Number(g)),children:[e.jsx(N,{children:e.jsx(W,{children:e.jsx(Z,{placeholder:u("plan.form.reset_method.placeholder")})})}),e.jsx(Y,{children:Fx.map(g=>e.jsx(q,{value:g.value?.toString()??"null",children:u(`plan.form.reset_method.options.${g.label}`)},g.value))})]}),e.jsx(z,{className:"text-xs",children:u("plan.form.reset_method.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:x.control,name:"content",render:({field:p})=>{const[g,j]=m.useState(!1);return e.jsxs(v,{className:"space-y-2",children:[e.jsxs(y,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u("plan.form.content.label"),e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>j(!g),children:g?e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-4 w-4",children:[e.jsx("path",{d:"M10 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z"}),e.jsx("path",{fillRule:"evenodd",d:"M.664 10.59a1.651 1.651 0 010-1.186A10.004 10.004 0 0110 3c4.257 0 7.893 2.66 9.336 6.41.147.381.146.804 0 1.186A10.004 10.004 0 0110 17c-4.257 0-7.893-2.66-9.336-6.41zM14 10a4 4 0 11-8 0 4 4 0 018 0z",clipRule:"evenodd"})]}):e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-4 w-4",children:[e.jsx("path",{fillRule:"evenodd",d:"M3.28 2.22a.75.75 0 00-1.06 1.06l14.5 14.5a.75.75 0 101.06-1.06l-1.745-1.745a10.029 10.029 0 003.3-4.38 1.651 1.651 0 000-1.185A10.004 10.004 0 009.999 3a9.956 9.956 0 00-4.744 1.194L3.28 2.22zM7.752 6.69l1.092 1.092a2.5 2.5 0 013.374 3.373l1.091 1.092a4 4 0 00-5.557-5.557z",clipRule:"evenodd"}),e.jsx("path",{d:"M10.748 13.93l2.523 2.523a9.987 9.987 0 01-3.27.547c-4.258 0-7.894-2.66-9.337-6.41a1.651 1.651 0 010-1.186A10.007 10.007 0 012.839 6.02L6.07 9.252a4 4 0 004.678 4.678z"})]})})}),e.jsx(ce,{side:"top",children:e.jsx("p",{className:"text-xs",children:u(g?"plan.form.content.preview_button.hide":"plan.form.content.preview_button.show")})})]})})]}),e.jsx(je,{children:e.jsxs(xe,{children:[e.jsx(he,{asChild:!0,children:e.jsx(D,{variant:"outline",size:"sm",onClick:()=>{p.onChange(u("plan.form.content.template.content"))},children:u("plan.form.content.template.button")})}),e.jsx(ce,{side:"left",align:"center",children:e.jsx("p",{className:"text-xs",children:u("plan.form.content.template.tooltip")})})]})})]}),e.jsxs("div",{className:`grid gap-4 ${g?"grid-cols-1 lg:grid-cols-2":"grid-cols-1"}`,children:[e.jsx("div",{className:"space-y-2",children:e.jsx(N,{children:e.jsx(Ra,{style:{height:"400px"},value:p.value||"",renderHTML:S=>i.render(S),onChange:({text:S})=>p.onChange(S),config:{view:{menu:!0,md:!0,html:!1},canView:{menu:!0,md:!0,html:!1,fullScreen:!1,hideMenu:!1}},placeholder:u("plan.form.content.placeholder"),className:"rounded-md border"})})}),g&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:u("plan.form.content.preview")}),e.jsx("div",{className:"prose prose-sm dark:prose-invert h-[400px] max-w-none overflow-y-auto rounded-md border p-4",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:i.render(p.value||"")}})})]})]}),e.jsx(z,{className:"text-xs",children:u("plan.form.content.description")}),e.jsx(k,{})]})}})]}),e.jsx(Oe,{className:"mt-6",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("div",{className:"flex-shrink-0",children:a&&e.jsx(b,{control:x.control,name:"force_update",render:({field:p})=>e.jsxs(v,{className:"flex flex-row items-center space-x-2 space-y-0",children:[e.jsx(N,{children:e.jsx(sl,{checked:p.value,onCheckedChange:p.onChange})}),e.jsx("div",{className:"",children:e.jsx(y,{className:"text-sm",children:u("plan.form.force_update.label")})})]})})}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(D,{type:"button",variant:"outline",onClick:C,children:u("plan.form.submit.cancel")}),e.jsx(D,{type:"submit",disabled:c,onClick:()=>{x.handleSubmit(async p=>{o(!0),(await Zc(p)).data&&(A.success(u(a?"plan.form.submit.success.update":"plan.form.submit.success.add")),C(),l()),o(!1)})()},children:u(c?"plan.form.submit.submitting":"plan.form.submit.submit")})]})]})})]})]})})}function zx(){const[s,n]=m.useState({}),[a,r]=m.useState({"drag-handle":!1}),[l,c]=m.useState([]),[o,u]=m.useState([]),[x,i]=m.useState(!1),[d,f]=m.useState({pageSize:20,pageIndex:0}),[w,P]=m.useState([]),{refetch:C}=ie({queryKey:["planList"],queryFn:async()=>{const{data:R}=await Hs();return P(R),R}});m.useEffect(()=>{r({"drag-handle":x}),f({pageSize:x?99999:10,pageIndex:0})},[x]);const p=(R,E)=>{x&&(R.dataTransfer.setData("text/plain",E.toString()),R.currentTarget.classList.add("opacity-50"))},g=(R,E)=>{if(!x)return;R.preventDefault(),R.currentTarget.classList.remove("bg-muted");const F=parseInt(R.dataTransfer.getData("text/plain"));if(F===E)return;const H=[...w],[te]=H.splice(F,1);H.splice(E,0,te),P(H)},j=async()=>{if(!x){i(!0);return}const R=w?.map(E=>E.id);ed(R).then(()=>{A.success("排序保存成功"),i(!1),C()}).finally(()=>{i(!1)})},S=ts({data:w||[],columns:Vx(C),state:{sorting:o,columnVisibility:a,rowSelection:s,columnFilters:l,pagination:d},enableRowSelection:!0,onPaginationChange:f,onRowSelectionChange:n,onSortingChange:u,onColumnFiltersChange:c,onColumnVisibilityChange:r,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}},pageCount:x?1:void 0});return e.jsx(Rx,{refreshData:C,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(xs,{table:S,toolbar:R=>e.jsx(Ix,{table:R,refetch:C,saveOrder:j,isSortMode:x}),draggable:x,onDragStart:p,onDragEnd:R=>R.currentTarget.classList.remove("opacity-50"),onDragOver:R=>{R.preventDefault(),R.currentTarget.classList.add("bg-muted")},onDragLeave:R=>R.currentTarget.classList.remove("bg-muted"),onDrop:g,showPagination:!x}),e.jsx(Ox,{})]})})}function Lx(){const{t:s}=M("subscribe");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("plan.title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("plan.page.description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(zx,{})})]})]})}const Ax=Object.freeze(Object.defineProperty({__proto__:null,default:Lx},Symbol.toStringTag,{value:"Module"})),Ys=[{value:re.PENDING,label:ot[re.PENDING],icon:Uo,color:ct[re.PENDING]},{value:re.PROCESSING,label:ot[re.PROCESSING],icon:xr,color:ct[re.PROCESSING]},{value:re.COMPLETED,label:ot[re.COMPLETED],icon:va,color:ct[re.COMPLETED]},{value:re.CANCELLED,label:ot[re.CANCELLED],icon:hr,color:ct[re.CANCELLED]},{value:re.DISCOUNTED,label:ot[re.DISCOUNTED],icon:va,color:ct[re.DISCOUNTED]}],ut=[{value:me.PENDING,label:wt[me.PENDING],icon:Ko,color:Ct[me.PENDING]},{value:me.PROCESSING,label:wt[me.PROCESSING],icon:xr,color:Ct[me.PROCESSING]},{value:me.VALID,label:wt[me.VALID],icon:va,color:Ct[me.VALID]},{value:me.INVALID,label:wt[me.INVALID],icon:hr,color:Ct[me.INVALID]}];function Pt({column:s,title:n,options:a}){const r=s?.getFacetedUniqueValues(),l=s?.getFilterValue(),c=Array.isArray(l)?new Set(l):l!==void 0?new Set([l]):new Set;return e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(vt,{className:"mr-2 h-4 w-4"}),n,c?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:c.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:c.size>2?e.jsxs(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[c.size," selected"]}):a.filter(o=>c.has(o.value)).map(o=>e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:o.label},o.value))})]})]})}),e.jsx(ms,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Vs,{children:[e.jsx(Us,{placeholder:n}),e.jsxs(Ms,{children:[e.jsx(Ks,{children:"No results found."}),e.jsx(Ge,{children:a.map(o=>{const u=c.has(o.value);return e.jsxs(Ie,{onSelect:()=>{const x=new Set(c);u?x.delete(o.value):x.add(o.value);const i=Array.from(x);s?.setFilterValue(i.length?i:void 0)},children:[e.jsx("div",{className:_("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",u?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(As,{className:_("h-4 w-4")})}),o.icon&&e.jsx(o.icon,{className:`mr-2 h-4 w-4 text-muted-foreground text-${o.color}`}),e.jsx("span",{children:o.label}),r?.get(o.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(o.value)})]},o.value)})}),c.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(at,{}),e.jsx(Ge,{children:e.jsx(Ie,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}const $x=h.object({email:h.string().min(1),plan_id:h.number(),period:h.string(),total_amount:h.number()}),qx={email:"",plan_id:0,total_amount:0,period:""};function tl({refetch:s,trigger:n,defaultValues:a}){const{t:r}=M("order"),[l,c]=m.useState(!1),o=fe({resolver:ye($x),defaultValues:{...qx,...a},mode:"onChange"}),[u,x]=m.useState([]);return m.useEffect(()=>{l&&Hs().then(({data:i})=>{x(i)})},[l]),e.jsxs(ve,{open:l,onOpenChange:c,children:[e.jsx(Ye,{asChild:!0,children:n||e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 space-x-2",children:[e.jsx(Re,{icon:"ion:add"}),e.jsx("div",{children:r("dialog.addOrder")})]})}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:r("dialog.assignOrder")}),e.jsx(ke,{})]}),e.jsxs(Ne,{...o,children:[e.jsx(b,{control:o.control,name:"email",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dialog.fields.userEmail")}),e.jsx(N,{children:e.jsx(T,{placeholder:r("dialog.placeholders.email"),...i})})]})}),e.jsx(b,{control:o.control,name:"plan_id",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dialog.fields.subscriptionPlan")}),e.jsx(N,{children:e.jsxs(J,{value:i.value?i.value?.toString():void 0,onValueChange:d=>i.onChange(parseInt(d)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dialog.placeholders.plan")})}),e.jsx(Y,{children:u.map(d=>e.jsx(q,{value:d.id.toString(),children:d.name},d.id))})]})})]})}),e.jsx(b,{control:o.control,name:"period",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dialog.fields.orderPeriod")}),e.jsx(N,{children:e.jsxs(J,{value:i.value,onValueChange:i.onChange,children:[e.jsx(W,{children:e.jsx(Z,{placeholder:r("dialog.placeholders.period")})}),e.jsx(Y,{children:Object.keys(fu).map(d=>e.jsx(q,{value:d,children:r(`period.${d}`)},d))})]})})]})}),e.jsx(b,{control:o.control,name:"total_amount",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:r("dialog.fields.paymentAmount")}),e.jsx(N,{children:e.jsx(T,{type:"number",placeholder:r("dialog.placeholders.amount"),value:i.value/100,onChange:d=>i.onChange(parseFloat(d.currentTarget.value)*100)})}),e.jsx(k,{})]})}),e.jsxs(Oe,{children:[e.jsx(D,{variant:"outline",onClick:()=>c(!1),children:r("dialog.actions.cancel")}),e.jsx(D,{type:"submit",onClick:()=>{o.handleSubmit(i=>{rd(i).then(({data:d})=>{d&&(s&&s(),o.reset(),c(!1),A.success(r("dialog.messages.addSuccess")))})})()},children:r("dialog.actions.confirm")})]})]})]})]})}function Hx({table:s,refetch:n}){const{t:a}=M("order"),r=s.getState().columnFilters.length>0,l=Object.values(is).filter(x=>typeof x=="number").map(x=>({label:a(`type.${is[x]}`),value:x,color:x===is.NEW?"green-500":x===is.RENEWAL?"blue-500":x===is.UPGRADE?"purple-500":"orange-500"})),c=Object.values(De).map(x=>({label:a(`period.${x}`),value:x,color:x===De.MONTH_PRICE?"slate-500":x===De.QUARTER_PRICE?"cyan-500":x===De.HALF_YEAR_PRICE?"indigo-500":x===De.YEAR_PRICE?"violet-500":x===De.TWO_YEAR_PRICE?"fuchsia-500":x===De.THREE_YEAR_PRICE?"pink-500":x===De.ONETIME_PRICE?"rose-500":"orange-500"})),o=Object.values(re).filter(x=>typeof x=="number").map(x=>({label:a(`status.${re[x]}`),value:x,icon:x===re.PENDING?Ys[0].icon:x===re.PROCESSING?Ys[1].icon:x===re.COMPLETED?Ys[2].icon:x===re.CANCELLED?Ys[3].icon:Ys[4].icon,color:x===re.PENDING?"yellow-500":x===re.PROCESSING?"blue-500":x===re.COMPLETED?"green-500":x===re.CANCELLED?"red-500":"green-500"})),u=Object.values(me).filter(x=>typeof x=="number").map(x=>({label:a(`commission.${me[x]}`),value:x,icon:x===me.PENDING?ut[0].icon:x===me.PROCESSING?ut[1].icon:x===me.VALID?ut[2].icon:ut[3].icon,color:x===me.PENDING?"yellow-500":x===me.PROCESSING?"blue-500":x===me.VALID?"green-500":"red-500"}));return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(tl,{refetch:n}),e.jsx(T,{placeholder:a("search.placeholder"),value:s.getColumn("trade_no")?.getFilterValue()??"",onChange:x=>s.getColumn("trade_no")?.setFilterValue(x.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),e.jsxs("div",{className:"flex flex-wrap gap-x-2",children:[s.getColumn("type")&&e.jsx(Pt,{column:s.getColumn("type"),title:a("table.columns.type"),options:l}),s.getColumn("period")&&e.jsx(Pt,{column:s.getColumn("period"),title:a("table.columns.period"),options:c}),s.getColumn("status")&&e.jsx(Pt,{column:s.getColumn("status"),title:a("table.columns.status"),options:o}),s.getColumn("commission_status")&&e.jsx(Pt,{column:s.getColumn("commission_status"),title:a("table.columns.commissionStatus"),options:u})]}),r&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[a("actions.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]})}function rs({label:s,value:n,className:a,valueClassName:r}){return e.jsxs("div",{className:_("flex items-center py-1.5",a),children:[e.jsx("div",{className:"w-28 shrink-0 text-sm text-muted-foreground",children:s}),e.jsx("div",{className:_("text-sm",r),children:n||"-"})]})}function Ux({status:s}){const{t:n}=M("order"),a={[re.PENDING]:"bg-yellow-100 text-yellow-800 hover:bg-yellow-100",[re.PROCESSING]:"bg-blue-100 text-blue-800 hover:bg-blue-100",[re.CANCELLED]:"bg-red-100 text-red-800 hover:bg-red-100",[re.COMPLETED]:"bg-green-100 text-green-800 hover:bg-green-100",[re.DISCOUNTED]:"bg-gray-100 text-gray-800 hover:bg-gray-100"};return e.jsx(K,{variant:"secondary",className:_("font-medium",a[s]),children:n(`status.${re[s]}`)})}function Kx({id:s,trigger:n}){const[a,r]=m.useState(!1),[l,c]=m.useState(),{t:o}=M("order");return m.useEffect(()=>{(async()=>{if(a){const{data:x}=await td({id:s});c(x)}})()},[a,s]),e.jsxs(ve,{onOpenChange:r,open:a,children:[e.jsx(Ye,{asChild:!0,children:n}),e.jsxs(pe,{className:"max-w-xl",children:[e.jsxs(we,{className:"space-y-2",children:[e.jsx(be,{className:"text-lg font-medium",children:o("dialog.title")}),e.jsx("div",{className:"flex items-center justify-between text-sm",children:e.jsxs("div",{className:"flex items-center space-x-6",children:[e.jsxs("div",{className:"text-muted-foreground",children:[o("table.columns.tradeNo"),":",l?.trade_no]}),l?.status&&e.jsx(Ux,{status:l.status})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:o("dialog.basicInfo")}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(rs,{label:o("dialog.fields.userEmail"),value:l?.user?.email?e.jsxs($s,{to:`/user/manage?email=${l.user.email}`,className:"group inline-flex items-center gap-1 text-primary hover:underline",children:[l.user.email,e.jsx(pr,{className:"h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}):"-"}),e.jsx(rs,{label:o("dialog.fields.orderPeriod"),value:l&&o(`period.${l.period}`)}),e.jsx(rs,{label:o("dialog.fields.subscriptionPlan"),value:l?.plan?.name,valueClassName:"font-medium"}),e.jsx(rs,{label:o("dialog.fields.callbackNo"),value:l?.callback_no,valueClassName:"font-mono text-xs"})]})]}),e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:o("dialog.amountInfo")}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(rs,{label:o("dialog.fields.paymentAmount"),value:Fs(l?.total_amount||0),valueClassName:"font-medium text-primary"}),e.jsx(Se,{className:"my-2"}),e.jsx(rs,{label:o("dialog.fields.balancePayment"),value:Fs(l?.balance_amount||0)}),e.jsx(rs,{label:o("dialog.fields.discountAmount"),value:Fs(l?.discount_amount||0),valueClassName:"text-green-600"}),e.jsx(rs,{label:o("dialog.fields.refundAmount"),value:Fs(l?.refund_amount||0),valueClassName:"text-red-600"}),e.jsx(rs,{label:o("dialog.fields.deductionAmount"),value:Fs(l?.surplus_amount||0)})]})]}),e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:o("dialog.timeInfo")}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(rs,{label:o("dialog.fields.createdAt"),value:_e(l?.created_at),valueClassName:"font-mono text-xs"}),e.jsx(rs,{label:o("dialog.fields.updatedAt"),value:_e(l?.updated_at),valueClassName:"font-mono text-xs"})]})]})]})]})]})}const Bx={[is.NEW]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[is.RENEWAL]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[is.UPGRADE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[is.RESET_FLOW]:{color:"text-slate-700",bgColor:"bg-slate-100/80"}},Gx={[De.MONTH_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.QUARTER_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.HALF_YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.TWO_YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.THREE_YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.ONETIME_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[De.RESET_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"}},Wx=s=>re[s],Yx=s=>me[s],Qx=s=>is[s],Jx=s=>{const{t:n}=M("order");return[{accessorKey:"trade_no",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.tradeNo")}),cell:({row:a})=>{const r=a.original.trade_no,l=r.length>6?`${r.slice(0,3)}...${r.slice(-3)}`:r;return e.jsx("div",{className:"flex items-center",children:e.jsx(Kx,{trigger:e.jsxs(X,{variant:"ghost",size:"sm",className:"flex h-8 items-center gap-1.5 px-2 font-medium text-primary transition-colors hover:bg-primary/10 hover:text-primary/80",children:[e.jsx("span",{className:"font-mono",children:l}),e.jsx(pr,{className:"h-3.5 w-3.5 opacity-70"})]}),id:a.original.id})})},enableSorting:!1,enableHiding:!1},{accessorKey:"type",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.type")}),cell:({row:a})=>{const r=a.getValue("type"),l=Bx[r];return e.jsx(K,{variant:"secondary",className:_("font-medium transition-colors text-nowrap",l.color,l.bgColor,"border border-border/50","hover:bg-slate-200/80"),children:n(`type.${Qx(r)}`)})},enableSorting:!1,enableHiding:!1},{accessorKey:"plan.name",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.plan")}),cell:({row:a})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium text-foreground/90 sm:max-w-72 md:max-w-[31rem]",children:a.original.plan?.name||"-"})}),enableSorting:!1,enableHiding:!1},{accessorKey:"period",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.period")}),cell:({row:a})=>{const r=a.getValue("period"),l=Gx[r];return e.jsx(K,{variant:"secondary",className:_("font-medium transition-colors text-nowrap",l.color,l.bgColor,"hover:bg-opacity-80"),children:n(`period.${r}`)})},enableSorting:!1,enableHiding:!1},{accessorKey:"total_amount",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.amount")}),cell:({row:a})=>{const r=a.getValue("total_amount"),l=typeof r=="number"?(r/100).toFixed(2):"N/A";return e.jsxs("div",{className:"flex items-center font-mono text-foreground/90",children:["¥",l]})},enableSorting:!0,enableHiding:!1},{accessorKey:"status",header:({column:a})=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(L,{column:a,title:n("table.columns.status")}),e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{children:e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground/70 transition-colors hover:text-muted-foreground"})}),e.jsx(ce,{side:"top",className:"max-w-[200px] text-sm",children:n("status.tooltip")})]})})]}),cell:({row:a})=>{const r=Ys.find(l=>l.value===a.getValue("status"));return r?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r.icon&&e.jsx(r.icon,{className:`h-4 w-4 text-${r.color}`}),e.jsx("span",{className:"text-sm font-medium",children:n(`status.${Wx(r.value)}`)})]}),r.value===re.PENDING&&e.jsxs(Cs,{modal:!0,children:[e.jsx(Ss,{asChild:!0,children:e.jsxs(X,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 hover:bg-muted/60",children:[e.jsx(Ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:n("actions.openMenu")})]})}),e.jsxs(ps,{align:"end",className:"w-[140px]",children:[e.jsx(ge,{className:"cursor-pointer",onClick:async()=>{await ad({trade_no:a.original.trade_no}),s()},children:n("actions.markAsPaid")}),e.jsx(ge,{className:"cursor-pointer text-destructive focus:text-destructive",onClick:async()=>{await nd({trade_no:a.original.trade_no}),s()},children:n("actions.cancel")})]})]})]}):null},enableSorting:!0,enableHiding:!1},{accessorKey:"commission_balance",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.commission")}),cell:({row:a})=>{const r=a.getValue("commission_balance"),l=r?(r/100).toFixed(2):"-";return e.jsx("div",{className:"flex items-center font-mono text-foreground/90",children:r?`¥${l}`:"-"})},enableSorting:!0,enableHiding:!1},{accessorKey:"commission_status",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.commissionStatus")}),cell:({row:a})=>{const r=a.original.status,l=a.original.commission_balance,c=ut.find(o=>o.value===a.getValue("commission_status"));return l==0||!c?e.jsx("span",{className:"text-muted-foreground",children:"-"}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c.icon&&e.jsx(c.icon,{className:`h-4 w-4 text-${c.color}`}),e.jsx("span",{className:"text-sm font-medium",children:n(`commission.${Yx(c.value)}`)})]}),c.value===me.PENDING&&r===re.COMPLETED&&e.jsxs(Cs,{modal:!0,children:[e.jsx(Ss,{asChild:!0,children:e.jsxs(X,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 hover:bg-muted/60",children:[e.jsx(Ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:n("actions.openMenu")})]})}),e.jsxs(ps,{align:"end",className:"w-[120px]",children:[e.jsx(ge,{className:"cursor-pointer",onClick:async()=>{await an({trade_no:a.original.trade_no,commission_status:me.PROCESSING}),s()},children:n("commission.PROCESSING")}),e.jsx(ge,{className:"cursor-pointer text-destructive focus:text-destructive",onClick:async()=>{await an({trade_no:a.original.trade_no,commission_status:me.INVALID}),s()},children:n("commission.INVALID")})]})]})]})},enableSorting:!0,enableHiding:!1},{accessorKey:"created_at",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.createdAt")}),cell:({row:a})=>e.jsx("div",{className:"text-nowrap font-mono text-sm text-muted-foreground",children:_e(a.getValue("created_at"),"YYYY/MM/DD HH:mm:ss")}),enableSorting:!0,enableHiding:!1}]};function Zx(){const[s]=fr(),[n,a]=m.useState({}),[r,l]=m.useState({}),[c,o]=m.useState([]),[u,x]=m.useState([]),[i,d]=m.useState({pageIndex:0,pageSize:20});m.useEffect(()=>{const g=Object.entries({user_id:"string",order_id:"string",commission_status:"number",status:"number",commission_balance:"string"}).map(([j,S])=>{const R=s.get(j);return R?{id:j,value:S==="number"?parseInt(R):R}:null}).filter(Boolean);g.length>0&&o(g)},[s]);const{refetch:f,data:w,isLoading:P}=ie({queryKey:["orderList",i,c,u],queryFn:()=>sd({pageSize:i.pageSize,current:i.pageIndex+1,filter:c,sort:u})}),C=ts({data:w?.data??[],columns:Jx(f),state:{sorting:u,columnVisibility:r,rowSelection:n,columnFilters:c,pagination:i},rowCount:w?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:a,onSortingChange:x,onColumnFiltersChange:o,onColumnVisibilityChange:l,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),onPaginationChange:d,getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(xs,{table:C,toolbar:e.jsx(Hx,{table:C,refetch:f}),showPagination:!0})}function Xx(){const{t:s}=M("order");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"text-muted-foreground mt-2",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Zx,{})})]})]})}const eh=Object.freeze(Object.defineProperty({__proto__:null,default:Xx},Symbol.toStringTag,{value:"Module"}));function sh({column:s,title:n,options:a}){const r=s?.getFacetedUniqueValues(),l=new Set(s?.getFilterValue());return e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(vt,{className:"mr-2 h-4 w-4"}),n,l?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:l.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:l.size>2?e.jsxs(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[l.size," selected"]}):a.filter(c=>l.has(c.value)).map(c=>e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:c.label},c.value))})]})]})}),e.jsx(ms,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Vs,{children:[e.jsx(Us,{placeholder:n}),e.jsxs(Ms,{children:[e.jsx(Ks,{children:"No results found."}),e.jsx(Ge,{children:a.map(c=>{const o=l.has(c.value);return e.jsxs(Ie,{onSelect:()=>{o?l.delete(c.value):l.add(c.value);const u=Array.from(l);s?.setFilterValue(u.length?u:void 0)},children:[e.jsx("div",{className:_("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",o?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(As,{className:_("h-4 w-4")})}),c.icon&&e.jsx(c.icon,{className:`mr-2 h-4 w-4 text-muted-foreground text-${c.color}`}),e.jsx("span",{children:c.label}),r?.get(c.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(c.value)})]},c.value)})}),l.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(at,{}),e.jsx(Ge,{children:e.jsx(Ie,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}const th=h.object({id:h.coerce.number().nullable().optional(),name:h.string().min(1,"请输入优惠券名称"),code:h.string().nullable(),type:h.coerce.number(),value:h.coerce.number(),started_at:h.coerce.number(),ended_at:h.coerce.number(),limit_use:h.union([h.string(),h.number()]).nullable(),limit_use_with_user:h.union([h.string(),h.number()]).nullable(),generate_count:h.coerce.number().nullable().optional(),limit_plan_ids:h.array(h.coerce.number()).default([]).nullable(),limit_period:h.array(h.nativeEnum(xt)).default([]).nullable()}).refine(s=>s.ended_at>s.started_at,{message:"结束时间必须晚于开始时间",path:["ended_at"]}),xn={name:"",code:null,type:Ue.AMOUNT,value:0,started_at:Math.floor(Date.now()/1e3),ended_at:Math.floor(Date.now()/1e3)+7*24*60*60,limit_use:null,limit_use_with_user:null,limit_plan_ids:[],limit_period:[],generate_count:null};function al({defaultValues:s,refetch:n,type:a="create",dialogTrigger:r=null,open:l,onOpenChange:c}){const{t:o}=M("coupon"),[u,x]=m.useState(!1),i=l??u,d=c??x,[f,w]=m.useState([]),P=fe({resolver:ye(th),defaultValues:s||xn});m.useEffect(()=>{s&&P.reset(s)},[s,P]),m.useEffect(()=>{Hs().then(({data:j})=>w(j))},[]);const C=j=>{if(!j)return;const S=(R,E)=>{const F=new Date(E*1e3);return R.setHours(F.getHours(),F.getMinutes(),F.getSeconds()),Math.floor(R.getTime()/1e3)};j.from&&P.setValue("started_at",S(j.from,P.watch("started_at"))),j.to&&P.setValue("ended_at",S(j.to,P.watch("ended_at")))},p=async j=>{const S=await id(j);if(j.generate_count&&S){const R=new Blob([S],{type:"text/csv;charset=utf-8;"}),E=document.createElement("a");E.href=window.URL.createObjectURL(R),E.download=`coupons_${new Date().getTime()}.csv`,E.click(),window.URL.revokeObjectURL(E.href)}d(!1),a==="create"&&P.reset(xn),n()},g=(j,S)=>e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:S}),e.jsx(T,{type:"datetime-local",step:"1",value:_e(P.watch(j),"YYYY-MM-DDTHH:mm:ss"),onChange:R=>{const E=new Date(R.target.value);P.setValue(j,Math.floor(E.getTime()/1e3))},className:"h-8 [&::-webkit-calendar-picker-indicator]:hidden"})]});return e.jsxs(ve,{open:i,onOpenChange:d,children:[r&&e.jsx(Ye,{asChild:!0,children:r}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsx(we,{children:e.jsx(be,{children:o(a==="create"?"form.add":"form.edit")})}),e.jsx(Ne,{...P,children:e.jsxs("form",{onSubmit:P.handleSubmit(p),className:"space-y-4",children:[e.jsx(b,{control:P.control,name:"name",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.name.label")}),e.jsx(T,{placeholder:o("form.name.placeholder"),...j}),e.jsx(k,{})]})}),a==="create"&&e.jsx(b,{control:P.control,name:"generate_count",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.generateCount.label")}),e.jsx(T,{type:"number",min:0,placeholder:o("form.generateCount.placeholder"),...j,value:j.value===void 0?"":j.value,onChange:S=>j.onChange(S.target.value===""?"":parseInt(S.target.value)),className:"h-9"}),e.jsx(z,{className:"text-xs",children:o("form.generateCount.description")}),e.jsx(k,{})]})}),(!P.watch("generate_count")||P.watch("generate_count")==null)&&e.jsx(b,{control:P.control,name:"code",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.code.label")}),e.jsx(T,{placeholder:o("form.code.placeholder"),...j,className:"h-9"}),e.jsx(z,{className:"text-xs",children:o("form.code.description")}),e.jsx(k,{})]})}),e.jsxs(v,{children:[e.jsx(y,{children:o("form.type.label")}),e.jsxs("div",{className:"flex",children:[e.jsx(b,{control:P.control,name:"type",render:({field:j})=>e.jsxs(J,{value:j.value.toString(),onValueChange:S=>{const R=j.value,E=parseInt(S);j.onChange(E);const F=P.getValues("value");F&&(R===Ue.AMOUNT&&E===Ue.PERCENTAGE?P.setValue("value",F/100):R===Ue.PERCENTAGE&&E===Ue.AMOUNT&&P.setValue("value",F*100))},children:[e.jsx(W,{className:"flex-[1.2] rounded-r-none border-r-0 focus:z-10",children:e.jsx(Z,{placeholder:o("form.type.placeholder")})}),e.jsx(Y,{children:Object.entries(gu).map(([S,R])=>e.jsx(q,{value:S,children:o(`table.toolbar.types.${S}`)},S))})]})}),e.jsx(b,{control:P.control,name:"value",render:({field:j})=>{const S=j.value==null?"":P.watch("type")===Ue.AMOUNT&&typeof j.value=="number"?(j.value/100).toString():j.value.toString();return e.jsx(T,{type:"number",placeholder:o("form.value.placeholder"),...j,value:S,onChange:R=>{const E=R.target.value;if(E===""){j.onChange("");return}const F=parseFloat(E);isNaN(F)||j.onChange(P.watch("type")===Ue.AMOUNT?Math.round(F*100):F)},step:"any",min:0,className:"flex-[2] rounded-none border-x-0 text-left"})}}),e.jsx("div",{className:"flex min-w-[40px] items-center justify-center rounded-md rounded-l-none border border-l-0 border-input bg-muted/50 px-3 font-medium text-muted-foreground",children:e.jsx("span",{children:P.watch("type")==Ue.AMOUNT?"¥":"%"})})]})]}),e.jsxs(v,{children:[e.jsx(y,{children:o("form.validity.label")}),e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(D,{variant:"outline",className:_("w-full justify-start text-left font-normal",!P.watch("started_at")&&"text-muted-foreground"),children:[e.jsx(jt,{className:"mr-2 h-4 w-4"}),_e(P.watch("started_at"),"YYYY-MM-DD HH:mm:ss")," ",o("form.validity.to")," ",_e(P.watch("ended_at"),"YYYY-MM-DD HH:mm:ss")]})}),e.jsxs(ms,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"border-b border-border",children:e.jsx(Bs,{mode:"range",selected:{from:new Date(P.watch("started_at")*1e3),to:new Date(P.watch("ended_at")*1e3)},onSelect:C,numberOfMonths:2})}),e.jsx("div",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-4",children:[g("started_at",o("table.validity.startTime")),e.jsx("div",{className:"mt-6 text-sm text-muted-foreground",children:o("form.validity.to")}),g("ended_at",o("table.validity.endTime"))]})})]})]}),e.jsx(k,{})]}),e.jsx(b,{control:P.control,name:"limit_use",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.limitUse.label")}),e.jsx(T,{type:"number",min:0,placeholder:o("form.limitUse.placeholder"),...j,value:j.value===null?"":j.value,onChange:S=>j.onChange(S.target.value===""?null:parseInt(S.target.value)),className:"h-9"}),e.jsx(z,{className:"text-xs",children:o("form.limitUse.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:P.control,name:"limit_use_with_user",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.limitUseWithUser.label")}),e.jsx(T,{type:"number",min:0,placeholder:o("form.limitUseWithUser.placeholder"),...j,value:j.value===null?"":j.value,onChange:S=>j.onChange(S.target.value===""?null:parseInt(S.target.value)),className:"h-9"}),e.jsx(z,{className:"text-xs",children:o("form.limitUseWithUser.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:P.control,name:"limit_period",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.limitPeriod.label")}),e.jsx(st,{options:Object.entries(xt).filter(([S])=>isNaN(Number(S))).map(([S,R])=>({label:o(`coupon:period.${R}`),value:S})),onChange:S=>{if(S.length===0){j.onChange([]);return}const R=S.map(E=>xt[E.value]);j.onChange(R)},value:(j.value||[]).map(S=>({label:o(`coupon:period.${S}`),value:Object.entries(xt).find(([R,E])=>E===S)?.[0]||""})),placeholder:o("form.limitPeriod.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:o("form.limitPeriod.empty")})}),e.jsx(z,{className:"text-xs",children:o("form.limitPeriod.description")}),e.jsx(k,{})]})}),e.jsx(b,{control:P.control,name:"limit_plan_ids",render:({field:j})=>e.jsxs(v,{children:[e.jsx(y,{children:o("form.limitPlan.label")}),e.jsx(st,{options:f?.map(S=>({label:S.name,value:S.id.toString()}))||[],onChange:S=>j.onChange(S.map(R=>Number(R.value))),value:(f||[]).filter(S=>(j.value||[]).includes(S.id)).map(S=>({label:S.name,value:S.id.toString()})),placeholder:o("form.limitPlan.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:o("form.limitPlan.empty")})}),e.jsx(k,{})]})}),e.jsx(Oe,{children:e.jsx(D,{type:"submit",disabled:P.formState.isSubmitting,children:P.formState.isSubmitting?o("form.submit.saving"):o("form.submit.save")})})]})})]})]})}function ah({table:s,refetch:n}){const a=s.getState().columnFilters.length>0,{t:r}=M("coupon");return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(al,{refetch:n,dialogTrigger:e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 space-x-2",children:[e.jsx(Re,{icon:"ion:add"}),e.jsx("div",{children:r("form.add")})]})}),e.jsx(T,{placeholder:r("table.toolbar.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:l=>s.getColumn("name")?.setFilterValue(l.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),s.getColumn("type")&&e.jsx(sh,{column:s.getColumn("type"),title:r("table.toolbar.type"),options:[{value:Ue.AMOUNT,label:r(`table.toolbar.types.${Ue.AMOUNT}`)},{value:Ue.PERCENTAGE,label:r(`table.toolbar.types.${Ue.PERCENTAGE}`)}]}),a&&e.jsxs(D,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[r("table.toolbar.reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]})]})}const nl=m.createContext(void 0);function nh({children:s,refetch:n}){const[a,r]=m.useState(!1),[l,c]=m.useState(null),o=x=>{c(x),r(!0)},u=()=>{r(!1),c(null)};return e.jsxs(nl.Provider,{value:{isOpen:a,currentCoupon:l,openEdit:o,closeEdit:u},children:[s,l&&e.jsx(al,{defaultValues:l,refetch:n,type:"edit",open:a,onOpenChange:r})]})}function rh(){const s=m.useContext(nl);if(s===void 0)throw new Error("useCouponEdit must be used within a CouponEditProvider");return s}const lh=s=>{const{t:n}=M("coupon");return[{accessorKey:"id",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.id")}),cell:({row:a})=>e.jsx(K,{children:a.original.id}),enableSorting:!0},{accessorKey:"show",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.show")}),cell:({row:a})=>e.jsx(Q,{defaultChecked:a.original.show,onCheckedChange:r=>{cd({id:a.original.id,show:r}).then(({data:l})=>!l&&s())}}),enableSorting:!1},{accessorKey:"name",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.name")}),cell:({row:a})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{children:a.original.name})}),enableSorting:!1,size:800},{accessorKey:"type",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.type")}),cell:({row:a})=>e.jsx(K,{variant:"outline",children:n(`table.toolbar.types.${a.original.type}`)}),enableSorting:!0},{accessorKey:"code",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.code")}),cell:({row:a})=>e.jsx(K,{variant:"secondary",children:a.original.code}),enableSorting:!0},{accessorKey:"limit_use",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.limitUse")}),cell:({row:a})=>e.jsx(K,{variant:"outline",children:a.original.limit_use===null?n("table.validity.unlimited"):a.original.limit_use}),enableSorting:!0},{accessorKey:"limit_use_with_user",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.limitUseWithUser")}),cell:({row:a})=>e.jsx(K,{variant:"outline",children:a.original.limit_use_with_user===null?n("table.validity.noLimit"):a.original.limit_use_with_user}),enableSorting:!0},{accessorKey:"#",header:({column:a})=>e.jsx(L,{column:a,title:n("table.columns.validity")}),cell:({row:a})=>{const[r,l]=m.useState(!1),c=Date.now(),o=a.original.started_at*1e3,u=a.original.ended_at*1e3,x=c>u,i=ce.jsx(L,{className:"justify-end",column:a,title:n("table.columns.actions")}),cell:({row:a})=>{const{openEdit:r}=rh();return e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",onClick:()=>r(a.original),children:[e.jsx(qs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("table.actions.edit")})]}),e.jsx(We,{title:n("table.actions.deleteConfirm.title"),description:n("table.actions.deleteConfirm.description"),confirmText:n("table.actions.deleteConfirm.confirmText"),variant:"destructive",onConfirm:async()=>{od({id:a.original.id}).then(({data:l})=>{l&&(A.success("删除成功"),s())})},children:e.jsxs(D,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(os,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("table.actions.delete")})]})})]})}}]};function ih(){const[s,n]=m.useState({}),[a,r]=m.useState({}),[l,c]=m.useState([]),[o,u]=m.useState([]),[x,i]=m.useState({pageIndex:0,pageSize:20}),{refetch:d,data:f}=ie({queryKey:["couponList",x,l,o],queryFn:()=>ld({pageSize:x.pageSize,current:x.pageIndex+1,filter:l,sort:o})}),w=ts({data:f?.data??[],columns:lh(d),state:{sorting:o,columnVisibility:a,rowSelection:s,columnFilters:l,pagination:x},pageCount:Math.ceil((f?.total??0)/x.pageSize),rowCount:f?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:u,onColumnFiltersChange:c,onColumnVisibilityChange:r,onPaginationChange:i,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(nh,{refetch:d,children:e.jsx("div",{className:"space-y-4",children:e.jsx(xs,{table:w,toolbar:e.jsx(ah,{table:w,refetch:d})})})})}function oh(){const{t:s}=M("coupon");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"text-muted-foreground mt-2",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(ih,{})})]})]})}const ch=Object.freeze(Object.defineProperty({__proto__:null,default:oh},Symbol.toStringTag,{value:"Module"})),dh=1,uh=1e6;let ma=0;function mh(){return ma=(ma+1)%Number.MAX_SAFE_INTEGER,ma.toString()}const xa=new Map,hn=s=>{if(xa.has(s))return;const n=setTimeout(()=>{xa.delete(s),ht({type:"REMOVE_TOAST",toastId:s})},uh);xa.set(s,n)},xh=(s,n)=>{switch(n.type){case"ADD_TOAST":return{...s,toasts:[n.toast,...s.toasts].slice(0,dh)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(a=>a.id===n.toast.id?{...a,...n.toast}:a)};case"DISMISS_TOAST":{const{toastId:a}=n;return a?hn(a):s.toasts.forEach(r=>{hn(r.id)}),{...s,toasts:s.toasts.map(r=>r.id===a||a===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return n.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(a=>a.id!==n.toastId)}}},Rt=[];let It={toasts:[]};function ht(s){It=xh(It,s),Rt.forEach(n=>{n(It)})}function hh({...s}){const n=mh(),a=l=>ht({type:"UPDATE_TOAST",toast:{...l,id:n}}),r=()=>ht({type:"DISMISS_TOAST",toastId:n});return ht({type:"ADD_TOAST",toast:{...s,id:n,open:!0,onOpenChange:l=>{l||r()}}}),{id:n,dismiss:r,update:a}}function rl(){const[s,n]=m.useState(It);return m.useEffect(()=>(Rt.push(n),()=>{const a=Rt.indexOf(n);a>-1&&Rt.splice(a,1)}),[s]),{...s,toast:hh,dismiss:a=>ht({type:"DISMISS_TOAST",toastId:a})}}function ph({open:s,onOpenChange:n,table:a}){const{t:r}=M("user"),{toast:l}=rl(),[c,o]=m.useState(!1),[u,x]=m.useState(""),[i,d]=m.useState(""),f=async()=>{if(!u||!i){l({title:r("messages.error"),description:r("messages.send_mail.required_fields"),variant:"destructive"});return}try{o(!0),await Lt.sendMail({subject:u,content:i,filter:a.getState().columnFilters,sort:a.getState().sorting[0]?.id,sort_type:a.getState().sorting[0]?.desc?"DESC":"ASC"}),l({title:r("messages.success"),description:r("messages.send_mail.success")}),n(!1),x(""),d("")}catch{l({title:r("messages.error"),description:r("messages.send_mail.failed"),variant:"destructive"})}finally{o(!1)}};return e.jsx(ve,{open:s,onOpenChange:n,children:e.jsxs(pe,{className:"sm:max-w-[500px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:r("send_mail.title")}),e.jsx(ke,{children:r("send_mail.description")})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[e.jsx("label",{htmlFor:"subject",className:"text-right",children:r("send_mail.subject")}),e.jsx(T,{id:"subject",value:u,onChange:w=>x(w.target.value),className:"col-span-3"})]}),e.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[e.jsx("label",{htmlFor:"content",className:"text-right",children:r("send_mail.content")}),e.jsx(bs,{id:"content",value:i,onChange:w=>d(w.target.value),className:"col-span-3",rows:6})]})]}),e.jsx(Oe,{children:e.jsx(X,{type:"submit",onClick:f,disabled:c,children:r(c?"send_mail.sending":"send_mail.send")})})]})})}const fh=h.object({email_prefix:h.string().optional(),email_suffix:h.string().min(1),password:h.string().optional(),expired_at:h.number().optional().nullable(),plan_id:h.number().nullable(),generate_count:h.number().optional().nullable()}).refine(s=>s.generate_count===null?s.email_prefix!==void 0&&s.email_prefix!=="":!0,{message:"Email prefix is required when generate_count is null",path:["email_prefix"]}),gh={email_prefix:"",email_suffix:"",password:"",expired_at:null,plan_id:null,generate_count:void 0};function jh({refetch:s}){const{t:n}=M("user"),[a,r]=m.useState(!1),l=fe({resolver:ye(fh),defaultValues:gh,mode:"onChange"}),[c,o]=m.useState([]);return m.useEffect(()=>{a&&Hs().then(({data:u})=>{u&&o(u)})},[a]),e.jsxs(ve,{open:a,onOpenChange:r,children:[e.jsx(Ye,{asChild:!0,children:e.jsxs(X,{size:"sm",variant:"outline",className:"space-x-2 gap-0",children:[e.jsx(Re,{icon:"ion:add"}),e.jsx("div",{children:n("generate.button")})]})}),e.jsxs(pe,{className:"sm:max-w-[425px]",children:[e.jsxs(we,{children:[e.jsx(be,{children:n("generate.title")}),e.jsx(ke,{})]}),e.jsxs(Ne,{...l,children:[e.jsxs(v,{children:[e.jsx(y,{children:n("generate.form.email")}),e.jsxs("div",{className:"flex",children:[!l.watch("generate_count")&&e.jsx(b,{control:l.control,name:"email_prefix",render:({field:u})=>e.jsx(T,{className:"flex-[5] rounded-r-none",placeholder:n("generate.form.email_prefix"),...u})}),e.jsx("div",{className:`z-[-1] border border-r-0 border-input px-3 py-1 shadow-sm ${l.watch("generate_count")?"rounded-l-md":"border-l-0"}`,children:"@"}),e.jsx(b,{control:l.control,name:"email_suffix",render:({field:u})=>e.jsx(T,{className:"flex-[4] rounded-l-none",placeholder:n("generate.form.email_domain"),...u})})]})]}),e.jsx(b,{control:l.control,name:"password",render:({field:u})=>e.jsxs(v,{children:[e.jsx(y,{children:n("generate.form.password")}),e.jsx(T,{placeholder:n("generate.form.password_placeholder"),...u}),e.jsx(k,{})]})}),e.jsx(b,{control:l.control,name:"expired_at",render:({field:u})=>e.jsxs(v,{className:"flex flex-col",children:[e.jsx(y,{children:n("generate.form.expire_time")}),e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsx(N,{children:e.jsxs(X,{variant:"outline",className:_("w-full pl-3 text-left font-normal",!u.value&&"text-muted-foreground"),children:[u.value?_e(u.value):e.jsx("span",{children:n("generate.form.expire_time_placeholder")}),e.jsx(jt,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),e.jsxs(ms,{className:"flex w-auto flex-col space-y-2 p-2",children:[e.jsx(Go,{asChild:!0,children:e.jsx(X,{variant:"outline",className:"w-full",onClick:()=>{u.onChange(null)},children:n("generate.form.permanent")})}),e.jsx("div",{className:"rounded-md border",children:e.jsx(Bs,{mode:"single",selected:u.value?new Date(u.value*1e3):void 0,onSelect:x=>{x&&u.onChange(x?.getTime()/1e3)}})})]})]})]})}),e.jsx(b,{control:l.control,name:"plan_id",render:({field:u})=>e.jsxs(v,{children:[e.jsx(y,{children:n("generate.form.subscription")}),e.jsx(N,{children:e.jsxs(J,{value:u.value?u.value.toString():"null",onValueChange:x=>u.onChange(x==="null"?null:parseInt(x)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:n("generate.form.subscription_none")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"null",children:n("generate.form.subscription_none")}),c.map(x=>e.jsx(q,{value:x.id.toString(),children:x.name},x.id))]})]})})]})}),!l.watch("email_prefix")&&e.jsx(b,{control:l.control,name:"generate_count",render:({field:u})=>e.jsxs(v,{children:[e.jsx(y,{children:n("generate.form.generate_count")}),e.jsx(T,{type:"number",placeholder:n("generate.form.generate_count_placeholder"),value:u.value||"",onChange:x=>u.onChange(x.target.value?parseInt(x.target.value):null)})]})})]}),e.jsxs(Oe,{children:[e.jsx(X,{variant:"outline",onClick:()=>r(!1),children:n("generate.form.cancel")}),e.jsx(X,{onClick:()=>l.handleSubmit(u=>{xd(u).then(({data:x})=>{x&&(A.success(n("generate.form.success")),l.reset(),s(),r(!1))})})(),children:n("generate.form.submit")})]})]})]})}const ll=Nn,il=_n,vh=wn,ol=m.forwardRef(({className:s,...n},a)=>e.jsx($t,{className:_("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...n,ref:a}));ol.displayName=$t.displayName;const bh=Ls("fixed overflow-y-scroll z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-md",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-md"}},defaultVariants:{side:"right"}}),$a=m.forwardRef(({side:s="right",className:n,children:a,...r},l)=>e.jsxs(vh,{children:[e.jsx(ol,{}),e.jsxs(qt,{ref:l,className:_(bh({side:s}),n),...r,children:[e.jsxs(Sa,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e.jsx(Xe,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),a]})]}));$a.displayName=qt.displayName;const qa=({className:s,...n})=>e.jsx("div",{className:_("flex flex-col space-y-2 text-center sm:text-left",s),...n});qa.displayName="SheetHeader";const cl=({className:s,...n})=>e.jsx("div",{className:_("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...n});cl.displayName="SheetFooter";const Ha=m.forwardRef(({className:s,...n},a)=>e.jsx(Ht,{ref:a,className:_("text-lg font-semibold text-foreground",s),...n}));Ha.displayName=Ht.displayName;const Ua=m.forwardRef(({className:s,...n},a)=>e.jsx(Ut,{ref:a,className:_("text-sm text-muted-foreground",s),...n}));Ua.displayName=Ut.displayName;function yh({table:s,refetch:n,permissionGroups:a=[],subscriptionPlans:r=[]}){const{t:l}=M("user"),{toast:c}=rl(),o=s.getState().columnFilters.length>0,[u,x]=m.useState([]),[i,d]=m.useState(!1),[f,w]=m.useState(!1),[P,C]=m.useState(!1),[p,g]=m.useState(!1),j=async()=>{try{const G=await Lt.dumpCSV({filter:s.getState().columnFilters,sort:s.getState().sorting[0]?.id,sort_type:s.getState().sorting[0]?.desc?"DESC":"ASC"}),ae=G;console.log(G);const $=new Blob([ae],{type:"text/csv;charset=utf-8;"}),I=window.URL.createObjectURL($),B=document.createElement("a");B.href=I,B.setAttribute("download",`users_${new Date().toISOString()}.csv`),document.body.appendChild(B),B.click(),B.remove(),window.URL.revokeObjectURL(I),c({title:l("messages.success"),description:l("messages.export.success")})}catch{c({title:l("messages.error"),description:l("messages.export.failed"),variant:"destructive"})}},S=async()=>{try{g(!0),await Lt.batchBan({filter:s.getState().columnFilters,sort:s.getState().sorting[0]?.id,sort_type:s.getState().sorting[0]?.desc?"DESC":"ASC"}),c({title:l("messages.success"),description:l("messages.batch_ban.success")}),n()}catch{c({title:l("messages.error"),description:l("messages.batch_ban.failed"),variant:"destructive"})}finally{g(!1),C(!1)}},R=[{label:l("filter.fields.email"),value:"email",type:"text",operators:[{label:l("filter.operators.contains"),value:"contains"},{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.id"),value:"id",type:"number",operators:[{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.plan_id"),value:"plan_id",type:"select",operators:[{label:l("filter.operators.eq"),value:"eq"}],useOptions:!0},{label:l("filter.fields.transfer_enable"),value:"transfer_enable",type:"number",unit:"GB",operators:[{label:l("filter.operators.gt"),value:"gt"},{label:l("filter.operators.lt"),value:"lt"},{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.total_used"),value:"total_used",type:"number",unit:"GB",operators:[{label:l("filter.operators.gt"),value:"gt"},{label:l("filter.operators.lt"),value:"lt"},{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.online_count"),value:"online_count",type:"number",operators:[{label:l("filter.operators.eq"),value:"eq"},{label:l("filter.operators.gt"),value:"gt"},{label:l("filter.operators.lt"),value:"lt"}]},{label:l("filter.fields.expired_at"),value:"expired_at",type:"date",operators:[{label:l("filter.operators.lt"),value:"lt"},{label:l("filter.operators.gt"),value:"gt"},{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.uuid"),value:"uuid",type:"text",operators:[{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.token"),value:"token",type:"text",operators:[{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.banned"),value:"banned",type:"select",operators:[{label:l("filter.operators.eq"),value:"eq"}],options:[{label:l("filter.status.normal"),value:"0"},{label:l("filter.status.banned"),value:"1"}]},{label:l("filter.fields.remark"),value:"remarks",type:"text",operators:[{label:l("filter.operators.contains"),value:"contains"},{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.inviter_email"),value:"invite_user.email",type:"text",operators:[{label:l("filter.operators.contains"),value:"contains"},{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.invite_user_id"),value:"invite_user_id",type:"number",operators:[{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.is_admin"),value:"is_admin",type:"boolean",operators:[{label:l("filter.operators.eq"),value:"eq"}]},{label:l("filter.fields.is_staff"),value:"is_staff",type:"boolean",operators:[{label:l("filter.operators.eq"),value:"eq"}]}],E=G=>G*1024*1024*1024,F=G=>G/(1024*1024*1024),H=()=>{x([...u,{field:"",operator:"",value:""}])},te=G=>{x(u.filter((ae,$)=>$!==G))},O=(G,ae,$)=>{const I=[...u];if(I[G]={...I[G],[ae]:$},ae==="field"){const B=R.find(ne=>ne.value===$);B&&(I[G].operator=B.operators[0].value,I[G].value=B.type==="boolean"?!1:"")}x(I)},se=(G,ae)=>{const $=R.find(I=>I.value===G.field);if(!$)return null;switch($.type){case"text":return e.jsx(T,{placeholder:l("filter.sheet.value"),value:G.value,onChange:I=>O(ae,"value",I.target.value)});case"number":return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(T,{type:"number",placeholder:l("filter.sheet.value_number",{unit:$.unit}),value:$.unit==="GB"?F(G.value||0):G.value,onChange:I=>{const B=Number(I.target.value);O(ae,"value",$.unit==="GB"?E(B):B)}}),$.unit&&e.jsx("span",{className:"text-sm text-muted-foreground",children:$.unit})]});case"date":return e.jsx(Bs,{mode:"single",selected:G.value,onSelect:I=>O(ae,"value",I),className:"rounded-md border"});case"select":return e.jsxs(J,{value:G.value,onValueChange:I=>O(ae,"value",I),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:l("filter.sheet.value")})}),e.jsx(Y,{children:$.useOptions?r.map(I=>e.jsx(q,{value:I.value.toString(),children:I.label},I.value)):$.options?.map(I=>e.jsx(q,{value:I.value.toString(),children:I.label},I.value))})]});case"boolean":return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Q,{checked:G.value,onCheckedChange:I=>O(ae,"value",I)}),e.jsx(Ot,{children:G.value?l("filter.boolean.true"):l("filter.boolean.false")})]});default:return null}},He=()=>{const G=u.filter(ae=>ae.field&&ae.operator&&ae.value!=="").map(ae=>{const $=R.find(B=>B.value===ae.field);let I=ae.value;return ae.operator==="contains"?{id:ae.field,value:I}:($?.type==="date"&&I instanceof Date&&(I=Math.floor(I.getTime()/1e3)),$?.type==="boolean"&&(I=I?1:0),{id:ae.field,value:`${ae.operator}:${I}`})});s.setColumnFilters(G),d(!1)};return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-1 flex-wrap items-center gap-2",children:[e.jsx(jh,{refetch:n}),e.jsx(T,{placeholder:l("filter.email_search"),value:s.getColumn("email")?.getFilterValue()??"",onChange:G=>s.getColumn("email")?.setFilterValue(G.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),e.jsxs(ll,{open:i,onOpenChange:d,children:[e.jsx(il,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(Wo,{className:"mr-2 h-4 w-4"}),l("filter.advanced"),u.length>0&&e.jsx(K,{variant:"secondary",className:"ml-2 rounded-sm px-1",children:u.length})]})}),e.jsxs($a,{className:"w-[400px] sm:w-[540px]",children:[e.jsxs(qa,{children:[e.jsx(Ha,{children:l("filter.sheet.title")}),e.jsx(Ua,{children:l("filter.sheet.description")})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-medium",children:l("filter.sheet.conditions")}),e.jsx(D,{variant:"outline",size:"sm",onClick:H,children:l("filter.sheet.add")})]}),e.jsx(zs,{className:"h-[calc(100vh-280px)] pr-4",children:e.jsx("div",{className:"space-y-4",children:u.map((G,ae)=>e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ot,{children:l("filter.sheet.condition",{number:ae+1})}),e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>te(ae),children:e.jsx(Xe,{className:"h-4 w-4"})})]}),e.jsxs(J,{value:G.field,onValueChange:$=>O(ae,"field",$),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:l("filter.sheet.field")})}),e.jsx(Y,{children:R.map($=>e.jsx(q,{value:$.value,children:$.label},$.value))})]}),G.field&&e.jsxs(J,{value:G.operator,onValueChange:$=>O(ae,"operator",$),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:l("filter.sheet.operator")})}),e.jsx(Y,{children:R.find($=>$.value===G.field)?.operators.map($=>e.jsx(q,{value:$.value,children:$.label},$.value))})]}),G.field&&G.operator&&se(G,ae)]},ae))})}),e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(D,{variant:"outline",onClick:()=>{x([]),d(!1)},children:l("filter.sheet.reset")}),e.jsx(D,{onClick:He,children:l("filter.sheet.apply")})]})]})]})]}),o&&e.jsxs(D,{variant:"ghost",onClick:()=>{s.resetColumnFilters(),x([])},className:"h-8 px-2 lg:px-3",children:[l("reset"),e.jsx(Xe,{className:"ml-2 h-4 w-4"})]}),e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsx(D,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:l("actions.title")})}),e.jsxs(ps,{children:[e.jsx(ge,{onClick:()=>w(!0),children:l("actions.send_email")}),e.jsx(ge,{onClick:j,children:l("actions.export_csv")}),e.jsx(et,{}),e.jsx(ge,{onClick:()=>C(!0),className:"text-red-600 focus:text-red-600",children:l("actions.batch_ban")})]})]})]}),e.jsx(ph,{open:f,onOpenChange:w,table:s}),e.jsx(za,{open:P,onOpenChange:C,children:e.jsxs(Qt,{children:[e.jsxs(Jt,{children:[e.jsx(Xt,{children:l("actions.confirm_ban.title")}),e.jsx(ea,{children:l(o?"actions.confirm_ban.filtered_description":"actions.confirm_ban.all_description")})]}),e.jsxs(Zt,{children:[e.jsx(ta,{disabled:p,children:l("actions.confirm_ban.cancel")}),e.jsx(sa,{onClick:S,disabled:p,className:"bg-red-600 hover:bg-red-700 focus:ring-red-600",children:l(p?"actions.confirm_ban.banning":"actions.confirm_ban.confirm")})]})]})})]})}const Nh=h.object({id:h.number(),email:h.string().email(),invite_user_email:h.string().email().nullable().optional(),password:h.string().optional().nullable(),balance:h.coerce.number(),commission_balance:h.coerce.number(),u:h.number(),d:h.number(),transfer_enable:h.number(),expired_at:h.number().nullable(),plan_id:h.number().nullable(),banned:h.number(),commission_type:h.number(),commission_rate:h.number().nullable(),discount:h.number().nullable(),speed_limit:h.number().nullable(),device_limit:h.number().nullable(),is_admin:h.number(),is_staff:h.number(),remarks:h.string().nullable()}),dl=m.createContext(void 0);function _h({children:s,defaultValues:n,open:a,onOpenChange:r}){const[l,c]=m.useState(!1),[o,u]=m.useState(!1),[x,i]=m.useState([]),d=fe({resolver:ye(Nh),defaultValues:n,mode:"onChange"});m.useEffect(()=>{a!==void 0&&c(a)},[a]);const f=w=>{c(w),r?.(w)};return e.jsx(dl.Provider,{value:{form:d,formOpen:l,setFormOpen:f,datePickerOpen:o,setDatePickerOpen:u,planList:x,setPlanList:i},children:s})}function wh(){const s=m.useContext(dl);if(!s)throw new Error("useUserForm must be used within a UserFormProvider");return s}function Ch({refetch:s}){const{t:n}=M("user"),{form:a,formOpen:r,setFormOpen:l,datePickerOpen:c,setDatePickerOpen:o,planList:u,setPlanList:x}=wh();return m.useEffect(()=>{r&&Hs().then(({data:i})=>{x(i)})},[r,x]),e.jsxs(Ne,{...a,children:[e.jsx(b,{control:a.control,name:"email",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.email")}),e.jsx(N,{children:e.jsx(T,{...i,placeholder:n("edit.form.email_placeholder")})}),e.jsx(k,{...i})]})}),e.jsx(b,{control:a.control,name:"invite_user_email",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.inviter_email")}),e.jsx(N,{children:e.jsx(T,{value:i.value||"",onChange:d=>i.onChange(d.target.value?d.target.value:null),placeholder:n("edit.form.inviter_email_placeholder")})}),e.jsx(k,{...i})]})}),e.jsx(b,{control:a.control,name:"password",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.password")}),e.jsx(N,{children:e.jsx(T,{value:i.value||"",onChange:i.onChange,placeholder:n("edit.form.password_placeholder")})}),e.jsx(k,{...i})]})}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[e.jsx(b,{control:a.control,name:"balance",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.balance")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value||"",onChange:i.onChange,placeholder:n("edit.form.balance_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"¥"})]})}),e.jsx(k,{...i})]})}),e.jsx(b,{control:a.control,name:"commission_balance",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.commission_balance")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value||"",onChange:i.onChange,placeholder:n("edit.form.commission_balance_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"¥"})]})}),e.jsx(k,{...i})]})}),e.jsx(b,{control:a.control,name:"u",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.upload")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{value:i.value/1024/1024/1024||"",onChange:d=>i.onChange(parseInt(d.target.value)*1024*1024*1024),placeholder:n("edit.form.upload_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"GB"})]})}),e.jsx(k,{...i})]})}),e.jsx(b,{control:a.control,name:"d",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.download")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value/1024/1024/1024||"",onChange:d=>i.onChange(parseInt(d.target.value)*1024*1024*1024),placeholder:n("edit.form.download_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"GB"})]})}),e.jsx(k,{...i})]})})]}),e.jsx(b,{control:a.control,name:"transfer_enable",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.total_traffic")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value/1024/1024/1024||"",onChange:d=>i.onChange(parseInt(d.target.value)*1024*1024*1024),placeholder:n("edit.form.total_traffic_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"GB"})]})}),e.jsx(k,{})]})}),e.jsx(b,{control:a.control,name:"expired_at",render:({field:i})=>e.jsxs(v,{className:"flex flex-col",children:[e.jsx(y,{children:n("edit.form.expire_time")}),e.jsxs(js,{open:c,onOpenChange:o,children:[e.jsx(vs,{asChild:!0,children:e.jsx(N,{children:e.jsxs(D,{type:"button",variant:"outline",className:_("w-full pl-3 text-left font-normal",!i.value&&"text-muted-foreground"),onClick:()=>o(!0),children:[i.value?_e(i.value):e.jsx("span",{children:n("edit.form.expire_time_placeholder")}),e.jsx(jt,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),e.jsx(ms,{className:"w-auto p-0",align:"start",side:"top",sideOffset:4,onInteractOutside:d=>{d.preventDefault()},onEscapeKeyDown:d=>{d.preventDefault()},children:e.jsxs("div",{className:"flex flex-col space-y-3 p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(D,{type:"button",variant:"outline",className:"flex-1",onClick:()=>{i.onChange(null),o(!1)},children:n("edit.form.expire_time_permanent")}),e.jsx(D,{type:"button",variant:"outline",className:"flex-1",onClick:()=>{const d=new Date;d.setMonth(d.getMonth()+1),d.setHours(23,59,59,999),i.onChange(Math.floor(d.getTime()/1e3)),o(!1)},children:n("edit.form.expire_time_1month")}),e.jsx(D,{type:"button",variant:"outline",className:"flex-1",onClick:()=>{const d=new Date;d.setMonth(d.getMonth()+3),d.setHours(23,59,59,999),i.onChange(Math.floor(d.getTime()/1e3)),o(!1)},children:n("edit.form.expire_time_3months")})]}),e.jsx("div",{className:"rounded-md border",children:e.jsx(Bs,{mode:"single",selected:i.value?new Date(i.value*1e3):void 0,onSelect:d=>{if(d){const f=new Date(i.value?i.value*1e3:Date.now());d.setHours(f.getHours(),f.getMinutes(),f.getSeconds()),i.onChange(Math.floor(d.getTime()/1e3))}},disabled:d=>d{const d=new Date;d.setHours(23,59,59,999),i.onChange(Math.floor(d.getTime()/1e3))},className:"h-6 px-2 text-xs",children:n("edit.form.expire_time_today")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{type:"datetime-local",step:"1",value:_e(i.value,"YYYY-MM-DDTHH:mm:ss"),onChange:d=>{const f=new Date(d.target.value);isNaN(f.getTime())||i.onChange(Math.floor(f.getTime()/1e3))},className:"flex-1"}),e.jsx(D,{type:"button",variant:"outline",onClick:()=>o(!1),children:n("edit.form.expire_time_confirm")})]})]})]})})]}),e.jsx(k,{})]})}),e.jsx(b,{control:a.control,name:"plan_id",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.subscription")}),e.jsx(N,{children:e.jsxs(J,{value:i.value?i.value.toString():"null",onValueChange:d=>i.onChange(d==="null"?null:parseInt(d)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:n("edit.form.subscription_none")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"null",children:n("edit.form.subscription_none")}),u.map(d=>e.jsx(q,{value:d.id.toString(),children:d.name},d.id))]})]})})]})}),e.jsx(b,{control:a.control,name:"banned",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.account_status")}),e.jsx(N,{children:e.jsxs(J,{value:i.value.toString(),onValueChange:d=>i.onChange(parseInt(d)),children:[e.jsx(W,{children:e.jsx(Z,{})}),e.jsxs(Y,{children:[e.jsx(q,{value:"1",children:n("columns.status_text.banned")}),e.jsx(q,{value:"0",children:n("columns.status_text.normal")})]})]})})]})}),e.jsx(b,{control:a.control,name:"commission_type",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.commission_type")}),e.jsx(N,{children:e.jsxs(J,{value:i.value.toString(),onValueChange:d=>i.onChange(parseInt(d)),children:[e.jsx(W,{children:e.jsx(Z,{placeholder:n("edit.form.subscription_none")})}),e.jsxs(Y,{children:[e.jsx(q,{value:"0",children:n("edit.form.commission_type_system")}),e.jsx(q,{value:"1",children:n("edit.form.commission_type_cycle")}),e.jsx(q,{value:"2",children:n("edit.form.commission_type_onetime")})]})]})})]})}),e.jsx(b,{control:a.control,name:"commission_rate",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.commission_rate")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value||"",onChange:d=>i.onChange(parseInt(d.currentTarget.value)||null),placeholder:n("edit.form.commission_rate_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"%"})]})})]})}),e.jsx(b,{control:a.control,name:"discount",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.discount")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value||"",onChange:d=>i.onChange(parseInt(d.currentTarget.value)||null),placeholder:n("edit.form.discount_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"%"})]})}),e.jsx(k,{})]})}),e.jsx(b,{control:a.control,name:"speed_limit",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.speed_limit")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value||"",onChange:d=>i.onChange(parseInt(d.currentTarget.value)||null),placeholder:n("edit.form.speed_limit_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"Mbps"})]})}),e.jsx(k,{})]})}),e.jsx(b,{control:a.control,name:"device_limit",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.device_limit")}),e.jsx(N,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:i.value||"",onChange:d=>i.onChange(parseInt(d.currentTarget.value)||null),placeholder:n("edit.form.device_limit_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"台"})]})}),e.jsx(k,{})]})}),e.jsx(b,{control:a.control,name:"is_admin",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.is_admin")}),e.jsx("div",{className:"py-2",children:e.jsx(N,{children:e.jsx(Q,{checked:i.value===1,onCheckedChange:d=>i.onChange(d?1:0)})})})]})}),e.jsx(b,{control:a.control,name:"is_staff",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.is_staff")}),e.jsx("div",{className:"py-2",children:e.jsx(N,{children:e.jsx(Q,{checked:i.value===1,onCheckedChange:d=>i.onChange(d?1:0)})})})]})}),e.jsx(b,{control:a.control,name:"remarks",render:({field:i})=>e.jsxs(v,{children:[e.jsx(y,{children:n("edit.form.remarks")}),e.jsx(N,{children:e.jsx(bs,{className:"h-24",value:i.value||"",onChange:d=>i.onChange(d.currentTarget.value??null),placeholder:n("edit.form.remarks_placeholder")})}),e.jsx(k,{})]})}),e.jsxs(cl,{children:[e.jsx(D,{variant:"outline",onClick:()=>l(!1),children:n("edit.form.cancel")}),e.jsx(D,{type:"submit",onClick:()=>{a.handleSubmit(i=>{ud(i).then(({data:d})=>{d&&(A.success(n("edit.form.success")),l(!1),s())})})()},children:n("edit.form.submit")})]})]})}function ul({refetch:s,defaultValues:n,dialogTrigger:a=e.jsxs(D,{variant:"outline",size:"sm",className:"ml-auto hidden h-8 lg:flex",children:[e.jsx(vt,{className:"mr-2 h-4 w-4"}),t("edit.button")]})}){const{t:r}=M("user"),[l,c]=m.useState(!1);return e.jsx(_h,{defaultValues:n,open:l,onOpenChange:c,children:e.jsxs(ll,{open:l,onOpenChange:c,children:[e.jsx(il,{asChild:!0,children:a}),e.jsxs($a,{className:"max-w-[90%] space-y-4",children:[e.jsxs(qa,{children:[e.jsx(Ha,{children:r("edit.title")}),e.jsx(Ua,{})]}),e.jsx(Ch,{refetch:s})]})]})})}const ml=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"m17.71 11.29l-5-5a1 1 0 0 0-.33-.21a1 1 0 0 0-.76 0a1 1 0 0 0-.33.21l-5 5a1 1 0 0 0 1.42 1.42L11 9.41V17a1 1 0 0 0 2 0V9.41l3.29 3.3a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42"})}),xl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M17.71 11.29a1 1 0 0 0-1.42 0L13 14.59V7a1 1 0 0 0-2 0v7.59l-3.29-3.3a1 1 0 0 0-1.42 1.42l5 5a1 1 0 0 0 .33.21a.94.94 0 0 0 .76 0a1 1 0 0 0 .33-.21l5-5a1 1 0 0 0 0-1.42"})}),Sh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M17 11H9.41l3.3-3.29a1 1 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33a1 1 0 0 0 0 .76a1 1 0 0 0 .21.33l5 5a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42L9.41 13H17a1 1 0 0 0 0-2"})}),kh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M17.92 11.62a1 1 0 0 0-.21-.33l-5-5a1 1 0 0 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1 1 0 0 0 0 1.42a1 1 0 0 0 1.42 0l5-5a1 1 0 0 0 .21-.33a1 1 0 0 0 0-.76"})}),ha=[{accessorKey:"record_at",header:"时间",cell:({row:s})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx("time",{className:"text-sm text-muted-foreground",children:mc(s.original.record_at)})})},{accessorKey:"u",header:"上行流量",cell:({row:s})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ml,{className:"h-4 w-4 text-emerald-500"}),e.jsx("span",{className:"font-mono text-sm",children:hs(s.original.u)})]})},{accessorKey:"d",header:"下行流量",cell:({row:s})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(xl,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"font-mono text-sm",children:hs(s.original.d)})]})},{accessorKey:"server_rate",header:"倍率",cell:({row:s})=>{const n=s.original.server_rate;return e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs(K,{variant:"outline",className:"font-mono",children:[n,"x"]})})}},{id:"total",header:"总计",cell:({row:s})=>{const n=s.original.u+s.original.d;return e.jsx("div",{className:"flex items-center justify-end font-mono text-sm",children:hs(n)})}}];function hl({user_id:s,dialogTrigger:n}){const{t:a}=M(["traffic"]),[r,l]=m.useState(!1),[c,o]=m.useState({pageIndex:0,pageSize:20}),{data:u,isLoading:x}=ie({queryKey:["userStats",s,c,r],queryFn:()=>r?hd({user_id:s,pageSize:c.pageSize,page:c.pageIndex+1}):null}),i=ts({data:u?.data??[],columns:ha,pageCount:Math.ceil((u?.total??0)/c.pageSize),state:{pagination:c},manualPagination:!0,getCoreRowModel:as(),onPaginationChange:o});return e.jsxs(ve,{open:r,onOpenChange:l,children:[e.jsx(Ye,{asChild:!0,children:n}),e.jsxs(pe,{className:"sm:max-w-[700px]",children:[e.jsx(we,{children:e.jsx(be,{children:a("trafficRecord.title")})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ma,{children:i.getHeaderGroups().map(d=>e.jsx(Rs,{children:d.headers.map(f=>e.jsx(Oa,{className:_("h-10 px-2 text-xs",f.id==="total"&&"text-right"),children:f.isPlaceholder?null:Vt(f.column.columnDef.header,f.getContext())},f.id))},d.id))}),e.jsx(Fa,{children:x?Array.from({length:c.pageSize}).map((d,f)=>e.jsx(Rs,{children:Array.from({length:ha.length}).map((w,P)=>e.jsx(Js,{className:"p-2",children:e.jsx(oe,{className:"h-6 w-full"})},P))},f)):i.getRowModel().rows?.length?i.getRowModel().rows.map(d=>e.jsx(Rs,{"data-state":d.getIsSelected()&&"selected",className:"h-10",children:d.getVisibleCells().map(f=>e.jsx(Js,{className:"px-2",children:Vt(f.column.columnDef.cell,f.getContext())},f.id))},d.id)):e.jsx(Rs,{children:e.jsx(Js,{colSpan:ha.length,className:"h-24 text-center",children:a("trafficRecord.noRecords")})})})]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("p",{className:"text-sm font-medium",children:a("trafficRecord.perPage")}),e.jsxs(J,{value:`${i.getState().pagination.pageSize}`,onValueChange:d=>{i.setPageSize(Number(d))},children:[e.jsx(W,{className:"h-8 w-[70px]",children:e.jsx(Z,{placeholder:i.getState().pagination.pageSize})}),e.jsx(Y,{side:"top",children:[10,20,30,40,50].map(d=>e.jsx(q,{value:`${d}`,children:d},d))})]}),e.jsx("p",{className:"text-sm font-medium",children:a("trafficRecord.records")})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("div",{className:"flex w-[100px] items-center justify-center text-sm",children:a("trafficRecord.page",{current:i.getState().pagination.pageIndex+1,total:i.getPageCount()})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(X,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>i.previousPage(),disabled:!i.getCanPreviousPage()||x,children:e.jsx(Sh,{className:"h-4 w-4"})}),e.jsx(X,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>i.nextPage(),disabled:!i.getCanNextPage()||x,children:e.jsx(kh,{className:"h-4 w-4"})})]})]})]})]})]})]})}function Th({onConfirm:s,children:n,title:a="确认操作",description:r="确定要执行此操作吗?",cancelText:l="取消",confirmText:c="确认",variant:o="default",className:u}){return e.jsxs(za,{children:[e.jsx(Kr,{asChild:!0,children:n}),e.jsxs(Qt,{className:_("sm:max-w-[425px]",u),children:[e.jsxs(Jt,{children:[e.jsx(Xt,{children:a}),e.jsx(ea,{children:r})]}),e.jsxs(Zt,{children:[e.jsx(ta,{asChild:!0,children:e.jsx(D,{variant:"outline",children:l})}),e.jsx(sa,{asChild:!0,children:e.jsx(D,{variant:o,onClick:s,children:c})})]})]})]})}const Dh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M5 18h4.24a1 1 0 0 0 .71-.29l6.92-6.93L19.71 8a1 1 0 0 0 0-1.42l-4.24-4.29a1 1 0 0 0-1.42 0l-2.82 2.83l-6.94 6.93a1 1 0 0 0-.29.71V17a1 1 0 0 0 1 1m9.76-13.59l2.83 2.83l-1.42 1.42l-2.83-2.83ZM6 13.17l5.93-5.93l2.83 2.83L8.83 16H6ZM21 20H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2"})}),Ph=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M19 11h-6V5a1 1 0 0 0-2 0v6H5a1 1 0 0 0 0 2h6v6a1 1 0 0 0 2 0v-6h6a1 1 0 0 0 0-2"})}),Eh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21 8.94a1.3 1.3 0 0 0-.06-.27v-.09a1 1 0 0 0-.19-.28l-6-6a1 1 0 0 0-.28-.19a.3.3 0 0 0-.09 0a.9.9 0 0 0-.33-.11H10a3 3 0 0 0-3 3v1H6a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3v-1h1a3 3 0 0 0 3-3zm-6-3.53L17.59 8H16a1 1 0 0 1-1-1ZM15 19a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h1v7a3 3 0 0 0 3 3h5Zm4-4a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3v3a3 3 0 0 0 3 3h3Z"})}),Rh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21 11a1 1 0 0 0-1 1a8.05 8.05 0 1 1-2.22-5.5h-2.4a1 1 0 0 0 0 2h4.53a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1.77A10 10 0 1 0 22 12a1 1 0 0 0-1-1"})}),Ih=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M9.5 10.5H12a1 1 0 0 0 0-2h-1V8a1 1 0 0 0-2 0v.55a2.5 2.5 0 0 0 .5 4.95h1a.5.5 0 0 1 0 1H8a1 1 0 0 0 0 2h1v.5a1 1 0 0 0 2 0v-.55a2.5 2.5 0 0 0-.5-4.95h-1a.5.5 0 0 1 0-1M21 12h-3V3a1 1 0 0 0-.5-.87a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0A1 1 0 0 0 2 3v16a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-6a1 1 0 0 0-1-1M5 20a1 1 0 0 1-1-1V4.73l2 1.14a1.08 1.08 0 0 0 1 0l3-1.72l3 1.72a1.08 1.08 0 0 0 1 0l2-1.14V19a3 3 0 0 0 .18 1Zm15-1a1 1 0 0 1-2 0v-5h2Z"})}),Vh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M12.3 12.22A4.92 4.92 0 0 0 14 8.5a5 5 0 0 0-10 0a4.92 4.92 0 0 0 1.7 3.72A8 8 0 0 0 1 19.5a1 1 0 0 0 2 0a6 6 0 0 1 12 0a1 1 0 0 0 2 0a8 8 0 0 0-4.7-7.28M9 11.5a3 3 0 1 1 3-3a3 3 0 0 1-3 3m9.74.32A5 5 0 0 0 15 3.5a1 1 0 0 0 0 2a3 3 0 0 1 3 3a3 3 0 0 1-1.5 2.59a1 1 0 0 0-.5.84a1 1 0 0 0 .45.86l.39.26l.13.07a7 7 0 0 1 4 6.38a1 1 0 0 0 2 0a9 9 0 0 0-4.23-7.68"})}),Mh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M12 2a10 10 0 0 0-6.88 2.77V3a1 1 0 0 0-2 0v4.5a1 1 0 0 0 1 1h4.5a1 1 0 0 0 0-2h-2.4A8 8 0 1 1 4 12a1 1 0 0 0-2 0A10 10 0 1 0 12 2m0 6a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h2a1 1 0 0 0 0-2h-1V9a1 1 0 0 0-1-1"})}),Fh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M20 6h-4V5a3 3 0 0 0-3-3h-2a3 3 0 0 0-3 3v1H4a1 1 0 0 0 0 2h1v11a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3V8h1a1 1 0 0 0 0-2M10 5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v1h-4Zm7 14a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8h10Z"})}),Oh=(s,n)=>{const{t:a}=M("user");return[{accessorKey:"is_admin",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.is_admin")}),enableSorting:!1,enableHiding:!0,filterFn:(r,l,c)=>c.includes(r.getValue(l)),size:0},{accessorKey:"is_staff",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.is_staff")}),enableSorting:!1,enableHiding:!0,filterFn:(r,l,c)=>c.includes(r.getValue(l)),size:0},{accessorKey:"id",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.id")}),cell:({row:r})=>e.jsx(K,{variant:"outline",children:r.original.id}),enableSorting:!0,enableHiding:!1},{accessorKey:"email",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.email")}),cell:({row:r})=>{const l=r.original.t||0,c=Date.now()/1e3-l<120,o=Math.floor(Date.now()/1e3-l);let u=c?a("columns.online_status.online"):l===0?a("columns.online_status.never"):a("columns.online_status.last_online",{time:_e(l)});if(!c&&l!==0){const x=Math.floor(o/60),i=Math.floor(x/60),d=Math.floor(i/24);d>0?u+=` -`+a("columns.online_status.offline_duration.days",{count:d}):i>0?u+=` -`+a("columns.online_status.offline_duration.hours",{count:i}):x>0?u+=` -`+a("columns.online_status.offline_duration.minutes",{count:x}):u+=` -`+a("columns.online_status.offline_duration.seconds",{count:o})}return e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:_("size-2.5 rounded-full ring-2 ring-offset-2",c?"bg-green-500 ring-green-500/20":"bg-gray-300 ring-gray-300/20","transition-all duration-300")}),e.jsx("span",{className:"font-medium text-foreground/90",children:r.original.email})]})}),e.jsx(ce,{side:"bottom",className:"max-w-[280px]",children:e.jsx("p",{className:"whitespace-pre-line text-sm",children:u})})]})})},enableSorting:!1,enableHiding:!1},{accessorKey:"online_count",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.online_count")}),cell:({row:r})=>{const l=r.original.device_limit,c=r.original.online_count||0;return e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsxs(K,{variant:"outline",className:_("min-w-[4rem] justify-center",l!==null&&c>=l?"border-destructive/50 bg-destructive/10 text-destructive":"border-primary/40 bg-primary/5 text-primary/90"),children:[c," / ",l===null?"∞":l]})})}),e.jsx(ce,{side:"bottom",children:e.jsx("p",{className:"text-sm",children:l===null?a("columns.device_limit.unlimited"):a("columns.device_limit.limited",{count:l})})})]})})},enableSorting:!0,enableHiding:!1},{accessorKey:"banned",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.status")}),cell:({row:r})=>{const l=r.original.banned;return e.jsx("div",{className:"flex justify-center",children:e.jsx(K,{className:_("min-w-20 justify-center transition-colors",l?"bg-destructive/15 text-destructive hover:bg-destructive/25":"bg-success/15 text-success hover:bg-success/25"),children:a(l?"columns.status_text.banned":"columns.status_text.normal")})})},enableSorting:!0,filterFn:(r,l,c)=>c.includes(r.getValue(l))},{accessorKey:"plan_id",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.subscription")}),cell:({row:r})=>e.jsx("div",{className:"min-w-[10em] break-all",children:r.original?.plan?.name||"-"}),enableSorting:!1,enableHiding:!1},{accessorKey:"group_id",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.group")}),cell:({row:r})=>e.jsx("div",{className:"flex flex-wrap gap-1",children:e.jsx(K,{variant:"outline",className:_("px-2 py-0.5 font-medium","bg-secondary/50 hover:bg-secondary/70","border border-border/50","transition-all duration-200","cursor-default select-none","flex items-center gap-1.5 whitespace-nowrap"),children:r.original?.group?.name||"-"})}),enableSorting:!1},{accessorKey:"total_used",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.used_traffic")}),cell:({row:r})=>{const l=hs(r.original?.total_used),c=hs(r.original?.transfer_enable),o=r.original?.total_used/r.original?.transfer_enable*100||0;return e.jsx(je,{delayDuration:100,children:e.jsxs(xe,{children:[e.jsx(he,{className:"w-full",children:e.jsxs("div",{className:"w-full space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:l}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.toFixed(1),"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-secondary",children:e.jsx("div",{className:_("h-full rounded-full transition-all",o>90?"bg-destructive":"bg-primary"),style:{width:`${Math.min(o,100)}%`}})})]})}),e.jsx(ce,{side:"bottom",children:e.jsxs("p",{className:"text-sm",children:[a("columns.total_traffic"),": ",c]})})]})})}},{accessorKey:"transfer_enable",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.total_traffic")}),cell:({row:r})=>e.jsx("div",{className:"font-medium text-muted-foreground",children:hs(r.original?.transfer_enable)})},{accessorKey:"expired_at",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.expire_time")}),cell:({row:r})=>{const l=r.original.expired_at,c=Date.now()/1e3,o=l!=null&&le.jsx(L,{column:r,title:a("columns.balance")}),cell:({row:r})=>{const l=Qs(r.original?.balance);return e.jsxs("div",{className:"flex items-center gap-1 font-medium",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"¥"}),e.jsx("span",{className:"tabular-nums text-foreground",children:l})]})}},{accessorKey:"commission_balance",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.commission")}),cell:({row:r})=>{const l=Qs(r.original?.commission_balance);return e.jsxs("div",{className:"flex items-center gap-1 font-medium",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"¥"}),e.jsx("span",{className:"tabular-nums text-foreground",children:l})]})}},{accessorKey:"created_at",header:({column:r})=>e.jsx(L,{column:r,title:a("columns.register_time")}),cell:({row:r})=>e.jsx("div",{className:"truncate",children:_e(r.original?.created_at)}),size:1e3},{id:"actions",header:({column:r})=>e.jsx(L,{column:r,className:"justify-end",title:a("columns.actions")}),cell:({row:r,table:l})=>e.jsxs(Cs,{modal:!0,children:[e.jsx(Ss,{asChild:!0,children:e.jsx("div",{className:"text-center",children:e.jsx(X,{variant:"ghost",className:"h-8 w-8 p-0 hover:bg-muted","aria-label":a("columns.actions"),children:e.jsx(Ft,{className:"size-4"})})})}),e.jsxs(ps,{align:"end",className:"min-w-[40px]",children:[e.jsx(ge,{onSelect:c=>{c.preventDefault()},className:"p-0",children:e.jsx(ul,{defaultValues:{...r.original,invite_user_email:r.original.invite_user?.email},refetch:s,dialogTrigger:e.jsxs(X,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Dh,{className:"mr-2"}),a("columns.actions_menu.edit")]})})}),e.jsx(ge,{onSelect:c=>c.preventDefault(),className:"p-0",children:e.jsx(tl,{defaultValues:{email:r.original.email},trigger:e.jsxs(X,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Ph,{className:"mr-2 "}),a("columns.actions_menu.assign_order")]})})}),e.jsx(ge,{onSelect:()=>{zt(r.original.subscribe_url).then(()=>{A.success(a("common:copy.success"))})},className:"p-0",children:e.jsxs(X,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Eh,{className:"mr-2"}),a("columns.actions_menu.copy_url")]})}),e.jsx(ge,{onSelect:()=>{md({id:r.original.id}).then(({data:c})=>{c&&A.success("重置成功")})},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Rh,{className:"mr-2 "}),a("columns.actions_menu.reset_secret")]})}),e.jsx(ge,{onSelect:()=>{},className:"p-0",children:e.jsxs($s,{className:"flex items-center px-2 py-1.5",to:`/finance/order?user_id=${r.original?.id}`,children:[e.jsx(Ih,{className:"mr-2"}),a("columns.actions_menu.orders")]})}),e.jsx(ge,{onSelect:()=>{l.setColumnFilters([{id:"invite_user_id",value:r.original?.id}])},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Vh,{className:"mr-2 "}),a("columns.actions_menu.invites")]})}),e.jsx(ge,{onSelect:c=>c.preventDefault(),className:"p-0",children:e.jsx(hl,{user_id:r.original?.id,dialogTrigger:e.jsxs(X,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Mh,{className:"mr-2 "}),a("columns.actions_menu.traffic_records")]})})}),e.jsx(ge,{onSelect:c=>c.preventDefault(),className:"p-0",children:e.jsx(Th,{title:a("columns.actions_menu.delete_confirm_title"),description:a("columns.actions_menu.delete_confirm_description",{email:r.original.email}),cancelText:a("common:cancel"),confirmText:a("common:confirm"),variant:"destructive",onConfirm:async()=>{try{const{data:c}=await Lt.destroy(r.original.id);c&&(A.success(a("common:delete.success")),s())}catch{A.error(a("common:delete.failed"))}},children:e.jsxs(X,{variant:"ghost",className:"w-full justify-start px-2 py-1.5 text-destructive hover:text-destructive",children:[e.jsx(Fh,{className:"mr-2"}),a("columns.actions_menu.delete")]})})})]})]})}]};function zh(){const[s]=fr(),[n,a]=m.useState({}),[r,l]=m.useState({is_admin:!1,is_staff:!1}),[c,o]=m.useState([]),[u,x]=m.useState([]),[i,d]=m.useState({pageIndex:0,pageSize:20});m.useEffect(()=>{const F=s.get("email");F&&o(H=>H.some(O=>O.id==="email")?H:[...H,{id:"email",value:F}])},[s]);const{refetch:f,data:w,isLoading:P}=ie({queryKey:["userList",i,c,u],queryFn:()=>dd({pageSize:i.pageSize,current:i.pageIndex+1,filter:c,sort:u})}),[C,p]=m.useState([]),[g,j]=m.useState([]);m.useEffect(()=>{yt().then(({data:F})=>{p(F)}),Hs().then(({data:F})=>{j(F)})},[]);const S=C.map(F=>({label:F.name,value:F.id})),R=g.map(F=>({label:F.name,value:F.id})),E=ts({data:w?.data??[],columns:Oh(f),state:{sorting:u,columnVisibility:r,rowSelection:n,columnFilters:c,pagination:i},rowCount:w?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:a,onSortingChange:x,onColumnFiltersChange:o,onColumnVisibilityChange:l,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),onPaginationChange:d,getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnVisibility:{commission_balance:!1,created_at:!1,is_admin:!1,is_staff:!1,permission_group:!1,plan_id:!1},columnPinning:{right:["actions"]}}});return e.jsx(xs,{table:E,toolbar:e.jsx(yh,{table:E,refetch:f,serverGroupList:C,permissionGroups:S,subscriptionPlans:R})})}function Lh(){const{t:s}=M("user");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("manage.title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("manage.description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx("div",{className:"w-full",children:e.jsx(zh,{})})})]})]})}const Ah=Object.freeze(Object.defineProperty({__proto__:null,default:Lh},Symbol.toStringTag,{value:"Module"}));function $h({column:s,title:n,options:a}){const r=new Set(s?.getFilterValue());return e.jsxs(js,{children:[e.jsx(vs,{asChild:!0,children:e.jsxs(X,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(Yo,{className:"mr-2 h-4 w-4"}),n,r?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(Se,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:r.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:r.size>2?e.jsxs(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[r.size," selected"]}):a.filter(l=>r.has(l.value)).map(l=>e.jsx(K,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:l.label},`selected-${l.value}`))})]})]})}),e.jsx(ms,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Vs,{children:[e.jsx(Us,{placeholder:n}),e.jsxs(Ms,{children:[e.jsx(Ks,{children:"No results found."}),e.jsx(Ge,{children:a.map(l=>{const c=r.has(l.value);return e.jsxs(Ie,{onSelect:()=>{c?r.delete(l.value):r.add(l.value);const o=Array.from(r);s?.setFilterValue(o.length?o:void 0)},children:[e.jsx("div",{className:_("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",c?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(Qo,{className:_("h-4 w-4")})}),l.icon&&e.jsx(l.icon,{className:"mr-2 h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:l.label})]},`option-${l.value}`)})}),r.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(at,{}),e.jsx(Ge,{children:e.jsx(Ie,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}const qh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M19 11H5a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2"})});function Hh({table:s}){const{t:n}=M("ticket");return e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-4",children:[e.jsx(Wt,{defaultValue:s.getColumn("status")?.getFilterValue(),onValueChange:a=>s.getColumn("status")?.setFilterValue(a),children:e.jsxs(bt,{className:"grid w-full grid-cols-2",children:[e.jsx(Ke,{value:"0",children:n("status.pending")}),e.jsx(Ke,{value:"1",children:n("status.closed")})]})}),s.getColumn("level")&&e.jsx($h,{column:s.getColumn("level"),title:n("columns.level"),options:[{label:n("level.low"),value:Me.LOW,icon:qh,color:"gray"},{label:n("level.medium"),value:Me.MIDDLE,icon:ml,color:"yellow"},{label:n("level.high"),value:Me.HIGH,icon:xl,color:"red"}]})]})})}function Uh(){return e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",className:"text-foreground",children:[e.jsx("circle",{cx:"4",cy:"12",r:"2",fill:"currentColor",children:e.jsx("animate",{id:"spinner_qFRN",begin:"0;spinner_OcgL.end+0.25s",attributeName:"cy",calcMode:"spline",dur:"0.6s",values:"12;6;12",keySplines:".33,.66,.66,1;.33,0,.66,.33"})}),e.jsx("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor",children:e.jsx("animate",{begin:"spinner_qFRN.begin+0.1s",attributeName:"cy",calcMode:"spline",dur:"0.6s",values:"12;6;12",keySplines:".33,.66,.66,1;.33,0,.66,.33"})}),e.jsx("circle",{cx:"20",cy:"12",r:"2",fill:"currentColor",children:e.jsx("animate",{id:"spinner_OcgL",begin:"spinner_qFRN.begin+0.2s",attributeName:"cy",calcMode:"spline",dur:"0.6s",values:"12;6;12",keySplines:".33,.66,.66,1;.33,0,.66,.33"})})]})}const Kh=Ls("flex gap-2 max-w-[60%] items-end relative group",{variants:{variant:{received:"self-start",sent:"self-end flex-row-reverse"},layout:{default:"",ai:"max-w-full w-full items-center"}},defaultVariants:{variant:"received",layout:"default"}}),pl=m.forwardRef(({className:s,variant:n,layout:a,children:r,...l},c)=>e.jsx("div",{className:_(Kh({variant:n,layout:a,className:s}),"relative group"),ref:c,...l,children:m.Children.map(r,o=>m.isValidElement(o)&&typeof o.type!="string"?m.cloneElement(o,{variant:n,layout:a}):o)}));pl.displayName="ChatBubble";const Bh=Ls("p-4",{variants:{variant:{received:"bg-secondary text-secondary-foreground rounded-r-lg rounded-tl-lg",sent:"bg-primary text-primary-foreground rounded-l-lg rounded-tr-lg"},layout:{default:"",ai:"border-t w-full rounded-none bg-transparent"}},defaultVariants:{variant:"received",layout:"default"}}),fl=m.forwardRef(({className:s,variant:n,layout:a,isLoading:r=!1,children:l,...c},o)=>e.jsx("div",{className:_(Bh({variant:n,layout:a,className:s}),"break-words max-w-full whitespace-pre-wrap"),ref:o,...c,children:r?e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(Uh,{})}):l}));fl.displayName="ChatBubbleMessage";const Gh=m.forwardRef(({variant:s,className:n,children:a,...r},l)=>e.jsx("div",{ref:l,className:_("absolute top-1/2 -translate-y-1/2 flex opacity-0 group-hover:opacity-100 transition-opacity duration-200",s==="sent"?"-left-1 -translate-x-full flex-row-reverse":"-right-1 translate-x-full",n),...r,children:a}));Gh.displayName="ChatBubbleActionWrapper";const gl=m.forwardRef(({className:s,...n},a)=>e.jsx(bs,{autoComplete:"off",ref:a,name:"message",className:_("max-h-12 px-4 py-3 bg-background text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 w-full rounded-md flex items-center h-16 resize-none",s),...n}));gl.displayName="ChatInput";const jl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"m13.41 12l4.3-4.29a1 1 0 1 0-1.42-1.42L12 10.59l-4.29-4.3a1 1 0 0 0-1.42 1.42l4.3 4.29l-4.3 4.29a1 1 0 0 0 0 1.42a1 1 0 0 0 1.42 0l4.29-4.3l4.29 4.3a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42Z"})}),vl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M15.098 12.634L13 11.423V7a1 1 0 0 0-2 0v5a1 1 0 0 0 .5.866l2.598 1.5a1 1 0 1 0 1-1.732M12 2a10 10 0 1 0 10 10A10.01 10.01 0 0 0 12 2m0 18a8 8 0 1 1 8-8a8.01 8.01 0 0 1-8 8"})}),pn=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"m11.29 12l3.54-3.54a1 1 0 0 0 0-1.41a1 1 0 0 0-1.42 0l-4.24 4.24a1 1 0 0 0 0 1.42L13.41 17a1 1 0 0 0 .71.29a1 1 0 0 0 .71-.29a1 1 0 0 0 0-1.41Z"})}),Wh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21.71 20.29L18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.39M11 18a7 7 0 1 1 7-7a7 7 0 0 1-7 7"})}),Yh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M3.71 16.29a1 1 0 0 0-.33-.21a1 1 0 0 0-.76 0a1 1 0 0 0-.33.21a1 1 0 0 0-.21.33a1 1 0 0 0 .21 1.09a1.2 1.2 0 0 0 .33.21a.94.94 0 0 0 .76 0a1.2 1.2 0 0 0 .33-.21a1 1 0 0 0 .21-1.09a1 1 0 0 0-.21-.33M7 8h14a1 1 0 0 0 0-2H7a1 1 0 0 0 0 2m-3.29 3.29a1 1 0 0 0-1.09-.21a1.2 1.2 0 0 0-.33.21a1 1 0 0 0-.21.33a.94.94 0 0 0 0 .76a1.2 1.2 0 0 0 .21.33a1.2 1.2 0 0 0 .33.21a.94.94 0 0 0 .76 0a1.2 1.2 0 0 0 .33-.21a1.2 1.2 0 0 0 .21-.33a.94.94 0 0 0 0-.76a1 1 0 0 0-.21-.33M21 11H7a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2M3.71 6.29a1 1 0 0 0-.33-.21a1 1 0 0 0-1.09.21a1.2 1.2 0 0 0-.21.33a.94.94 0 0 0 0 .76a1.2 1.2 0 0 0 .21.33a1.2 1.2 0 0 0 .33.21a1 1 0 0 0 1.09-.21a1.2 1.2 0 0 0 .21-.33a.94.94 0 0 0 0-.76a1.2 1.2 0 0 0-.21-.33M21 16H7a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2"})}),Qh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M9 12H7a1 1 0 0 0 0 2h2a1 1 0 0 0 0-2m-1-2h4a1 1 0 0 0 0-2H8a1 1 0 0 0 0 2m1 6H7a1 1 0 0 0 0 2h2a1 1 0 0 0 0-2m12-4h-3V3a1 1 0 0 0-.5-.87a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0A1 1 0 0 0 2 3v16a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-6a1 1 0 0 0-1-1M5 20a1 1 0 0 1-1-1V4.73l2 1.14a1.08 1.08 0 0 0 1 0l3-1.72l3 1.72a1.08 1.08 0 0 0 1 0l2-1.14V19a3 3 0 0 0 .18 1Zm15-1a1 1 0 0 1-2 0v-5h2Zm-6.44-2.83a.8.8 0 0 0-.18-.09a.6.6 0 0 0-.19-.06a1 1 0 0 0-.9.27A1.05 1.05 0 0 0 12 17a1 1 0 0 0 .07.38a1.2 1.2 0 0 0 .22.33a1.2 1.2 0 0 0 .33.21a.94.94 0 0 0 .76 0a1.2 1.2 0 0 0 .33-.21A1 1 0 0 0 14 17a1.05 1.05 0 0 0-.29-.71a2 2 0 0 0-.15-.12m.14-3.88a1 1 0 0 0-1.62.33A1 1 0 0 0 13 14a1 1 0 0 0 1-1a1 1 0 0 0-.08-.38a.9.9 0 0 0-.22-.33"})});function Jh(){return e.jsxs("div",{className:"flex h-full flex-col space-y-4 p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"h-8 w-3/4"}),e.jsx(oe,{className:"h-4 w-1/2"})]}),e.jsx("div",{className:"flex-1 space-y-4",children:[1,2,3].map(s=>e.jsx(oe,{className:"h-20 w-2/3"},s))})]})}function Zh(){return e.jsx("div",{className:"space-y-4 p-4",children:[1,2,3,4].map(s=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"h-5 w-4/5"}),e.jsx(oe,{className:"h-4 w-2/3"}),e.jsx(oe,{className:"h-3 w-1/2"})]},s))})}function Xh({ticket:s,isActive:n,onClick:a}){const{t:r}=M("ticket"),l=c=>{switch(c){case Me.HIGH:return"bg-red-50 text-red-600 border-red-200";case Me.MIDDLE:return"bg-yellow-50 text-yellow-600 border-yellow-200";case Me.LOW:return"bg-green-50 text-green-600 border-green-200";default:return"bg-gray-50 text-gray-600 border-gray-200"}};return e.jsxs("div",{className:_("flex cursor-pointer flex-col border-b p-4 hover:bg-accent/50",n&&"bg-accent"),onClick:a,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 max-w-[280px]",children:[e.jsx("h4",{className:"truncate font-medium flex-1",children:s.subject}),e.jsx(K,{variant:s.status===Is.CLOSED?"secondary":"default",className:"shrink-0",children:s.status===Is.CLOSED?r("status.closed"):r("status.processing")})]}),e.jsx("div",{className:"mt-1 text-sm text-muted-foreground truncate max-w-[280px]",children:s.user?.email}),e.jsxs("div",{className:"mt-2 flex items-center justify-between text-xs",children:[e.jsx("time",{className:"text-muted-foreground",children:_e(s.updated_at)}),e.jsx("div",{className:_("px-2 py-0.5 rounded-full border text-xs font-medium",l(s.level)),children:r(`level.${s.level===Me.LOW?"low":s.level===Me.MIDDLE?"medium":"high"}`)})]})]})}function ep({ticketId:s,dialogTrigger:n}){const{t:a}=M("ticket"),r=ks(),l=m.useRef(null),c=m.useRef(null),[o,u]=m.useState(!1),[x,i]=m.useState(""),[d,f]=m.useState(!1),[w,P]=m.useState(s),[C,p]=m.useState(""),[g,j]=m.useState(!1),{data:S,isLoading:R,refetch:E}=ie({queryKey:["tickets",o],queryFn:()=>o?ia.getList({filter:[{id:"status",value:[Is.OPENING]}]}):Promise.resolve(null),enabled:o}),{data:F,refetch:H,isLoading:te}=ie({queryKey:["ticket",w,o],queryFn:()=>o?fd(w):Promise.resolve(null),refetchInterval:o?5e3:!1,retry:3}),O=F?.data,He=(S?.data||[]).filter(ne=>ne.subject.toLowerCase().includes(C.toLowerCase())||ne.user?.email.toLowerCase().includes(C.toLowerCase())),G=(ne="smooth")=>{if(l.current){const{scrollHeight:Qe,clientHeight:nt}=l.current;l.current.scrollTo({top:Qe-nt,behavior:ne})}};m.useEffect(()=>{if(!o)return;const ne=requestAnimationFrame(()=>{G("instant"),setTimeout(()=>G(),1e3)});return()=>{cancelAnimationFrame(ne)}},[o,O?.messages]);const ae=async()=>{const ne=x.trim();!ne||d||(f(!0),ia.reply({id:w,message:ne}).then(()=>{i(""),H(),G(),setTimeout(()=>{c.current?.focus()},0)}).finally(()=>{f(!1)}))},$=async()=>{ia.close(w).then(()=>{A.success(a("actions.close_success")),H(),E()})},I=()=>{O?.user&&r("/finance/order?user_id="+O.user.id)},B=O?.status===Is.CLOSED;return e.jsxs(ve,{open:o,onOpenChange:u,children:[e.jsx(Ye,{asChild:!0,children:n??e.jsx(X,{variant:"outline",children:a("actions.view_ticket")})}),e.jsxs(pe,{className:"flex h-[90vh] max-w-6xl flex-col gap-0 p-0",children:[e.jsx(be,{}),e.jsxs("div",{className:"flex h-full",children:[e.jsx(X,{variant:"ghost",size:"icon",className:"absolute left-2 top-2 md:hidden z-50",onClick:()=>j(!g),children:e.jsx(pn,{className:_("h-4 w-4 transition-transform",!g&&"rotate-180")})}),e.jsxs("div",{className:_("absolute md:relative inset-y-0 left-0 z-40 flex flex-col border-r bg-background transition-transform duration-200 ease-in-out",g?"-translate-x-full":"translate-x-0","w-80 md:w-80 md:translate-x-0"),children:[e.jsxs("div",{className:"space-y-4 border-b p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold",children:a("list.title")}),e.jsx(X,{variant:"ghost",size:"icon",className:"hidden md:flex h-8 w-8",onClick:()=>j(!g),children:e.jsx(pn,{className:_("h-4 w-4 transition-transform",!g&&"rotate-180")})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Wh,{className:"absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(T,{placeholder:a("list.search_placeholder"),value:C,onChange:ne=>p(ne.target.value),className:"pl-8"})]})]}),e.jsx(zs,{className:"flex-1",children:e.jsx("div",{className:"w-full",children:R?e.jsx(Zh,{}):He.length===0?e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground p-4",children:a(C?"list.no_search_results":"list.no_tickets")}):He.map(ne=>e.jsx(Xh,{ticket:ne,isActive:ne.id===w,onClick:()=>{P(ne.id),window.innerWidth<768&&j(!0)}},ne.id))})})]}),e.jsxs("div",{className:"flex-1 flex flex-col relative",children:[!g&&e.jsx("div",{className:"absolute inset-0 bg-black/20 z-30 md:hidden",onClick:()=>j(!0)}),te?e.jsx(Jh,{}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col space-y-4 border-b p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("h2",{className:"text-2xl font-semibold",children:O?.subject}),e.jsx(K,{variant:B?"secondary":"default",children:a(B?"status.closed":"status.processing")}),!B&&e.jsx(We,{title:a("actions.close_confirm_title"),description:a("actions.close_confirm_description"),confirmText:a("actions.close_confirm_button"),variant:"destructive",onConfirm:$,children:e.jsxs(X,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-destructive",children:[e.jsx(jl,{className:"h-4 w-4"}),a("actions.close_ticket")]})})]}),e.jsxs("div",{className:"flex items-center space-x-4 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{children:O?.user?.email})]}),e.jsx(Se,{orientation:"vertical",className:"h-4"}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsxs("span",{children:[a("detail.created_at")," ",_e(O?.created_at)]})]}),e.jsx(Se,{orientation:"vertical",className:"h-4"}),e.jsx(K,{variant:"outline",children:O?.level!=null&&a(`level.${O.level===Me.LOW?"low":O.level===Me.MIDDLE?"medium":"high"}`)})]})]}),O?.user&&e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(ul,{defaultValues:O.user,refetch:H,dialogTrigger:e.jsx(X,{variant:"outline",size:"icon",className:"h-8 w-8",title:a("detail.user_info"),children:e.jsx(gt,{className:"h-4 w-4"})})}),e.jsx(hl,{user_id:O.user.id,dialogTrigger:e.jsx(X,{variant:"outline",size:"icon",className:"h-8 w-8",title:a("detail.traffic_records"),children:e.jsx(Yh,{className:"h-4 w-4"})})}),e.jsx(X,{variant:"outline",size:"icon",className:"h-8 w-8",title:a("detail.order_records"),onClick:I,children:e.jsx(Qh,{className:"h-4 w-4"})})]})]})}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx("div",{ref:l,className:"h-full space-y-4 overflow-y-auto p-6",children:O?.messages?.length===0?e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:a("detail.no_messages")}):O?.messages?.map(ne=>e.jsx(pl,{variant:ne.is_me?"sent":"received",className:ne.is_me?"ml-auto":"mr-auto",children:e.jsx(fl,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"whitespace-pre-wrap break-words",children:ne.message}),e.jsx("div",{className:"text-right",children:e.jsx("time",{className:"text-[10px] text-muted-foreground",children:_e(ne.created_at)})})]})})},ne.id))})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs("div",{className:"relative flex items-center space-x-2",children:[e.jsx(gl,{ref:c,disabled:B||d,placeholder:a(B?"detail.input.closed_placeholder":"detail.input.reply_placeholder"),className:"flex-1 resize-none rounded-lg border bg-background p-3 focus-visible:ring-1",value:x,onChange:ne=>i(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),ae())}}),e.jsx(X,{disabled:B||d||!x.trim(),onClick:ae,children:a(d?"detail.input.sending":"detail.input.send")})]})})]})]})]})]})]})}const sp=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M19 4H5a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3V7a3 3 0 0 0-3-3m-.41 2l-5.88 5.88a1 1 0 0 1-1.42 0L5.41 6ZM20 17a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7.41l5.88 5.88a3 3 0 0 0 4.24 0L20 7.41Z"})}),tp=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21.92 11.6C19.9 6.91 16.1 4 12 4s-7.9 2.91-9.92 7.6a1 1 0 0 0 0 .8C4.1 17.09 7.9 20 12 20s7.9-2.91 9.92-7.6a1 1 0 0 0 0-.8M12 18c-3.17 0-6.17-2.29-7.9-6C5.83 8.29 8.83 6 12 6s6.17 2.29 7.9 6c-1.73 3.71-4.73 6-7.9 6m0-10a4 4 0 1 0 4 4a4 4 0 0 0-4-4m0 6a2 2 0 1 1 2-2a2 2 0 0 1-2 2"})}),ap=s=>{const{t:n}=M("ticket");return[{accessorKey:"id",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.id")}),cell:({row:a})=>e.jsx(K,{variant:"outline",children:a.getValue("id")}),enableSorting:!1,enableHiding:!1},{accessorKey:"subject",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.subject")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(sp,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"max-w-[500px] truncate font-medium",children:a.getValue("subject")})]}),enableSorting:!1,enableHiding:!1,size:4e3},{accessorKey:"level",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.level")}),cell:({row:a})=>{const r=a.getValue("level"),l=r===Me.LOW?"default":r===Me.MIDDLE?"secondary":"destructive";return e.jsx(K,{variant:l,className:"whitespace-nowrap",children:n(`level.${r===Me.LOW?"low":r===Me.MIDDLE?"medium":"high"}`)})},filterFn:(a,r,l)=>l.includes(a.getValue(r))},{accessorKey:"status",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.status")}),cell:({row:a})=>{const r=a.getValue("status"),l=a.original.reply_status,c=r===Is.CLOSED?n("status.closed"):n(l===0?"status.replied":"status.pending"),o=r===Is.CLOSED?"default":l===0?"secondary":"destructive";return e.jsx(K,{variant:o,className:"whitespace-nowrap",children:c})}},{accessorKey:"updated_at",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.updated_at")}),cell:({row:a})=>e.jsxs("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:_e(a.getValue("updated_at"))})]}),enableSorting:!0},{accessorKey:"created_at",header:({column:a})=>e.jsx(L,{column:a,title:n("columns.created_at")}),cell:({row:a})=>e.jsx("div",{className:"text-sm text-muted-foreground",children:_e(a.getValue("created_at"))}),enableSorting:!0,meta:{isFlexGrow:!0}},{id:"actions",header:({column:a})=>e.jsx(L,{className:"justify-end",column:a,title:n("columns.actions")}),cell:({row:a})=>{const r=a.original.status!==Is.CLOSED;return e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(ep,{ticketId:a.original.id,dialogTrigger:e.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8",title:n("actions.view_details"),children:e.jsx(tp,{className:"h-4 w-4"})})}),r&&e.jsx(We,{title:n("actions.close_confirm_title"),description:n("actions.close_confirm_description"),confirmText:n("actions.close_confirm_button"),variant:"destructive",onConfirm:async()=>{gd(a.original.id).then(()=>{A.success(n("actions.close_success")),s()})},children:e.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8",title:n("actions.close_ticket"),children:e.jsx(jl,{className:"h-4 w-4"})})})]})}}]};function np(){const[s,n]=m.useState({}),[a,r]=m.useState({}),[l,c]=m.useState([{id:"status",value:"0"}]),[o,u]=m.useState([]),[x,i]=m.useState({pageIndex:0,pageSize:20}),{refetch:d,data:f,isLoading:w}=ie({queryKey:["orderList",x,l,o],queryFn:()=>pd({pageSize:x.pageSize,current:x.pageIndex+1,filter:l,sort:o})}),P=ts({data:f?.data??[],columns:ap(d),state:{sorting:o,columnVisibility:a,rowSelection:s,columnFilters:l,pagination:x},rowCount:f?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:u,onColumnFiltersChange:c,onColumnVisibilityChange:r,getCoreRowModel:as(),getFilteredRowModel:cs(),getPaginationRowModel:ds(),onPaginationChange:i,getSortedRowModel:us(),getFacetedRowModel:Ts(),getFacetedUniqueValues:Ds(),initialState:{columnPinning:{right:["actions"]}}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Hh,{table:P,refetch:d}),e.jsx(xs,{table:P,showPagination:!0})]})}function rp(){const{t:s}=M("ticket");return e.jsxs(Pe,{children:[e.jsxs(Ee,{children:[e.jsx(qe,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(ze,{}),e.jsx(Le,{})]})]}),e.jsxs(Ve,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(np,{})})]})]})}const lp=Object.freeze(Object.defineProperty({__proto__:null,default:rp},Symbol.toStringTag,{value:"Module"}));export{up as a,cp as c,dp as g,mp as r}; +import{r as u,j as e,t as Sl,c as kl,I as Ka,a as As,S as Na,u as Ts,b as _a,R as fn,d as gn,e as Tl,F as Dl,C as Pl,L as jn,T as vn,f as bn,g as El,h as Rl,i as Il,k as A,z as x,l as V,m as ge,n as Ne,o as re,p as es,q as Se,s as it,v as Vl,O as wa,w as Ml,x as Fl,y as Ol,A as Ll,B as zl,D as Al,Q as $l,E as Ul,G as Hl,H as ql,P as Kl,J as Bl,K as Gl,M as Wl,N as Yl,U as yn,V as Nn,W as zt,X as At,Y as Ca,Z as ss,_ as $t,$ as Ut,a0 as _n,a1 as wn,a2 as Cn,a3 as Sa,a4 as Sn,a5 as Ql,a6 as kn,a7 as Tn,a8 as Dn,a9 as Pn,aa as $s,ab as En,ac as Jl,ad as Rn,ae as In,af as Xl,ag as Zl,ah as ei,ai as si,aj as ti,ak as ai,al as ni,am as ri,an as li,ao as ii,ap as oi,aq as Vn,ar as ci,as as di,at as Us,au as Mn,av as ui,aw as mi,ax as Fn,ay as ka,az as xi,aA as hi,aB as Ba,aC as pi,aD as On,aE as fi,aF as Ln,aG as gi,aH as ji,aI as vi,aJ as bi,aK as yi,aL as Ni,aM as zn,aN as _i,aO as wi,aP as Ci,aQ as Le,aR as Si,aS as An,aT as $n,aU as ki,aV as Ti,aW as Un,aX as Di,aY as Pi,aZ as Ze,a_ as Ei,a$ as Ri,b0 as Hn,b1 as qn,b2 as Kn,b3 as Ii,b4 as Vi,b5 as Mi,b6 as Bn,b7 as Fi,b8 as Ta,b9 as Gn,ba as Oi,bb as Wn,bc as Li,bd as Yn,be as zi,bf as Qn,bg as Jn,bh as Ai,bi as $i,bj as Xn,bk as Ui,bl as Hi,bm as Zn,bn as qi,bo as er,bp as Ki,bq as Bi,br as is,bs as jt,bt as Gi,bu as Wi,bv as Yi,bw as Qi,bx as Ji,by as Xi,bz as Ga,bA as Wa,bB as Zi,bC as eo,bD as so,bE as to,bF as ao,bG as ha,bH as pt,bI as no,bJ as ro,bK as lo,bL as Ya,bM as pa,bN as fa,bO as io,bP as oo,bQ as sr,bR as co,bS as Da,bT as uo,bU as mo,bV as xo,bW as tr,bX as ar,bY as ho,bZ as po,b_ as fo,b$ as go,c0 as jo,c1 as nr,c2 as vo,c3 as bo,c4 as yo,c5 as No,c6 as Rt,c7 as Ve,c8 as Qa,c9 as _o,ca as rr,cb as lr,cc as ir,cd as or,ce as cr,cf as dr,cg as wo,ch as Co,ci as So,cj as Ht,ck as Hs,cl as cs,cm as ns,cn as rs,co as ds,cp as us,cq as ms,cr as ko,cs as To,ct as Do,cu as Po,cv as Eo,cw as Ro,cx as Io,cy as Vo,cz as Mo,cA as ga,cB as Pa,cC as Ea,cD as Fo,cE as Ds,cF as Ps,cG as qt,cH as Oo,cI as It,cJ as Lo,cK as Ja,cL as ur,cM as Xa,cN as Vt,cO as zo,cP as Ao,cQ as $o,cR as Uo,cS as mr,cT as Ho,cU as qo,cV as xr,cW as ja,cX as hr,cY as Ko,cZ as pr,c_ as fr,c$ as Bo,d0 as Go,d1 as Wo,d2 as Yo,d3 as Qo}from"./vendor.js";import"./index.js";var mp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function xp(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Jo(s){if(s.__esModule)return s;var n=s.default;if(typeof n=="function"){var t=function r(){return this instanceof r?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};t.prototype=n.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(r){var a=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return s[r]}})}),t}const Xo={theme:"system",setTheme:()=>null},gr=u.createContext(Xo);function Zo({children:s,defaultTheme:n="system",storageKey:t="vite-ui-theme",...r}){const[a,i]=u.useState(()=>localStorage.getItem(t)||n);u.useEffect(()=>{const d=window.document.documentElement;if(d.classList.remove("light","dark"),a==="system"){const m=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";d.classList.add(m);return}d.classList.add(a)},[a]);const l={theme:a,setTheme:d=>{localStorage.setItem(t,d),i(d)}};return e.jsx(gr.Provider,{...r,value:l,children:s})}const ec=()=>{const s=u.useContext(gr);if(s===void 0)throw new Error("useTheme must be used within a ThemeProvider");return s},sc=function(){const n=typeof document<"u"&&document.createElement("link").relList;return n&&n.supports&&n.supports("modulepreload")?"modulepreload":"preload"}(),tc=function(s,n){return new URL(s,n).href},Za={},me=function(n,t,r){let a=Promise.resolve();if(t&&t.length>0){const l=document.getElementsByTagName("link"),d=document.querySelector("meta[property=csp-nonce]"),m=d?.nonce||d?.getAttribute("nonce");a=Promise.allSettled(t.map(o=>{if(o=tc(o,r),o in Za)return;Za[o]=!0;const c=o.endsWith(".css"),h=c?'[rel="stylesheet"]':"";if(!!r)for(let C=l.length-1;C>=0;C--){const S=l[C];if(S.href===o&&(!c||S.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${o}"]${h}`))return;const E=document.createElement("link");if(E.rel=c?"stylesheet":sc,c||(E.as="script"),E.crossOrigin="",E.href=o,m&&E.setAttribute("nonce",m),document.head.appendChild(E),c)return new Promise((C,S)=>{E.addEventListener("load",C),E.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${o}`)))})}))}function i(l){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=l,window.dispatchEvent(d),!d.defaultPrevented)throw l}return a.then(l=>{for(const d of l||[])d.status==="rejected"&&i(d.reason);return n().catch(i)})};function N(...s){return Sl(kl(s))}const nt=As("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),P=u.forwardRef(({className:s,variant:n,size:t,asChild:r=!1,children:a,disabled:i,loading:l=!1,leftSection:d,rightSection:m,...o},c)=>{const h=r?Na:"button";return e.jsxs(h,{className:N(nt({variant:n,size:t,className:s})),disabled:l||i,ref:c,...o,children:[(d&&l||!d&&!m&&l)&&e.jsx(Ka,{className:"mr-2 h-4 w-4 animate-spin"}),!l&&d&&e.jsx("div",{className:"mr-2",children:d}),a,!l&&m&&e.jsx("div",{className:"ml-2",children:m}),m&&l&&e.jsx(Ka,{className:"ml-2 h-4 w-4 animate-spin"})]})});P.displayName="Button";function Ys({className:s,minimal:n=!1}){const t=Ts();return e.jsx("div",{className:N("h-svh w-full",s),children:e.jsxs("div",{className:"m-auto flex h-full w-full flex-col items-center justify-center gap-2",children:[!n&&e.jsx("h1",{className:"text-[7rem] font-bold leading-tight",children:"500"}),e.jsxs("span",{className:"font-medium",children:["Oops! Something went wrong ",":')"]}),e.jsxs("p",{className:"text-center text-muted-foreground",children:["We apologize for the inconvenience. ",e.jsx("br",{})," Please try again later."]}),!n&&e.jsxs("div",{className:"mt-6 flex gap-4",children:[e.jsx(P,{variant:"outline",onClick:()=>t(-1),children:"Go Back"}),e.jsx(P,{onClick:()=>t("/"),children:"Back to Home"})]})]})})}function en(){const s=Ts();return e.jsx("div",{className:"h-svh",children:e.jsxs("div",{className:"m-auto flex h-full w-full flex-col items-center justify-center gap-2",children:[e.jsx("h1",{className:"text-[7rem] font-bold leading-tight",children:"404"}),e.jsx("span",{className:"font-medium",children:"Oops! Page Not Found!"}),e.jsxs("p",{className:"text-center text-muted-foreground",children:["It seems like the page you're looking for ",e.jsx("br",{}),"does not exist or might have been removed."]}),e.jsxs("div",{className:"mt-6 flex gap-4",children:[e.jsx(P,{variant:"outline",onClick:()=>s(-1),children:"Go Back"}),e.jsx(P,{onClick:()=>s("/"),children:"Back to Home"})]})]})})}function ac(){return e.jsx("div",{className:"h-svh",children:e.jsxs("div",{className:"m-auto flex h-full w-full flex-col items-center justify-center gap-2",children:[e.jsx("h1",{className:"text-[7rem] font-bold leading-tight",children:"503"}),e.jsx("span",{className:"font-medium",children:"Website is under maintenance!"}),e.jsxs("p",{className:"text-center text-muted-foreground",children:["The site is not available at the moment. ",e.jsx("br",{}),"We'll be back online shortly."]}),e.jsx("div",{className:"mt-6 flex gap-4",children:e.jsx(P,{variant:"outline",children:"Learn more"})})]})})}function nc(s){return typeof s>"u"}function rc(s){return s===null}function lc(s){return rc(s)||nc(s)}class ic{storage;prefixKey;constructor(n){this.storage=n.storage,this.prefixKey=n.prefixKey}getKey(n){return`${this.prefixKey}${n}`.toUpperCase()}set(n,t,r=null){const a=JSON.stringify({value:t,time:Date.now(),expire:r!==null?new Date().getTime()+r*1e3:null});this.storage.setItem(this.getKey(n),a)}get(n,t=null){const r=this.storage.getItem(this.getKey(n));if(!r)return{value:t,time:0};try{const a=JSON.parse(r),{value:i,time:l,expire:d}=a;return lc(d)||d>new Date().getTime()?{value:i,time:l}:(this.remove(n),{value:t,time:0})}catch{return this.remove(n),{value:t,time:0}}}remove(n){this.storage.removeItem(this.getKey(n))}clear(){this.storage.clear()}}function jr({prefixKey:s="",storage:n=sessionStorage}){return new ic({prefixKey:s,storage:n})}const vr="Xboard_",oc=function(s={}){return jr({prefixKey:s.prefixKey||"",storage:localStorage})},cc=function(s={}){return jr({prefixKey:s.prefixKey||"",storage:sessionStorage})},Kt=oc({prefixKey:vr});cc({prefixKey:vr});const br="access_token";function ft(){return Kt.get(br)}function yr(){Kt.remove(br)}const sn=["/sign-in","/sign-in-2","/sign-up","/forgot-password","/otp"];function dc({children:s}){const n=Ts(),t=_a(),r=ft();return u.useEffect(()=>{if(!r.value&&!sn.includes(t.pathname)){const a=encodeURIComponent(t.pathname+t.search);n(`/sign-in?redirect=${a}`)}},[r.value,t.pathname,t.search,n]),sn.includes(t.pathname)||r.value?e.jsx(e.Fragment,{children:s}):null}const ke=u.forwardRef(({className:s,orientation:n="horizontal",decorative:t=!0,...r},a)=>e.jsx(fn,{ref:a,decorative:t,orientation:n,className:N("shrink-0 bg-border",n==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));ke.displayName=fn.displayName;const uc=As("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Mt=u.forwardRef(({className:s,...n},t)=>e.jsx(gn,{ref:t,className:N(uc(),s),...n}));Mt.displayName=gn.displayName;const _e=Dl,Nr=u.createContext({}),g=({...s})=>e.jsx(Nr.Provider,{value:{name:s.name},children:e.jsx(Pl,{...s})}),Bt=()=>{const s=u.useContext(Nr),n=u.useContext(_r),{getFieldState:t,formState:r}=Tl(),a=t(s.name,r);if(!s)throw new Error("useFormField should be used within ");const{id:i}=n;return{id:i,name:s.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},_r=u.createContext({}),f=u.forwardRef(({className:s,...n},t)=>{const r=u.useId();return e.jsx(_r.Provider,{value:{id:r},children:e.jsx("div",{ref:t,className:N("space-y-2",s),...n})})});f.displayName="FormItem";const j=u.forwardRef(({className:s,...n},t)=>{const{error:r,formItemId:a}=Bt();return e.jsx(Mt,{ref:t,className:N(r&&"text-destructive",s),htmlFor:a,...n})});j.displayName="FormLabel";const y=u.forwardRef(({...s},n)=>{const{error:t,formItemId:r,formDescriptionId:a,formMessageId:i}=Bt();return e.jsx(Na,{ref:n,id:r,"aria-describedby":t?`${a} ${i}`:`${a}`,"aria-invalid":!!t,...s})});y.displayName="FormControl";const F=u.forwardRef(({className:s,...n},t)=>{const{formDescriptionId:r}=Bt();return e.jsx("p",{ref:t,id:r,className:N("text-[0.8rem] text-muted-foreground",s),...n})});F.displayName="FormDescription";const D=u.forwardRef(({className:s,children:n,...t},r)=>{const{error:a,formMessageId:i}=Bt(),l=a?String(a?.message):n;return l?e.jsx("p",{ref:r,id:i,className:N("text-[0.8rem] font-medium text-destructive",s),...t,children:l}):null});D.displayName="FormMessage";const Gt=El,vt=u.forwardRef(({className:s,...n},t)=>e.jsx(jn,{ref:t,className:N("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",s),...n}));vt.displayName=jn.displayName;const Ge=u.forwardRef(({className:s,...n},t)=>e.jsx(vn,{ref:t,className:N("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",s),...n}));Ge.displayName=vn.displayName;const ws=u.forwardRef(({className:s,...n},t)=>e.jsx(bn,{ref:t,className:N("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...n}));ws.displayName=bn.displayName;function we(s=void 0,n="YYYY-MM-DD HH:mm:ss"){return s==null?"":(Math.floor(s).toString().length===10&&(s=s*1e3),Rl(s).format(n))}function mc(s=void 0,n="YYYY-MM-DD"){return we(s,n)}function Xs(s){const n=typeof s=="string"?parseFloat(s):s;return isNaN(n)?"0.00":n.toFixed(2)}function Ls(s,n=!0){if(s==null)return n?"¥0.00":"0.00";const t=typeof s=="string"?parseFloat(s):s;if(isNaN(t))return n?"¥0.00":"0.00";const a=(t/100).toFixed(2).replace(/\.?0+$/,i=>i.includes(".")?".00":i);return n?`¥${a}`:a}function Ft(s){return new Promise(n=>{(async()=>{try{if(navigator.clipboard)await navigator.clipboard.writeText(s);else{const r=document.createElement("textarea");r.value=s,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select();const a=document.execCommand("copy");if(document.body.removeChild(r),!a)throw new Error("execCommand failed")}n(!0)}catch(r){console.error(r),n(!1)}})()})}function ps(s){const n=s/1024,t=n/1024,r=t/1024,a=r/1024;return a>=1?Xs(a)+" TB":r>=1?Xs(r)+" GB":t>=1?Xs(t)+" MB":Xs(n)+" KB"}const xc="locale";function hc(){return Kt.get(xc)}function wr(){yr();const s=window.location.pathname,n=s&&!["/404","/sign-in"].includes(s),t=new URL(window.location.href),a=`${t.pathname.split("/")[1]?`/${t.pathname.split("/")[1]}`:""}#/sign-in`;window.location.href=a+(n?`?redirect=${s}`:"")}const pc=["/passport/auth/login","/passport/auth/token2Login","/passport/auth/register","/guest/comm/config","/passport/comm/sendEmailVerify","/passport/auth/forget"];function fc(){const s=window.settings?.base_url||"/";return s.endsWith("/")?s+"api/v2":s+"/api/v2"}const I=Il.create({baseURL:fc(),timeout:12e3,headers:{"Content-Type":"application/json"}});I.interceptors.request.use(s=>{s.method?.toLowerCase()==="get"&&(s.params={...s.params,t:Date.now()});const n=ft();if(!pc.includes(s.url?.split("?")[0]||"")){if(!n.value)return wr(),Promise.reject({code:-1,message:"未登录"});s.headers.Authorization=n.value}return s.headers["Content-Language"]=hc().value||"zh-CN",s},s=>Promise.reject(s));I.interceptors.response.use(s=>s?.data||{code:-1,message:"未知错误"},s=>{const n=s.response?.status,t=s.response?.data?.message;return(n===401||n===403)&&wr(),A.error(t||{401:"登录已过期",403:"没有权限",404:"资源或接口不存在"}[n]||"未知异常"),Promise.reject(s.response?.data||{data:null,code:-1,message:"未知错误"})});const gc="access_token";function jc(s){Kt.set(gc,s)}const U=window?.settings?.secure_path,vc=s=>I.get(U+"/stat/getOrder",{params:s}),bc=()=>I.get(U+"/stat/getStats"),tn=s=>I.get(U+"/stat/getTrafficRank",{params:s}),yc=()=>I.get(U+"/theme/getThemes"),Nc=s=>I.post(U+"/theme/getThemeConfig",{name:s}),_c=(s,n)=>I.post(U+"/theme/saveThemeConfig",{name:s,config:n}),wc=s=>{const n=new FormData;return n.append("file",s),I.post(U+"/theme/upload",n,{headers:{"Content-Type":"multipart/form-data"}})},Cc=s=>I.post(U+"/theme/delete",{name:s}),Sc=s=>I.post(U+"/config/save",s),Cr=()=>I.get(U+"/server/manage/getNodes"),kc=s=>I.post(U+"/server/manage/save",s),Tc=s=>I.post(U+"/server/manage/drop",s),Dc=s=>I.post(U+"/server/manage/copy",s),Pc=s=>I.post(U+"/server/manage/update",s),Ec=s=>I.post(U+"/server/manage/sort",s),bt=()=>I.get(U+"/server/group/fetch"),Rc=s=>I.post(U+"/server/group/save",s),Ic=s=>I.post(U+"/server/group/drop",s),Sr=()=>I.get(U+"/server/route/fetch"),Vc=s=>I.post(U+"/server/route/save",s),Mc=s=>I.post(U+"/server/route/drop",s),Fc=()=>I.get(U+"/payment/fetch"),Oc=()=>I.get(U+"/payment/getPaymentMethods"),Lc=s=>I.post(U+"/payment/getPaymentForm",s),zc=s=>I.post(U+"/payment/save",s),Ac=s=>I.post(U+"/payment/drop",s),$c=s=>I.post(U+"/payment/show",s),Uc=s=>I.post(U+"/payment/sort",s),Hc=s=>I.post(U+"/notice/save",s),qc=s=>I.post(U+"/notice/drop",s),Kc=s=>I.post(U+"/notice/show",s),Bc=()=>I.get(U+"/knowledge/fetch"),Gc=s=>I.get(U+"/knowledge/fetch?id="+s),Wc=s=>I.post(U+"/knowledge/save",s),Yc=s=>I.post(U+"/knowledge/drop",s),Qc=s=>I.post(U+"/knowledge/show",s),Jc=s=>I.post(U+"/knowledge/sort",s),qs=()=>I.get(U+"/plan/fetch"),Xc=s=>I.post(U+"/plan/save",s),aa=s=>I.post(U+"/plan/update",s),Zc=s=>I.post(U+"/plan/drop",s),ed=s=>I.post(U+"/plan/sort",{ids:s}),sd=async s=>I.post(U+"/order/fetch",s),td=s=>I.post(U+"/order/detail",s),ad=s=>I.post(U+"/order/paid",s),nd=s=>I.post(U+"/order/cancel",s),an=s=>I.post(U+"/order/update",s),rd=s=>I.post(U+"/order/assign",s),ld=s=>I.post(U+"/coupon/fetch",s),id=s=>I.post(U+"/coupon/generate",s),od=s=>I.post(U+"/coupon/drop",s),cd=s=>I.post(U+"/coupon/update",s),dd=s=>I.post(U+"/user/fetch",s),ud=s=>I.post(U+"/user/update",s),md=s=>I.post(U+"/user/resetSecret",s),xd=s=>I.post(U+"/user/generate",s),hd=s=>I.post(U+"/stat/getStatUser",s),pd=s=>I.post(U+"/ticket/fetch",s),fd=s=>I.get(U+"/ticket/fetch?id= "+s),gd=s=>I.post(U+"/ticket/close",{id:s}),gs=(s="")=>I.get(U+"/config/fetch?key="+s),js=s=>I.post(U+"/config/save",s),jd=()=>I.get(U+"/config/getEmailTemplate"),vd=()=>I.post(U+"/config/testSendMail"),bd=()=>I.post(U+"/config/setTelegramWebhook"),yd=x.object({subscribe_template_singbox:x.string().nullable(),subscribe_template_clash:x.string().nullable(),subscribe_template_clashmeta:x.string().nullable(),subscribe_template_stash:x.string().nullable(),subscribe_template_surge:x.string().nullable()}),Nd={subscribe_template_singbox:"",subscribe_template_clash:"",subscribe_template_clashmeta:"",subscribe_template_stash:"",subscribe_template_surge:""};function _d(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),[a,i]=u.useState("singbox"),l=ge({resolver:Ne(yd),defaultValues:Nd,mode:"onBlur"}),{data:d}=re({queryKey:["settings","client"],queryFn:()=>gs("subscribe_template")}),{mutateAsync:m}=es({mutationFn:js,onSuccess:h=>{h.data&&A.success(s("common.autoSaved"))}});u.useEffect(()=>{if(d?.data.subscribe_template){const h=d.data.subscribe_template;Object.entries(h).forEach(([_,E])=>{l.setValue(_,E)}),r.current=h}},[d]),console.log(l.getValues());const o=u.useCallback(Se.debounce(async h=>{if(!Se.isEqual(h,r.current)){t(!0);try{await m(h),r.current=h}finally{t(!1)}}},1e3),[m]),c=u.useCallback(h=>{o(h)},[o]);return e.jsx(_e,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Gt,{value:a,onValueChange:i,children:[e.jsxs(vt,{children:[e.jsx(Ge,{value:"singbox",children:"Sing-box"}),e.jsx(Ge,{value:"clash",children:"Clash"}),e.jsx(Ge,{value:"clashmeta",children:"Clash Meta"}),e.jsx(Ge,{value:"stash",children:"Stash"}),e.jsx(Ge,{value:"surge",children:"Surge"})]}),e.jsx(ws,{value:"singbox",children:e.jsx(g,{control:l.control,name:"subscribe_template_singbox",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe_template.singbox.title")}),e.jsx(y,{children:e.jsx(it,{height:"500px",defaultLanguage:"json",value:h.value||"",onChange:_=>{typeof _=="string"&&(h.onChange(_),c(l.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(F,{children:s("subscribe_template.singbox.description")}),e.jsx(D,{})]})})}),e.jsx(ws,{value:"clash",children:e.jsx(g,{control:l.control,name:"subscribe_template_clash",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe_template.clash.title")}),e.jsx(y,{children:e.jsx(it,{height:"500px",defaultLanguage:"yaml",value:h.value||"",onChange:_=>{typeof _=="string"&&(h.onChange(_),c(l.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(F,{children:s("subscribe_template.clash.description")}),e.jsx(D,{})]})})}),e.jsx(ws,{value:"clashmeta",children:e.jsx(g,{control:l.control,name:"subscribe_template_clashmeta",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe_template.clashmeta.title")}),e.jsx(y,{children:e.jsx(it,{height:"500px",defaultLanguage:"yaml",value:h.value||"",onChange:_=>{typeof _=="string"&&(h.onChange(_),c(l.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(F,{children:s("subscribe_template.clashmeta.description")}),e.jsx(D,{})]})})}),e.jsx(ws,{value:"stash",children:e.jsx(g,{control:l.control,name:"subscribe_template_stash",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe_template.stash.title")}),e.jsx(y,{children:e.jsx(it,{height:"500px",defaultLanguage:"yaml",value:h.value||"",onChange:_=>{typeof _=="string"&&(h.onChange(_),c(l.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(F,{children:s("subscribe_template.stash.description")}),e.jsx(D,{})]})})}),e.jsx(ws,{value:"surge",children:e.jsx(g,{control:l.control,name:"subscribe_template_surge",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe_template.surge.title")}),e.jsx(y,{children:e.jsx(it,{height:"500px",defaultLanguage:"ini",value:h.value||"",onChange:_=>{typeof _=="string"&&(h.onChange(_),c(l.getValues()))},options:{minimap:{enabled:!1},fontSize:14}})}),e.jsx(F,{children:s("subscribe_template.surge.description")}),e.jsx(D,{})]})})})]}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function wd(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("subscribe_template.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("subscribe_template.description")})]}),e.jsx(ke,{}),e.jsx(_d,{})]})}const Cd=()=>e.jsx(dc,{children:e.jsx(wa,{})}),Sd=Vl([{path:"/sign-in",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Hd);return{default:s}},void 0,import.meta.url)).default})},{element:e.jsx(Cd,{}),children:[{path:"/",lazy:async()=>({Component:(await me(()=>Promise.resolve().then(()=>Xd),void 0,import.meta.url)).default}),errorElement:e.jsx(Ys,{}),children:[{index:!0,lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Nu);return{default:s}},void 0,import.meta.url)).default})},{path:"config",errorElement:e.jsx(Ys,{}),children:[{path:"system",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Su);return{default:s}},void 0,import.meta.url)).default}),children:[{index:!0,lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Pu);return{default:s}},void 0,import.meta.url)).default})},{path:"safe",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Mu);return{default:s}},void 0,import.meta.url)).default})},{path:"subscribe",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Au);return{default:s}},void 0,import.meta.url)).default})},{path:"invite",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Ku);return{default:s}},void 0,import.meta.url)).default})},{path:"frontend",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Qu);return{default:s}},void 0,import.meta.url)).default})},{path:"server",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>sm);return{default:s}},void 0,import.meta.url)).default})},{path:"email",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>lm);return{default:s}},void 0,import.meta.url)).default})},{path:"telegram",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>um);return{default:s}},void 0,import.meta.url)).default})},{path:"APP",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>fm);return{default:s}},void 0,import.meta.url)).default})},{path:"subscribe-template",element:e.jsx(wd,{})}]},{path:"payment",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Sm);return{default:s}},void 0,import.meta.url)).default})},{path:"plugin",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Dm);return{default:s}},void 0,import.meta.url)).default})},{path:"theme",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Im);return{default:s}},void 0,import.meta.url)).default})},{path:"notice",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Am);return{default:s}},void 0,import.meta.url)).default})},{path:"knowledge",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Wm);return{default:s}},void 0,import.meta.url)).default})}]},{path:"server",errorElement:e.jsx(Ys,{}),children:[{path:"manage",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>wx);return{default:s}},void 0,import.meta.url)).default})},{path:"group",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Dx);return{default:s}},void 0,import.meta.url)).default})},{path:"route",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Mx);return{default:s}},void 0,import.meta.url)).default})}]},{path:"finance",errorElement:e.jsx(Ys,{}),children:[{path:"plan",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>qx);return{default:s}},void 0,import.meta.url)).default})},{path:"order",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>nh);return{default:s}},void 0,import.meta.url)).default})},{path:"coupon",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>xh);return{default:s}},void 0,import.meta.url)).default})}]},{path:"user",errorElement:e.jsx(Ys,{}),children:[{path:"manage",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>Hh);return{default:s}},void 0,import.meta.url)).default})},{path:"ticket",lazy:async()=>({Component:(await me(async()=>{const{default:s}=await Promise.resolve().then(()=>cp);return{default:s}},void 0,import.meta.url)).default})}]}]}]},{path:"/500",Component:Ys},{path:"/404",Component:en},{path:"/503",Component:ac},{path:"*",Component:en}]);function kd(){return I.get("/user/info")}const na={token:ft()?.value||"",userInfo:null,isLoggedIn:!!ft()?.value,loading:!1,error:null},mt=Ml("user/fetchUserInfo",async()=>(await kd()).data,{condition:(s,{getState:n})=>{const{user:t}=n();return!!t.token&&!t.loading}}),kr=Fl({name:"user",initialState:na,reducers:{setToken(s,n){s.token=n.payload,s.isLoggedIn=!!n.payload},resetUserState:()=>na},extraReducers:s=>{s.addCase(mt.pending,n=>{n.loading=!0,n.error=null}).addCase(mt.fulfilled,(n,t)=>{n.loading=!1,n.userInfo=t.payload,n.error=null}).addCase(mt.rejected,(n,t)=>{if(n.loading=!1,n.error=t.error.message||"Failed to fetch user info",!n.token)return na})}}),{setToken:Td,resetUserState:Dd}=kr.actions,Pd=s=>s.user.userInfo,Ed=kr.reducer,Tr=Ol({reducer:{user:Ed}});ft()?.value&&Tr.dispatch(mt());Ll.use(zl).use(Al).init({resources:{"en-US":window.XBOARD_TRANSLATIONS?.["en-US"]||{},"zh-CN":window.XBOARD_TRANSLATIONS?.["zh-CN"]||{},"ko-KR":window.XBOARD_TRANSLATIONS?.["ko-KR"]||{}},fallbackLng:"zh-CN",supportedLngs:["en-US","zh-CN","ko-KR"],detection:{order:["querystring","localStorage","navigator"],lookupQuerystring:"lang",lookupLocalStorage:"i18nextLng",caches:["localStorage"]},interpolation:{escapeValue:!1}});const Rd=new $l;Ul.createRoot(document.getElementById("root")).render(e.jsx(Hl.StrictMode,{children:e.jsx(ql,{client:Rd,children:e.jsx(Kl,{store:Tr,children:e.jsxs(Zo,{defaultTheme:"light",storageKey:"vite-ui-theme",children:[e.jsx(Bl,{router:Sd}),e.jsx(Gl,{richColors:!0,position:"top-right"})]})})})}));const We=u.forwardRef(({className:s,...n},t)=>e.jsx("div",{ref:t,className:N("rounded-xl border bg-card text-card-foreground shadow",s),...n}));We.displayName="Card";const ts=u.forwardRef(({className:s,...n},t)=>e.jsx("div",{ref:t,className:N("flex flex-col space-y-1.5 p-6",s),...n}));ts.displayName="CardHeader";const Cs=u.forwardRef(({className:s,...n},t)=>e.jsx("h3",{ref:t,className:N("font-semibold leading-none tracking-tight",s),...n}));Cs.displayName="CardTitle";const et=u.forwardRef(({className:s,...n},t)=>e.jsx("p",{ref:t,className:N("text-sm text-muted-foreground",s),...n}));et.displayName="CardDescription";const as=u.forwardRef(({className:s,...n},t)=>e.jsx("div",{ref:t,className:N("p-6 pt-0",s),...n}));as.displayName="CardContent";const Id=u.forwardRef(({className:s,...n},t)=>e.jsx("div",{ref:t,className:N("flex items-center p-6 pt-0",s),...n}));Id.displayName="CardFooter";const T=u.forwardRef(({className:s,type:n,...t},r)=>e.jsx("input",{type:n,className:N("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:r,...t}));T.displayName="Input";const Dr=u.forwardRef(({className:s,...n},t)=>{const[r,a]=u.useState(!1);return e.jsxs("div",{className:"relative rounded-md",children:[e.jsx("input",{type:r?"text":"password",className:N("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:t,...n}),e.jsx(P,{type:"button",size:"icon",variant:"ghost",className:"absolute right-1 top-1/2 h-6 w-6 -translate-y-1/2 rounded-md text-muted-foreground",onClick:()=>a(i=>!i),children:r?e.jsx(Wl,{size:18}):e.jsx(Yl,{size:18})})]})});Dr.displayName="PasswordInput";const Vd=s=>I({url:"/passport/auth/login",method:"post",data:s});function Md({className:s,onForgotPassword:n,...t}){const r=Ts(),a=yn(),{t:i}=V("auth"),l=x.object({email:x.string().min(1,{message:i("signIn.validation.emailRequired")}),password:x.string().min(1,{message:i("signIn.validation.passwordRequired")}).min(7,{message:i("signIn.validation.passwordLength")})}),d=ge({resolver:Ne(l),defaultValues:{email:"",password:""}});async function m(o){try{const{data:c}=await Vd(o);jc(c.auth_data),a(Td(c.auth_data)),await a(mt()).unwrap(),r("/")}catch(c){console.error("Login failed:",c),c.response?.data?.message&&d.setError("root",{message:c.response.data.message})}}return e.jsx("div",{className:N("grid gap-6",s),...t,children:e.jsx(_e,{...d,children:e.jsx("form",{onSubmit:d.handleSubmit(m),className:"space-y-4",children:e.jsxs("div",{className:"space-y-4",children:[d.formState.errors.root&&e.jsx("div",{className:"text-sm text-destructive",children:d.formState.errors.root.message}),e.jsx(g,{control:d.control,name:"email",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:i("signIn.email")}),e.jsx(y,{children:e.jsx(T,{placeholder:i("signIn.emailPlaceholder"),autoComplete:"email",...o})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"password",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:i("signIn.password")}),e.jsx(y,{children:e.jsx(Dr,{placeholder:i("signIn.passwordPlaceholder"),autoComplete:"current-password",...o})}),e.jsx(D,{})]})}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(P,{variant:"link",type:"button",className:"px-0 text-sm font-normal text-muted-foreground hover:text-primary",onClick:n,children:i("signIn.forgotPassword")})}),e.jsx(P,{className:"w-full",size:"lg",loading:d.formState.isSubmitting,children:i("signIn.submit")})]})})})})}const be=Nn,Je=_n,Fd=wn,yt=Ca,Pr=u.forwardRef(({className:s,...n},t)=>e.jsx(zt,{ref:t,className:N("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...n}));Pr.displayName=zt.displayName;const fe=u.forwardRef(({className:s,children:n,...t},r)=>e.jsxs(Fd,{children:[e.jsx(Pr,{}),e.jsxs(At,{ref:r,className:N("max-h-[95%] overflow-auto fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...t,children:[n,e.jsxs(Ca,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(ss,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));fe.displayName=At.displayName;const Ce=({className:s,...n})=>e.jsx("div",{className:N("flex flex-col space-y-1.5 text-center sm:text-left",s),...n});Ce.displayName="DialogHeader";const ze=({className:s,...n})=>e.jsx("div",{className:N("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...n});ze.displayName="DialogFooter";const ye=u.forwardRef(({className:s,...n},t)=>e.jsx($t,{ref:t,className:N("text-lg font-semibold leading-none tracking-tight",s),...n}));ye.displayName=$t.displayName;const Te=u.forwardRef(({className:s,...n},t)=>e.jsx(Ut,{ref:t,className:N("text-sm text-muted-foreground",s),...n}));Te.displayName=Ut.displayName;const st=As("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),J=u.forwardRef(({className:s,variant:n,size:t,asChild:r=!1,...a},i)=>{const l=r?Na:"button";return e.jsx(l,{className:N(st({variant:n,size:t,className:s})),ref:i,...a})});J.displayName="Button";const Ss=Xl,ks=Zl,Od=ei,Ld=u.forwardRef(({className:s,inset:n,children:t,...r},a)=>e.jsxs(Cn,{ref:a,className:N("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",n&&"pl-8",s),...r,children:[t,e.jsx(Sa,{className:"ml-auto h-4 w-4"})]}));Ld.displayName=Cn.displayName;const zd=u.forwardRef(({className:s,...n},t)=>e.jsx(Sn,{ref:t,className:N("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n}));zd.displayName=Sn.displayName;const fs=u.forwardRef(({className:s,sideOffset:n=4,...t},r)=>e.jsx(Ql,{children:e.jsx(kn,{ref:r,sideOffset:n,className:N("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...t})}));fs.displayName=kn.displayName;const je=u.forwardRef(({className:s,inset:n,...t},r)=>e.jsx(Tn,{ref:r,className:N("relative flex cursor-default cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",s),...t}));je.displayName=Tn.displayName;const Ad=u.forwardRef(({className:s,children:n,checked:t,...r},a)=>e.jsxs(Dn,{ref:a,className:N("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),checked:t,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Pn,{children:e.jsx($s,{className:"h-4 w-4"})})}),n]}));Ad.displayName=Dn.displayName;const $d=u.forwardRef(({className:s,children:n,...t},r)=>e.jsxs(En,{ref:r,className:N("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...t,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Pn,{children:e.jsx(Jl,{className:"h-4 w-4 fill-current"})})}),n]}));$d.displayName=En.displayName;const Ra=u.forwardRef(({className:s,inset:n,...t},r)=>e.jsx(Rn,{ref:r,className:N("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",s),...t}));Ra.displayName=Rn.displayName;const tt=u.forwardRef(({className:s,...n},t)=>e.jsx(In,{ref:t,className:N("-mx-1 my-1 h-px bg-muted",s),...n}));tt.displayName=In.displayName;const va=({className:s,...n})=>e.jsx("span",{className:N("ml-auto text-xs tracking-widest opacity-60",s),...n});va.displayName="DropdownMenuShortcut";const ra=[{code:"en-US",name:"English",flag:si,shortName:"EN"},{code:"zh-CN",name:"中文",flag:ti,shortName:"CN"},{code:"ko-KR",name:"한국어",flag:ai,shortName:"KR"}];function Er(){const{i18n:s}=V(),n=a=>{s.changeLanguage(a)},t=ra.find(a=>a.code===s.language)||ra[1],r=t.flag;return e.jsxs(Ss,{children:[e.jsx(ks,{asChild:!0,children:e.jsxs(J,{variant:"ghost",size:"sm",className:"h-8 px-2 gap-1",children:[e.jsx(r,{className:"h-4 w-5 rounded-sm shadow-sm"}),e.jsx("span",{className:"text-sm font-medium",children:t.shortName})]})}),e.jsx(fs,{align:"end",className:"w-[120px]",children:ra.map(a=>{const i=a.flag,l=a.code===s.language;return e.jsxs(je,{onClick:()=>n(a.code),className:N("flex items-center gap-2 px-2 py-1.5 cursor-pointer",l&&"bg-accent"),children:[e.jsx(i,{className:"h-4 w-5 rounded-sm shadow-sm"}),e.jsx("span",{className:N("text-sm",l&&"font-medium"),children:a.name})]},a.code)})})]})}function Ud(){const[s,n]=u.useState(!1),{t}=V("auth"),r=t("signIn.resetPassword.command");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"container relative grid h-svh flex-col items-center justify-center bg-primary-foreground lg:max-w-none lg:px-0",children:[e.jsx("div",{className:"absolute right-4 top-4 md:right-8 md:top-8",children:e.jsx(Er,{})}),e.jsxs("div",{className:"mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[480px] lg:p-8",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-center",children:[e.jsx("h1",{className:"text-3xl font-bold",children:window?.settings?.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:window?.settings?.description})]}),e.jsxs(We,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-col space-y-2 text-left",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:t("signIn.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t("signIn.description")})]}),e.jsx(Md,{onForgotPassword:()=>n(!0)})]})]})]}),e.jsx(be,{open:s,onOpenChange:n,children:e.jsx(fe,{children:e.jsxs(Ce,{children:[e.jsx(ye,{children:t("signIn.resetPassword.title")}),e.jsx(Te,{children:t("signIn.resetPassword.description")}),e.jsx("div",{className:"mt-4",children:e.jsxs("div",{className:"relative",children:[e.jsx("pre",{className:"rounded-md bg-secondary p-4 pr-12 text-sm",children:r}),e.jsx(J,{variant:"ghost",size:"icon",className:"absolute right-2 top-2 h-8 w-8 hover:bg-secondary-foreground/10",onClick:()=>Ft(r).then(()=>{A.success(t("common:copy.success"))}),children:e.jsx(ni,{className:"h-4 w-4"})})]})})]})})})]})}const Hd=Object.freeze(Object.defineProperty({__proto__:null,default:Ud},Symbol.toStringTag,{value:"Module"})),Ee=u.forwardRef(({className:s,fadedBelow:n=!1,fixedHeight:t=!1,...r},a)=>e.jsx("div",{ref:a,className:N("relative flex h-full w-full flex-col",n&&"after:pointer-events-none after:absolute after:bottom-0 after:left-0 after:hidden after:h-32 after:w-full after:bg-[linear-gradient(180deg,_transparent_10%,_hsl(var(--background))_70%)] after:md:block",t&&"md:h-svh",s),...r}));Ee.displayName="Layout";const Re=u.forwardRef(({className:s,...n},t)=>e.jsx("div",{ref:t,className:N("flex h-[var(--header-height)] flex-none items-center gap-4 bg-background p-4 md:px-8",s),...n}));Re.displayName="LayoutHeader";const Fe=u.forwardRef(({className:s,fixedHeight:n,...t},r)=>e.jsx("div",{ref:r,className:N("flex-1 overflow-hidden px-4 py-6 md:px-8",n&&"h-[calc(100%-var(--header-height))]",s),...t}));Fe.displayName="LayoutBody";const Rr=ri,Ir=li,Vr=ii,ve=oi,he=ci,pe=di,ce=u.forwardRef(({className:s,sideOffset:n=4,...t},r)=>e.jsx(Vn,{ref:r,sideOffset:n,className:N("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...t}));ce.displayName=Vn.displayName;function Wt(){const{pathname:s}=_a();return{checkActiveNav:t=>{if(t==="/"&&s==="/")return!0;const r=t.replace(/^\//,""),a=s.replace(/^\//,"");return r?a.startsWith(r):!1}}}function Mr({key:s,defaultValue:n}){const[t,r]=u.useState(()=>{const a=localStorage.getItem(s);return a!==null?JSON.parse(a):n});return u.useEffect(()=>{localStorage.setItem(s,JSON.stringify(t))},[t,s]),[t,r]}function qd(){const[s,n]=Mr({key:"collapsed-sidebar-items",defaultValue:[]}),t=a=>!s.includes(a);return{isExpanded:t,toggleItem:a=>{t(a)?n([...s,a]):n(s.filter(i=>i!==a))}}}function Kd({links:s,isCollapsed:n,className:t,closeNav:r}){const{t:a}=V(),i=({sub:l,...d})=>{const m=`${a(d.title)}-${d.href}`;return n&&l?u.createElement(Wd,{...d,sub:l,key:m,closeNav:r}):n?u.createElement(Gd,{...d,key:m,closeNav:r}):l?u.createElement(Bd,{...d,sub:l,key:m,closeNav:r}):u.createElement(Fr,{...d,key:m,closeNav:r})};return e.jsx("div",{"data-collapsed":n,className:N("group border-b bg-background py-2 transition-[max-height,padding] duration-500 data-[collapsed=true]:py-2 md:border-none",t),children:e.jsx(ve,{delayDuration:0,children:e.jsx("nav",{className:"grid gap-1 group-[[data-collapsed=true]]:justify-center group-[[data-collapsed=true]]:px-2",children:s.map(i)})})})}function Fr({title:s,icon:n,label:t,href:r,closeNav:a,subLink:i=!1}){const{checkActiveNav:l}=Wt(),{t:d}=V();return e.jsxs(Us,{to:r,onClick:a,className:N(nt({variant:l(r)?"secondary":"ghost",size:"sm"}),"h-12 justify-start text-wrap rounded-none px-6",i&&"h-10 w-full border-l border-l-slate-500 px-2"),"aria-current":l(r)?"page":void 0,children:[e.jsx("div",{className:"mr-2",children:n}),d(s),t&&e.jsx("div",{className:"ml-2 rounded-lg bg-primary px-1 text-[0.625rem] text-primary-foreground",children:d(t)})]})}function Bd({title:s,icon:n,label:t,sub:r,closeNav:a}){const{checkActiveNav:i}=Wt(),{isExpanded:l,toggleItem:d}=qd(),{t:m}=V(),o=!!r?.find(_=>i(_.href)),c=m(s),h=l(c)||o;return e.jsxs(Rr,{open:h,onOpenChange:()=>d(c),children:[e.jsxs(Ir,{className:N(nt({variant:o?"secondary":"ghost",size:"sm"}),"group h-12 w-full justify-start rounded-none px-6"),children:[e.jsx("div",{className:"mr-2",children:n}),m(s),t&&e.jsx("div",{className:"ml-2 rounded-lg bg-primary px-1 text-[0.625rem] text-primary-foreground",children:m(t)}),e.jsx("span",{className:N('ml-auto transition-all group-data-[state="open"]:-rotate-180'),children:e.jsx(Mn,{stroke:1})})]}),e.jsx(Vr,{className:"collapsibleDropdown",asChild:!0,children:e.jsx("ul",{children:r.map(_=>e.jsx("li",{className:"my-1 ml-8",children:e.jsx(Fr,{..._,subLink:!0,closeNav:a})},m(_.title)))})})]})}function Gd({title:s,icon:n,label:t,href:r,closeNav:a}){const{checkActiveNav:i}=Wt(),{t:l}=V();return e.jsxs(he,{delayDuration:0,children:[e.jsx(pe,{asChild:!0,children:e.jsxs(Us,{to:r,onClick:a,className:N(nt({variant:i(r)?"secondary":"ghost",size:"icon"}),"h-12 w-12"),children:[n,e.jsx("span",{className:"sr-only",children:l(s)})]})}),e.jsxs(ce,{side:"right",className:"flex items-center gap-4",children:[l(s),t&&e.jsx("span",{className:"ml-auto text-muted-foreground",children:l(t)})]})]})}function Wd({title:s,icon:n,label:t,sub:r,closeNav:a}){const{checkActiveNav:i}=Wt(),{t:l}=V(),d=!!r?.find(m=>i(m.href));return e.jsxs(Ss,{children:[e.jsxs(he,{delayDuration:0,children:[e.jsx(pe,{asChild:!0,children:e.jsx(ks,{asChild:!0,children:e.jsx(P,{variant:d?"secondary":"ghost",size:"icon",className:"h-12 w-12",children:n})})}),e.jsxs(ce,{side:"right",className:"flex items-center gap-4",children:[l(s)," ",t&&e.jsx("span",{className:"ml-auto text-muted-foreground",children:l(t)}),e.jsx(Mn,{size:18,className:"-rotate-90 text-muted-foreground"})]})]}),e.jsxs(fs,{side:"right",align:"start",sideOffset:4,children:[e.jsxs(Ra,{children:[l(s)," ",t?`(${l(t)})`:""]}),e.jsx(tt,{}),r.map(({title:m,icon:o,label:c,href:h})=>e.jsx(je,{asChild:!0,children:e.jsxs(Us,{to:h,onClick:a,className:`${i(h)?"bg-secondary":""}`,children:[o," ",e.jsx("span",{className:"ml-2 max-w-52 text-wrap",children:l(m)}),c&&e.jsx("span",{className:"ml-auto text-xs",children:l(c)})]})},`${l(m)}-${h}`))]})]})}const Or=[{title:"nav:dashboard",label:"",href:"/",icon:e.jsx(ui,{size:18})},{title:"nav:systemManagement",label:"",href:"",icon:e.jsx(mi,{size:18}),sub:[{title:"nav:systemConfig",label:"",href:"/config/system",icon:e.jsx(Fn,{size:18})},{title:"nav:pluginManagement",label:"",href:"/config/plugin",icon:e.jsx(ka,{size:18})},{title:"nav:themeConfig",label:"",href:"/config/theme",icon:e.jsx(xi,{size:18})},{title:"nav:noticeManagement",label:"",href:"/config/notice",icon:e.jsx(hi,{size:18})},{title:"nav:paymentConfig",label:"",href:"/config/payment",icon:e.jsx(Ba,{size:18})},{title:"nav:knowledgeManagement",label:"",href:"/config/knowledge",icon:e.jsx(pi,{size:18})}]},{title:"nav:nodeManagement",label:"",href:"",icon:e.jsx(On,{size:18}),sub:[{title:"nav:nodeManagement",label:"",href:"/server/manage",icon:e.jsx(fi,{size:18})},{title:"nav:permissionGroupManagement",label:"",href:"/server/group",icon:e.jsx(Ln,{size:18})},{title:"nav:routeManagement",label:"",href:"/server/route",icon:e.jsx(gi,{size:18})}]},{title:"nav:subscriptionManagement",label:"",href:"",icon:e.jsx(ji,{size:18}),sub:[{title:"nav:planManagement",label:"",href:"/finance/plan",icon:e.jsx(vi,{size:18})},{title:"nav:orderManagement",label:"",href:"/finance/order",icon:e.jsx(Ba,{size:18})},{title:"nav:couponManagement",label:"",href:"/finance/coupon",icon:e.jsx(bi,{size:18})}]},{title:"nav:userManagement",label:"",href:"",icon:e.jsx(yi,{size:18}),sub:[{title:"nav:userManagement",label:"",href:"/user/manage",icon:e.jsx(Ni,{size:18})},{title:"nav:ticketManagement",label:"",href:"/user/ticket",icon:e.jsx(zn,{size:18})}]}];function Yd({className:s,isCollapsed:n,setIsCollapsed:t}){const[r,a]=u.useState(!1),{t:i}=V();return u.useEffect(()=>{r?document.body.classList.add("overflow-hidden"):document.body.classList.remove("overflow-hidden")},[r]),e.jsxs("aside",{className:N(`fixed left-0 right-0 top-0 z-50 flex h-auto flex-col border-r-2 border-r-muted transition-[width] md:bottom-0 md:right-auto md:h-svh ${n?"md:w-14":"md:w-64"}`,s),children:[e.jsx("div",{onClick:()=>a(!1),className:`absolute inset-0 transition-[opacity] delay-100 duration-700 ${r?"h-svh opacity-50":"h-0 opacity-0"} w-full bg-black md:hidden`}),e.jsxs(Ee,{className:"flex h-full flex-col",children:[e.jsxs(Re,{className:"sticky top-0 justify-between px-4 py-3 shadow md:px-4",children:[e.jsxs("div",{className:`flex items-center ${n?"":"gap-2"}`,children:[e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",className:`transition-all ${n?"h-6 w-6":"h-8 w-8"}`,children:[e.jsx("rect",{width:"256",height:"256",fill:"none"}),e.jsx("line",{x1:"208",y1:"128",x2:"128",y2:"208",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"16"}),e.jsx("line",{x1:"192",y1:"40",x2:"40",y2:"192",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"16"}),e.jsx("span",{className:"sr-only",children:"Website Name"})]}),e.jsx("div",{className:`flex flex-col justify-end truncate ${n?"invisible w-0":"visible w-auto"}`,children:e.jsx("span",{className:"font-medium",children:window?.settings?.title})})]}),e.jsx(P,{variant:"ghost",size:"icon",className:"md:hidden","aria-label":i("common:toggleNavigation"),"aria-controls":"sidebar-menu","aria-expanded":r,onClick:()=>a(l=>!l),children:r?e.jsx(_i,{}):e.jsx(wi,{})})]}),e.jsx(Kd,{id:"sidebar-menu",className:N("flex-1 overflow-auto",r?"block":"hidden md:block","md:py-2"),closeNav:()=>a(!1),isCollapsed:n,links:Or}),e.jsx("div",{className:N("border-t border-border/50 bg-background","px-4 py-2.5 text-xs text-muted-foreground",r?"block":"hidden md:block",n?"text-center":"text-left"),children:e.jsxs("div",{className:N("flex items-center gap-1.5",n?"justify-center":"justify-start"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-green-500"}),e.jsxs("span",{className:N("tracking-wide whitespace-nowrap","transition-opacity duration-200",n&&"md:opacity-0"),children:["v",window?.settings?.version]})]})}),e.jsx(P,{onClick:()=>t(l=>!l),size:"icon",variant:"outline",className:"absolute -right-5 top-1/2 hidden rounded-full md:inline-flex","aria-label":i("common:toggleSidebar"),children:e.jsx(Ci,{stroke:1.5,className:`h-5 w-5 ${n?"rotate-180":""}`})})]})]})}function Qd(){const[s,n]=Mr({key:"collapsed-sidebar",defaultValue:!1});return u.useEffect(()=>{const t=()=>{n(window.innerWidth<768?!1:s)};return t(),window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t)}},[s,n]),[s,n]}function Jd(){const[s,n]=Qd();return e.jsxs("div",{className:"relative h-full overflow-hidden bg-background",children:[e.jsx(Yd,{isCollapsed:s,setIsCollapsed:n}),e.jsx("main",{id:"content",className:`overflow-x-hidden pt-16 transition-[margin] md:overflow-y-hidden md:pt-0 ${s?"md:ml-14":"md:ml-64"} h-full`,children:e.jsx(wa,{})})]})}const Xd=Object.freeze(Object.defineProperty({__proto__:null,default:Jd},Symbol.toStringTag,{value:"Module"})),Ms=u.forwardRef(({className:s,...n},t)=>e.jsx(Le,{ref:t,className:N("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...n}));Ms.displayName=Le.displayName;const Zd=({children:s,...n})=>e.jsx(be,{...n,children:e.jsx(fe,{className:"overflow-hidden p-0",children:e.jsx(Ms,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:s})})}),Ks=u.forwardRef(({className:s,...n},t)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Si,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Le.Input,{ref:t,className:N("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",s),...n})]}));Ks.displayName=Le.Input.displayName;const Fs=u.forwardRef(({className:s,...n},t)=>e.jsx(Le.List,{ref:t,className:N("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...n}));Fs.displayName=Le.List.displayName;const Bs=u.forwardRef((s,n)=>e.jsx(Le.Empty,{ref:n,className:"py-6 text-center text-sm",...s}));Bs.displayName=Le.Empty.displayName;const Ye=u.forwardRef(({className:s,...n},t)=>e.jsx(Le.Group,{ref:t,className:N("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",s),...n}));Ye.displayName=Le.Group.displayName;const rt=u.forwardRef(({className:s,...n},t)=>e.jsx(Le.Separator,{ref:t,className:N("-mx-1 h-px bg-border",s),...n}));rt.displayName=Le.Separator.displayName;const Me=u.forwardRef(({className:s,...n},t)=>e.jsx(Le.Item,{ref:t,className:N("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...n}));Me.displayName=Le.Item.displayName;function eu(){const s=[];for(const n of Or)if(n.href&&s.push(n),n.sub)for(const t of n.sub)s.push({...t,parent:n.title});return s}function Ke(){const[s,n]=u.useState(!1),t=Ts(),r=eu(),{t:a}=V("search"),{t:i}=V("nav");u.useEffect(()=>{const d=m=>{m.key==="k"&&(m.metaKey||m.ctrlKey)&&(m.preventDefault(),n(o=>!o))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[]);const l=u.useCallback(d=>{n(!1),t(d)},[t]);return e.jsxs(e.Fragment,{children:[e.jsxs(J,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-10 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>n(!0),children:[e.jsx(An,{className:"h-4 w-4 xl:mr-2"}),e.jsx("span",{className:"hidden xl:inline-flex",children:a("placeholder")}),e.jsx("span",{className:"sr-only",children:a("shortcut.label")}),e.jsx("kbd",{className:"pointer-events-none absolute right-1.5 top-2 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:a("shortcut.key")})]}),e.jsxs(Zd,{open:s,onOpenChange:n,children:[e.jsx(Ks,{placeholder:a("placeholder")}),e.jsxs(Fs,{children:[e.jsx(Bs,{children:a("noResults")}),e.jsx(Ye,{heading:a("title"),children:r.map(d=>e.jsxs(Me,{value:`${d.parent?d.parent+" ":""}${d.title}`,onSelect:()=>l(d.href),children:[e.jsx("div",{className:"mr-2",children:d.icon}),e.jsx("span",{children:i(d.title)}),d.parent&&e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:i(d.parent)})]},d.href))})]})]})]})}const ne=window?.settings?.secure_path,Lr=5*60*1e3,ba=new Map,su=s=>{const n=ba.get(s);return n?Date.now()-n.timestamp>Lr?(ba.delete(s),null):n.data:null},tu=(s,n)=>{ba.set(s,{data:n,timestamp:Date.now()})},au=async(s,n=Lr)=>{const t=su(s);if(t)return t;const r=await I.get(s);return tu(s,r),r},Ot={getList:s=>I.post(`${ne}/user/fetch`,s),update:s=>I.post(`${ne}/user/update`,s),resetSecret:s=>I.post(`${ne}/user/resetSecret`,{id:s}),generate:s=>I.post(`${ne}/user/generate`,s),getStats:s=>I.post(`${ne}/stat/getStatUser`,s),destroy:s=>I.post(`${ne}/user/destroy`,{id:s}),sendMail:s=>I.post(`${ne}/user/sendMail`,s),dumpCSV:s=>I.post(`${ne}/user/dumpCSV`,s,{responseType:"blob"}),batchBan:s=>I.post(`${ne}/user/ban`,s)},nn={getList:()=>au(`${ne}/notice/fetch`),save:s=>I.post(`${ne}/notice/save`,s),drop:s=>I.post(`${ne}/notice/drop`,{id:s}),updateStatus:s=>I.post(`${ne}/notice/show`,{id:s}),sort:s=>I.post(`${ne}/notice/sort`,{ids:s})},la={getList:s=>I.post(`${ne}/ticket/fetch`,s),getInfo:s=>I.get(`${ne}/ticket/fetch?id=${s}`),reply:s=>I.post(`${ne}/ticket/reply`,s),close:s=>I.post(`${ne}/ticket/close`,{id:s})},rn={getSystemStatus:()=>I.get(`${ne}/system/getSystemStatus`),getQueueStats:()=>I.get(`${ne}/system/getQueueStats`),getQueueWorkload:()=>I.get(`${ne}/system/getQueueWorkload`),getQueueMasters:()=>I.get(`${ne}/system/getQueueMasters`),getSystemLog:s=>I.get(`${ne}/system/getSystemLog`,{params:s})},_s={getPluginList:()=>I.get(`${ne}/plugin/getPlugins`),uploadPlugin:s=>{const n=new FormData;return n.append("file",s),I.post(`${ne}/plugin/upload`,n,{headers:{"Content-Type":"multipart/form-data"}})},deletePlugin:s=>I.post(`${ne}/plugin/delete`,{code:s}),installPlugin:s=>I.post(`${ne}/plugin/install`,{code:s}),uninstallPlugin:s=>I.post(`${ne}/plugin/uninstall`,{code:s}),enablePlugin:s=>I.post(`${ne}/plugin/enable`,{code:s}),disablePlugin:s=>I.post(`${ne}/plugin/disable`,{code:s}),getPluginConfig:s=>I.get(`${ne}/plugin/config`,{params:{code:s}}),updatePluginConfig:(s,n)=>I.post(`${ne}/plugin/config`,{code:s,config:n})},nu=()=>I.get(`${ne}/update/check`),ru=()=>I.post(`${ne}/update/execute`),lu=As("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/10",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function q({className:s,variant:n,...t}){return e.jsx("div",{className:N(lu({variant:n}),s),...t})}const zs=u.forwardRef(({className:s,children:n,...t},r)=>e.jsxs($n,{ref:r,className:N("relative overflow-hidden",s),...t,children:[e.jsx(ki,{className:"h-full w-full rounded-[inherit]",children:n}),e.jsx(Lt,{}),e.jsx(Ti,{})]}));zs.displayName=$n.displayName;const Lt=u.forwardRef(({className:s,orientation:n="vertical",...t},r)=>e.jsx(Un,{ref:r,orientation:n,className:N("flex touch-none select-none transition-colors",n==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",n==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...t,children:e.jsx(Di,{className:"relative flex-1 rounded-full bg-border"})}));Lt.displayName=Un.displayName;function iu(){const{t:s}=V("common"),[n,t]=u.useState(!1),{data:r}=re({queryKey:["checkUpdate"],queryFn:async()=>await nu(),refetchInterval:1e3*60*60}),a=r?.data,i=es({mutationFn:ru,onSuccess:l=>{const d=l.data;d.success?(A.success(s("update.updateSuccess")),t(!1)):A.error(d.message)},onError:()=>{A.error(s("update.updateFailed"))}});return a?.has_update?e.jsxs(e.Fragment,{children:[e.jsxs(P,{size:"icon",variant:"ghost",className:"rounded-full relative",onClick:()=>t(!0),children:[e.jsx(Pi,{size:20,className:"text-red-500"}),e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"})]}),e.jsx(be,{open:n,onOpenChange:t,children:e.jsxs(fe,{className:"sm:max-w-[500px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:s("update.title")}),e.jsxs(Te,{children:[s("update.newVersion")," ",a?.latest_version]})]}),e.jsxs("div",{className:"py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[s("update.currentVersion"),":",a?.current_version]}),e.jsxs(q,{variant:"outline",children:[s("update.latestVersion"),":",a?.latest_version]})]}),e.jsx(zs,{className:"h-[200px] rounded-md border p-4",children:e.jsx("div",{className:"space-y-4",children:a?.update_logs.map(l=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(q,{variant:"secondary",children:l.version}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ze(new Date(l.date),"yyyy-MM-dd HH:mm")})]}),e.jsx("p",{className:"text-sm",children:l.message})]},l.version))})})]}),e.jsxs(ze,{children:[e.jsx(P,{variant:"outline",onClick:()=>t(!1),children:s("update.updateLater")}),e.jsx(P,{onClick:()=>i.mutate(),disabled:i.isPending,children:i.isPending?s("update.updating"):s("update.updateNow")})]})]})})]}):null}function Ae(){const{theme:s,setTheme:n}=ec();return u.useEffect(()=>{const t=s==="dark"?"#020817":"#fff",r=document.querySelector("meta[name='theme-color']");r&&r.setAttribute("content",t)},[s]),e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"icon",variant:"ghost",className:"rounded-full",onClick:()=>n(s==="light"?"dark":"light"),children:s==="light"?e.jsx(Ei,{size:20}):e.jsx(Ri,{size:20})}),e.jsx(Er,{}),e.jsx(iu,{})]})}const zr=u.forwardRef(({className:s,...n},t)=>e.jsx(Hn,{ref:t,className:N("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...n}));zr.displayName=Hn.displayName;const Ar=u.forwardRef(({className:s,...n},t)=>e.jsx(qn,{ref:t,className:N("aspect-square h-full w-full",s),...n}));Ar.displayName=qn.displayName;const $r=u.forwardRef(({className:s,...n},t)=>e.jsx(Kn,{ref:t,className:N("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...n}));$r.displayName=Kn.displayName;function $e(){const s=Ts(),n=yn(),t=Ii(Pd),{t:r}=V(["common"]),a=()=>{yr(),n(Dd()),s("/sign-in")},i=t?.email?.split("@")[0]||r("common:user"),l=i.substring(0,2).toUpperCase();return e.jsxs(Ss,{children:[e.jsx(ks,{asChild:!0,children:e.jsx(P,{variant:"ghost",className:"relative h-8 w-8 rounded-full",children:e.jsxs(zr,{className:"h-8 w-8",children:[e.jsx(Ar,{src:t?.avatar_url,alt:i}),e.jsx($r,{children:l})]})})}),e.jsxs(fs,{className:"w-56",align:"end",forceMount:!0,children:[e.jsx(Ra,{className:"font-normal",children:e.jsxs("div",{className:"flex flex-col space-y-1",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:i}),e.jsx("p",{className:"text-xs leading-none text-muted-foreground",children:t?.email||r("common:defaultEmail")})]})}),e.jsx(tt,{}),e.jsx(je,{asChild:!0,children:e.jsxs(Us,{to:"/config/system",children:[r("common:settings"),e.jsx(va,{children:"⌘S"})]})}),e.jsx(tt,{}),e.jsxs(je,{onClick:a,children:[r("common:logout"),e.jsx(va,{children:"⇧⌘Q"})]})]})]})}const G=Vi,He=Ui,W=Mi,K=u.forwardRef(({className:s,children:n,...t},r)=>e.jsxs(Bn,{ref:r,className:N("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...t,children:[n,e.jsx(Fi,{asChild:!0,children:e.jsx(Ta,{className:"h-4 w-4 opacity-50"})})]}));K.displayName=Bn.displayName;const Ur=u.forwardRef(({className:s,...n},t)=>e.jsx(Gn,{ref:t,className:N("flex cursor-default items-center justify-center py-1",s),...n,children:e.jsx(Oi,{className:"h-4 w-4"})}));Ur.displayName=Gn.displayName;const Hr=u.forwardRef(({className:s,...n},t)=>e.jsx(Wn,{ref:t,className:N("flex cursor-default items-center justify-center py-1",s),...n,children:e.jsx(Ta,{className:"h-4 w-4"})}));Hr.displayName=Wn.displayName;const B=u.forwardRef(({className:s,children:n,position:t="popper",...r},a)=>e.jsx(Li,{children:e.jsxs(Yn,{ref:a,className:N("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:t,...r,children:[e.jsx(Ur,{}),e.jsx(zi,{className:N("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:n}),e.jsx(Hr,{})]})}));B.displayName=Yn.displayName;const ou=u.forwardRef(({className:s,...n},t)=>e.jsx(Qn,{ref:t,className:N("px-2 py-1.5 text-sm font-semibold",s),...n}));ou.displayName=Qn.displayName;const z=u.forwardRef(({className:s,children:n,...t},r)=>e.jsxs(Jn,{ref:r,className:N("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s),...t,children:[e.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Ai,{children:e.jsx($s,{className:"h-4 w-4"})})}),e.jsx($i,{children:n})]}));z.displayName=Jn.displayName;const cu=u.forwardRef(({className:s,...n},t)=>e.jsx(Xn,{ref:t,className:N("-mx-1 my-1 h-px bg-muted",s),...n}));cu.displayName=Xn.displayName;function Gs({className:s,classNames:n,showOutsideDays:t=!0,...r}){return e.jsx(Hi,{showOutsideDays:t,className:N("p-3",s),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:N(st({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:N("relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",r.mode==="range"?"[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md":"[&:has([aria-selected])]:rounded-md"),day:N(st({variant:"ghost"}),"h-8 w-8 p-0 font-normal aria-selected:opacity-100"),day_range_start:"day-range-start",day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...n},components:{IconLeft:({className:a,...i})=>e.jsx(Zn,{className:N("h-4 w-4",a),...i}),IconRight:({className:a,...i})=>e.jsx(Sa,{className:N("h-4 w-4",a),...i})},...r})}Gs.displayName="Calendar";const vs=Ki,bs=Bi,xs=u.forwardRef(({className:s,align:n="center",sideOffset:t=4,...r},a)=>e.jsx(qi,{children:e.jsx(er,{ref:a,align:n,sideOffset:t,className:N("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})}));xs.displayName=er.displayName;const Es={income:{main:"hsl(var(--primary))",gradient:{start:"hsl(var(--primary))",end:"transparent"}},commission:{main:"hsl(var(--secondary))",gradient:{start:"hsl(var(--secondary))",end:"transparent"}}},dt=s=>(s/100).toFixed(2),du=({active:s,payload:n,label:t})=>{const{t:r}=V();return s&&n&&n.length?e.jsxs("div",{className:"rounded-lg border bg-background p-3 shadow-sm",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:t}),n.map((a,i)=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:a.color}}),e.jsxs("span",{className:"text-muted-foreground",children:[r(a.name),":"]}),e.jsx("span",{className:"font-medium",children:a.name.includes(r("dashboard:overview.amount"))?`¥${dt(a.value)}`:r("dashboard:overview.transactions",{count:a.value})})]},i))]}):null},uu=[{value:"7d",label:"dashboard:overview.last7Days"},{value:"30d",label:"dashboard:overview.last30Days"},{value:"90d",label:"dashboard:overview.last90Days"},{value:"180d",label:"dashboard:overview.last180Days"},{value:"365d",label:"dashboard:overview.lastYear"},{value:"custom",label:"dashboard:overview.customRange"}],mu=(s,n)=>{const t=new Date;if(s==="custom"&&n)return{startDate:n.from,endDate:n.to};let r;switch(s){case"7d":r=is(t,7);break;case"30d":r=is(t,30);break;case"90d":r=is(t,90);break;case"180d":r=is(t,180);break;case"365d":r=is(t,365);break;default:r=is(t,30)}return{startDate:r,endDate:t}};function xu(){const[s,n]=u.useState("amount"),[t,r]=u.useState("30d"),[a,i]=u.useState({from:is(new Date,7),to:new Date}),{t:l}=V(),{startDate:d,endDate:m}=mu(t,a),{data:o}=re({queryKey:["orderStat",{start_date:Ze(d,"yyyy-MM-dd"),end_date:Ze(m,"yyyy-MM-dd")}],queryFn:async()=>{const{data:c}=await vc({start_date:Ze(d,"yyyy-MM-dd"),end_date:Ze(m,"yyyy-MM-dd")});return c},refetchInterval:3e4});return e.jsxs(We,{children:[e.jsx(ts,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Cs,{children:l("dashboard:overview.title")}),e.jsxs(et,{children:[o?.summary.start_date," ",l("dashboard:overview.to")," ",o?.summary.end_date]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsxs(G,{value:t,onValueChange:c=>r(c),children:[e.jsx(K,{className:"w-[120px]",children:e.jsx(W,{placeholder:l("dashboard:overview.selectTimeRange")})}),e.jsx(B,{children:uu.map(c=>e.jsx(z,{value:c.value,children:l(c.label)},c.value))})]}),t==="custom"&&e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(J,{variant:"outline",className:N("min-w-0 justify-start text-left font-normal",!a&&"text-muted-foreground"),children:[e.jsx(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:a?.from?a.to?e.jsxs(e.Fragment,{children:[Ze(a.from,"yyyy-MM-dd")," -"," ",Ze(a.to,"yyyy-MM-dd")]}):Ze(a.from,"yyyy-MM-dd"):l("dashboard:overview.selectDate")})]})}),e.jsx(xs,{className:"w-auto p-0",align:"end",children:e.jsx(Gs,{mode:"range",defaultMonth:a?.from,selected:{from:a?.from,to:a?.to},onSelect:c=>{c?.from&&c?.to&&i({from:c.from,to:c.to})},numberOfMonths:2})})]})]}),e.jsx(Gt,{value:s,onValueChange:c=>n(c),children:e.jsxs(vt,{children:[e.jsx(Ge,{value:"amount",children:l("dashboard:overview.amount")}),e.jsx(Ge,{value:"count",children:l("dashboard:overview.count")})]})})]})]})}),e.jsxs(as,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:l("dashboard:overview.totalIncome")}),e.jsxs("div",{className:"text-2xl font-bold",children:["¥",dt(o?.summary?.paid_total||0)]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l("dashboard:overview.totalTransactions",{count:o?.summary?.paid_count||0})}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[l("dashboard:overview.avgOrderAmount")," ¥",dt(o?.summary?.avg_paid_amount||0)]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:l("dashboard:overview.totalCommission")}),e.jsxs("div",{className:"text-2xl font-bold",children:["¥",dt(o?.summary?.commission_total||0)]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:l("dashboard:overview.totalTransactions",{count:o?.summary?.commission_count||0})}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[l("dashboard:overview.commissionRate")," ",o?.summary?.commission_rate.toFixed(2)||0,"%"]})]})]}),e.jsx("div",{className:"h-[400px] w-full",children:e.jsx(Gi,{width:"100%",height:"100%",children:e.jsxs(Wi,{data:o?.list||[],margin:{top:20,right:20,left:0,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"incomeGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Es.income.gradient.start,stopOpacity:.2}),e.jsx("stop",{offset:"100%",stopColor:Es.income.gradient.end,stopOpacity:.1})]}),e.jsxs("linearGradient",{id:"commissionGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Es.commission.gradient.start,stopOpacity:.2}),e.jsx("stop",{offset:"100%",stopColor:Es.commission.gradient.end,stopOpacity:.1})]})]}),e.jsx(Yi,{dataKey:"date",axisLine:!1,tickLine:!1,tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:c=>Ze(new Date(c),"MM-dd",{locale:Zi})}),e.jsx(Qi,{axisLine:!1,tickLine:!1,tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:c=>s==="amount"?`¥${dt(c)}`:l("dashboard:overview.transactions",{count:c})}),e.jsx(Ji,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))",opacity:.3}),e.jsx(Xi,{content:e.jsx(du,{})}),s==="amount"?e.jsxs(e.Fragment,{children:[e.jsx(Ga,{type:"monotone",dataKey:"paid_total",name:l("dashboard:overview.orderAmount"),stroke:Es.income.main,fill:"url(#incomeGradient)",strokeWidth:2}),e.jsx(Ga,{type:"monotone",dataKey:"commission_total",name:l("dashboard:overview.commissionAmount"),stroke:Es.commission.main,fill:"url(#commissionGradient)",strokeWidth:2})]}):e.jsxs(e.Fragment,{children:[e.jsx(Wa,{dataKey:"paid_count",name:l("dashboard:overview.orderCount"),fill:Es.income.main,radius:[4,4,0,0],maxBarSize:40}),e.jsx(Wa,{dataKey:"commission_count",name:l("dashboard:overview.commissionCount"),fill:Es.commission.main,radius:[4,4,0,0],maxBarSize:40})]})]})})})]})]})}function oe({className:s,...n}){return e.jsx("div",{className:N("animate-pulse rounded-md bg-primary/10",s),...n})}function hu(){return e.jsxs(We,{children:[e.jsxs(ts,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(oe,{className:"h-4 w-[120px]"}),e.jsx(oe,{className:"h-4 w-4"})]}),e.jsxs(as,{children:[e.jsx(oe,{className:"h-8 w-[140px] mb-2"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-4 w-4"}),e.jsx(oe,{className:"h-4 w-[100px]"})]})]})]})}function pu(){return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:Array.from({length:8}).map((s,n)=>e.jsx(hu,{},n))})}var ae=(s=>(s[s.PENDING=0]="PENDING",s[s.PROCESSING=1]="PROCESSING",s[s.CANCELLED=2]="CANCELLED",s[s.COMPLETED=3]="COMPLETED",s[s.DISCOUNTED=4]="DISCOUNTED",s))(ae||{});const ot={0:"待支付",1:"开通中",2:"已取消",3:"已完成",4:"已折抵"},ct={0:"yellow-500",1:"blue-500",2:"red-500",3:"green-500",4:"green-500"};var os=(s=>(s[s.NEW=1]="NEW",s[s.RENEWAL=2]="RENEWAL",s[s.UPGRADE=3]="UPGRADE",s[s.RESET_FLOW=4]="RESET_FLOW",s))(os||{}),xe=(s=>(s[s.PENDING=0]="PENDING",s[s.PROCESSING=1]="PROCESSING",s[s.VALID=2]="VALID",s[s.INVALID=3]="INVALID",s))(xe||{});const Nt={0:"待确认",1:"发放中",2:"有效",3:"无效"},_t={0:"yellow-500",1:"blue-500",2:"green-500",3:"red-500"};var Pe=(s=>(s.MONTH_PRICE="month_price",s.QUARTER_PRICE="quarter_price",s.HALF_YEAR_PRICE="half_year_price",s.YEAR_PRICE="year_price",s.TWO_YEAR_PRICE="two_year_price",s.THREE_YEAR_PRICE="three_year_price",s.ONETIME_PRICE="onetime_price",s.RESET_PRICE="reset_price",s))(Pe||{});const fu={month_price:"月付",quarter_price:"季付",half_year_price:"半年付",year_price:"年付",two_year_price:"两年付",three_year_price:"三年付",onetime_price:"一次性",reset_price:"流量重置包"};var ie=(s=>(s.Shadowsocks="shadowsocks",s.Vmess="vmess",s.Trojan="trojan",s.Hysteria="hysteria",s.Vless="vless",s.Tuic="tuic",s.Socks="socks",s.Naive="naive",s.Http="http",s.Mieru="mieru",s))(ie||{});const Xe=[{type:"shadowsocks",label:"Shadowsocks"},{type:"vmess",label:"VMess"},{type:"trojan",label:"Trojan"},{type:"hysteria",label:"Hysteria"},{type:"vless",label:"VLess"},{type:"tuic",label:"TUIC"},{type:"socks",label:"SOCKS"},{type:"naive",label:"Naive"},{type:"http",label:"HTTP"},{type:"mieru",label:"Mieru"}],qe={shadowsocks:"#489851",vmess:"#CB3180",trojan:"#EBB749",hysteria:"#5684e6",vless:"#1a1a1a",tuic:"#00C853",socks:"#2196F3",naive:"#9C27B0",http:"#FF5722",mieru:"#4CAF50"};var Be=(s=>(s[s.AMOUNT=1]="AMOUNT",s[s.PERCENTAGE=2]="PERCENTAGE",s))(Be||{});const gu={1:"按金额优惠",2:"按比例优惠"};var Vs=(s=>(s[s.OPENING=0]="OPENING",s[s.CLOSED=1]="CLOSED",s))(Vs||{}),Oe=(s=>(s[s.LOW=0]="LOW",s[s.MIDDLE=1]="MIDDLE",s[s.HIGH=2]="HIGH",s))(Oe||{}),xt=(s=>(s.MONTH="monthly",s.QUARTER="quarterly",s.HALF_YEAR="half_yearly",s.YEAR="yearly",s.TWO_YEAR="two_yearly",s.THREE_YEAR="three_yearly",s.ONETIME="onetime",s.RESET="reset_traffic",s))(xt||{});function Rs({title:s,value:n,icon:t,trend:r,description:a,onClick:i,highlight:l,className:d}){return e.jsxs(We,{className:N("transition-colors",i&&"cursor-pointer hover:bg-muted/50",l&&"border-primary/50",d),onClick:i,children:[e.jsxs(ts,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Cs,{className:"text-sm font-medium",children:s}),t]}),e.jsxs(as,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n}),r?e.jsxs("div",{className:"flex items-center pt-1",children:[e.jsx(ro,{className:N("h-4 w-4",r.isPositive?"text-emerald-500":"text-red-500")}),e.jsxs("span",{className:N("ml-1 text-xs",r.isPositive?"text-emerald-500":"text-red-500"),children:[r.isPositive?"+":"-",Math.abs(r.value),"%"]}),e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:r.label})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})]})}function ju({className:s}){const n=Ts(),{t}=V(),{data:r,isLoading:a}=re({queryKey:["dashboardStats"],queryFn:async()=>(await bc()).data,refetchInterval:1e3*60*5});if(a||!r)return e.jsx(pu,{});const i=()=>{const l=new URLSearchParams;l.set("commission_status",xe.PENDING.toString()),l.set("status",ae.COMPLETED.toString()),l.set("commission_balance","gt:0"),n(`/finance/order?${l.toString()}`)};return e.jsxs("div",{className:N("grid gap-4 md:grid-cols-2 lg:grid-cols-4",s),children:[e.jsx(Rs,{title:t("dashboard:stats.todayIncome"),value:Ls(r.todayIncome),icon:e.jsx(eo,{className:"h-4 w-4 text-emerald-500"}),trend:{value:r.dayIncomeGrowth,label:t("dashboard:stats.vsYesterday"),isPositive:r.dayIncomeGrowth>0}}),e.jsx(Rs,{title:t("dashboard:stats.monthlyIncome"),value:Ls(r.currentMonthIncome),icon:e.jsx(so,{className:"h-4 w-4 text-blue-500"}),trend:{value:r.monthIncomeGrowth,label:t("dashboard:stats.vsLastMonth"),isPositive:r.monthIncomeGrowth>0}}),e.jsx(Rs,{title:t("dashboard:stats.pendingTickets"),value:r.ticketPendingTotal,icon:e.jsx(to,{className:N("h-4 w-4",r.ticketPendingTotal>0?"text-orange-500":"text-muted-foreground")}),description:r.ticketPendingTotal>0?t("dashboard:stats.hasPendingTickets"):t("dashboard:stats.noPendingTickets"),onClick:()=>n("/user/ticket"),highlight:r.ticketPendingTotal>0}),e.jsx(Rs,{title:t("dashboard:stats.pendingCommission"),value:r.commissionPendingTotal,icon:e.jsx(ao,{className:N("h-4 w-4",r.commissionPendingTotal>0?"text-blue-500":"text-muted-foreground")}),description:r.commissionPendingTotal>0?t("dashboard:stats.hasPendingCommission"):t("dashboard:stats.noPendingCommission"),onClick:i,highlight:r.commissionPendingTotal>0}),e.jsx(Rs,{title:t("dashboard:stats.monthlyNewUsers"),value:r.currentMonthNewUsers,icon:e.jsx(ha,{className:"h-4 w-4 text-blue-500"}),trend:{value:r.userGrowth,label:t("dashboard:stats.vsLastMonth"),isPositive:r.userGrowth>0}}),e.jsx(Rs,{title:t("dashboard:stats.totalUsers"),value:r.totalUsers,icon:e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),description:t("dashboard:stats.activeUsers",{count:r.activeUsers})}),e.jsx(Rs,{title:t("dashboard:stats.monthlyUpload"),value:ps(r.monthTraffic.upload),icon:e.jsx(pt,{className:"h-4 w-4 text-emerald-500"}),description:t("dashboard:stats.todayTraffic",{value:ps(r.todayTraffic.upload)})}),e.jsx(Rs,{title:t("dashboard:stats.monthlyDownload"),value:ps(r.monthTraffic.download),icon:e.jsx(no,{className:"h-4 w-4 text-blue-500"}),description:t("dashboard:stats.todayTraffic",{value:ps(r.todayTraffic.download)})})]})}const ya={today:{getValue:()=>{const s=io();return{start:s,end:oo(s,1)}}},last7days:{getValue:()=>{const s=new Date;return{start:is(s,7),end:s}}},last30days:{getValue:()=>{const s=new Date;return{start:is(s,30),end:s}}},custom:{getValue:()=>null}};function ln({selectedRange:s,customDateRange:n,onRangeChange:t,onCustomRangeChange:r}){const{t:a}=V(),i={today:a("dashboard:trafficRank.today"),last7days:a("dashboard:trafficRank.last7days"),last30days:a("dashboard:trafficRank.last30days"),custom:a("dashboard:trafficRank.customRange")};return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:[e.jsxs(G,{value:s,onValueChange:t,children:[e.jsx(K,{className:"w-[120px]",children:e.jsx(W,{placeholder:a("dashboard:trafficRank.selectTimeRange")})}),e.jsx(B,{position:"popper",className:"z-50",children:Object.entries(ya).map(([l])=>e.jsx(z,{value:l,children:i[l]},l))})]}),s==="custom"&&e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(J,{variant:"outline",className:N("min-w-0 justify-start text-left font-normal",!n&&"text-muted-foreground"),children:[e.jsx(jt,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:n?.from?n.to?e.jsxs(e.Fragment,{children:[Ze(n.from,"yyyy-MM-dd")," -"," ",Ze(n.to,"yyyy-MM-dd")]}):Ze(n.from,"yyyy-MM-dd"):e.jsx("span",{children:a("dashboard:trafficRank.selectDateRange")})})]})}),e.jsx(xs,{className:"w-auto p-0",align:"end",children:e.jsx(Gs,{mode:"range",defaultMonth:n?.from,selected:{from:n?.from,to:n?.to},onSelect:l=>{l?.from&&l?.to&&r({from:l.from,to:l.to})},numberOfMonths:2})})]})]})}const Qs=s=>`${(s/1024/1024/1024).toFixed(2)} GB`;function vu({className:s}){const{t:n}=V(),[t,r]=u.useState("today"),[a,i]=u.useState({from:is(new Date,7),to:new Date}),[l,d]=u.useState("today"),[m,o]=u.useState({from:is(new Date,7),to:new Date}),c=u.useMemo(()=>t==="custom"?{start:a.from,end:a.to}:ya[t].getValue(),[t,a]),h=u.useMemo(()=>l==="custom"?{start:m.from,end:m.to}:ya[l].getValue(),[l,m]),{data:_}=re({queryKey:["nodeTrafficRank",c.start,c.end],queryFn:()=>tn({type:"node",start_time:Se.round(c.start.getTime()/1e3),end_time:Se.round(c.end.getTime()/1e3)}),refetchInterval:3e4}),{data:E}=re({queryKey:["userTrafficRank",h.start,h.end],queryFn:()=>tn({type:"user",start_time:Se.round(h.start.getTime()/1e3),end_time:Se.round(h.end.getTime()/1e3)}),refetchInterval:3e4});return e.jsxs("div",{className:N("grid gap-4 md:grid-cols-2",s),children:[e.jsxs(We,{children:[e.jsx(ts,{className:"flex-none pb-2",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(Cs,{className:"flex items-center text-base font-medium",children:[e.jsx(lo,{className:"mr-2 h-4 w-4"}),n("dashboard:trafficRank.nodeTrafficRank")]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(ln,{selectedRange:t,customDateRange:a,onRangeChange:r,onCustomRangeChange:i}),e.jsx(Ya,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})]})}),e.jsx(as,{className:"flex-1",children:_?.data?e.jsxs(zs,{className:"h-[400px] pr-4",children:[e.jsx("div",{className:"space-y-3",children:_.data.map(C=>e.jsx(ve,{delayDuration:200,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx("div",{className:"flex cursor-pointer items-center justify-between space-x-2 rounded-lg bg-muted/50 p-2 transition-colors hover:bg-muted/70",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:C.name}),e.jsxs("span",{className:N("ml-2 flex items-center text-xs font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?e.jsx(pa,{className:"mr-1 h-3 w-3"}):e.jsx(fa,{className:"mr-1 h-3 w-3"}),Math.abs(C.change),"%"]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${C.value/_.data[0].value*100}%`}})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Qs(C.value)})]})]})})}),e.jsx(ce,{side:"right",className:"space-y-2 p-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.currentTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Qs(C.value)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.previousTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Qs(C.previousValue)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.changeRate"),":"]}),e.jsxs("span",{className:N("font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?"+":"",C.change,"%"]})]})})]})},C.id))}),e.jsx(Lt,{orientation:"vertical"})]}):e.jsx("div",{className:"flex h-[400px] items-center justify-center",children:e.jsx("div",{className:"animate-pulse",children:n("common:loading")})})})]}),e.jsxs(We,{children:[e.jsx(ts,{className:"flex-none pb-2",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs(Cs,{className:"flex items-center text-base font-medium",children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),n("dashboard:trafficRank.userTrafficRank")]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(ln,{selectedRange:l,customDateRange:m,onRangeChange:d,onCustomRangeChange:o}),e.jsx(Ya,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})]})}),e.jsx(as,{className:"flex-1",children:E?.data?e.jsxs(zs,{className:"h-[400px] pr-4",children:[e.jsx("div",{className:"space-y-3",children:E.data.map(C=>e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx("div",{className:"flex cursor-pointer items-center justify-between space-x-2 rounded-lg bg-muted/50 p-2 transition-colors hover:bg-muted/70",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:C.name}),e.jsxs("span",{className:N("ml-2 flex items-center text-xs font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?e.jsx(pa,{className:"mr-1 h-3 w-3"}):e.jsx(fa,{className:"mr-1 h-3 w-3"}),Math.abs(C.change),"%"]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"h-2 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${C.value/E.data[0].value*100}%`}})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Qs(C.value)})]})]})})}),e.jsx(ce,{side:"right",className:"space-y-2 p-4",children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.currentTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Qs(C.value)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.previousTraffic"),":"]}),e.jsx("span",{className:"font-medium",children:Qs(C.previousValue)}),e.jsxs("span",{className:"text-muted-foreground",children:[n("dashboard:trafficRank.changeRate"),":"]}),e.jsxs("span",{className:N("font-medium",C.change>=0?"text-green-600":"text-red-600"),children:[C.change>=0?"+":"",C.change,"%"]})]})})]})},C.id))}),e.jsx(Lt,{orientation:"vertical"})]}):e.jsx("div",{className:"flex h-[400px] items-center justify-center",children:e.jsx("div",{className:"animate-pulse",children:n("common:loading")})})})]})]})}const Dt=u.forwardRef(({className:s,value:n,...t},r)=>e.jsx(sr,{ref:r,className:N("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",s),...t,children:e.jsx(co,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(n||0)}%)`}})}));Dt.displayName=sr.displayName;function bu(){const{t:s}=V(),[n,t]=u.useState(null),[r,a]=u.useState(null),[i,l]=u.useState(!0),[d,m]=u.useState(!1),o=async()=>{try{m(!0);const[_,E]=await Promise.all([rn.getSystemStatus(),rn.getQueueStats()]);t(_.data),a(E.data)}catch(_){console.error("Error fetching system data:",_)}finally{l(!1),m(!1)}};u.useEffect(()=>{o();const _=setInterval(o,3e4);return()=>clearInterval(_)},[]);const c=()=>{o()};if(i)return e.jsx("div",{className:"flex items-center justify-center p-6",children:e.jsx(Da,{className:"h-6 w-6 animate-spin"})});const h=_=>_?e.jsx(tr,{className:"h-5 w-5 text-green-500"}):e.jsx(ar,{className:"h-5 w-5 text-red-500"});return e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(We,{children:[e.jsxs(ts,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Cs,{className:"flex items-center gap-2",children:[e.jsx(uo,{className:"h-5 w-5"}),s("dashboard:queue.title")]}),e.jsx(et,{children:s("dashboard:queue.status.description")})]}),e.jsx(J,{variant:"outline",size:"icon",onClick:c,disabled:d,children:e.jsx(mo,{className:N("h-4 w-4",d&&"animate-spin")})})]}),e.jsx(as,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[h(r?.status||!1),e.jsx("span",{className:"font-medium",children:s("dashboard:queue.status.running")})]}),e.jsx(q,{variant:r?.status?"secondary":"destructive",children:r?.status?s("dashboard:queue.status.normal"):s("dashboard:queue.status.abnormal")})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.status.waitTime",{seconds:r?.wait?.default||0})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.recentJobs")}),e.jsx("p",{className:"text-2xl font-bold",children:r?.recentJobs||0}),e.jsx(Dt,{value:(r?.recentJobs||0)/(r?.periods?.recentJobs||1)*100,className:"h-1"})]})}),e.jsx(ce,{children:e.jsx("p",{children:s("dashboard:queue.details.statisticsPeriod",{hours:r?.periods?.recentJobs||0})})})]})}),e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.jobsPerMinute")}),e.jsx("p",{className:"text-2xl font-bold",children:r?.jobsPerMinute||0}),e.jsx(Dt,{value:(r?.jobsPerMinute||0)/(r?.queueWithMaxThroughput?.throughput||1)*100,className:"h-1"})]})}),e.jsx(ce,{children:e.jsx("p",{children:s("dashboard:queue.details.maxThroughput",{value:r?.queueWithMaxThroughput?.throughput||0})})})]})})]})]})})]}),e.jsxs(We,{children:[e.jsxs(ts,{children:[e.jsxs(Cs,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5"}),s("dashboard:queue.jobDetails")]}),e.jsx(et,{children:s("dashboard:queue.details.description")})]}),e.jsx(as,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.failedJobs7Days")}),e.jsx("p",{className:"text-2xl font-bold text-destructive",children:r?.failedJobs||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("dashboard:queue.details.retentionPeriod",{hours:r?.periods?.failedJobs||0})})]}),e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/50 p-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.longestRunningQueue")}),e.jsxs("p",{className:"text-2xl font-bold",children:[r?.queueWithMaxRuntime?.runtime||0,"s"]}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:r?.queueWithMaxRuntime?.name||"N/A"})]})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s("dashboard:queue.details.activeProcesses")}),e.jsxs("span",{className:"font-medium",children:[r?.processes||0," /"," ",(r?.processes||0)+(r?.pausedMasters||0)]})]}),e.jsx(Dt,{value:(r?.processes||0)/((r?.processes||0)+(r?.pausedMasters||0))*100,className:"mt-2 h-1"})]})]})})]})]})}function yu(){const{t:s}=V();return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx("div",{className:"flex items-center",children:e.jsx("h1",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:s("dashboard:title")})}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ke,{}),e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsx(Fe,{children:e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6",children:[e.jsx(ju,{}),e.jsx(xu,{}),e.jsx(vu,{}),e.jsx(bu,{})]})})})]})}const Nu=Object.freeze(Object.defineProperty({__proto__:null,default:yu},Symbol.toStringTag,{value:"Module"}));function _u({className:s,items:n,...t}){const{pathname:r}=_a(),a=Ts(),[i,l]=u.useState(r??"/settings"),d=o=>{l(o),a(o)},{t:m}=V("settings");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-1 md:hidden",children:e.jsxs(G,{value:i,onValueChange:d,children:[e.jsx(K,{className:"h-12 sm:w-48",children:e.jsx(W,{placeholder:"Theme"})}),e.jsx(B,{children:n.map(o=>e.jsx(z,{value:o.href,children:e.jsxs("div",{className:"flex gap-x-4 px-2 py-1",children:[e.jsx("span",{className:"scale-125",children:o.icon}),e.jsx("span",{className:"text-md",children:m(o.title)})]})},o.href))})]})}),e.jsx("div",{className:"hidden w-full overflow-x-auto bg-background px-1 py-2 md:block",children:e.jsx("nav",{className:N("flex space-x-2 lg:flex-col lg:space-x-0 lg:space-y-1",s),...t,children:n.map(o=>e.jsxs(Us,{to:o.href,className:N(nt({variant:"ghost"}),r===o.href?"bg-muted hover:bg-muted":"hover:bg-transparent hover:underline","justify-start"),children:[e.jsx("span",{className:"mr-2",children:o.icon}),m(o.title)]},o.href))})})]})}const wu=[{title:"site.title",key:"site",icon:e.jsx(ho,{size:18}),href:"/config/system",description:"site.description"},{title:"safe.title",key:"safe",icon:e.jsx(Ln,{size:18}),href:"/config/system/safe",description:"safe.description"},{title:"subscribe.title",key:"subscribe",icon:e.jsx(zn,{size:18}),href:"/config/system/subscribe",description:"subscribe.description"},{title:"invite.title",key:"invite",icon:e.jsx(po,{size:18}),href:"/config/system/invite",description:"invite.description"},{title:"server.title",key:"server",icon:e.jsx(On,{size:18}),href:"/config/system/server",description:"server.description"},{title:"email.title",key:"email",icon:e.jsx(fo,{size:18}),href:"/config/system/email",description:"email.description"},{title:"telegram.title",key:"telegram",icon:e.jsx(go,{size:18}),href:"/config/system/telegram",description:"telegram.description"},{title:"app.title",key:"app",icon:e.jsx(Fn,{size:18}),href:"/config/system/app",description:"app.description"},{title:"subscribe_template.title",key:"subscribe_template",icon:e.jsx(jo,{size:18}),href:"/config/system/subscribe-template",description:"subscribe_template.description"}];function Cu(){const{t:s}=V("settings");return e.jsxs(Ee,{fadedBelow:!0,fixedHeight:!0,children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:s("title")}),e.jsx("div",{className:"text-muted-foreground",children:s("description")})]}),e.jsx(ke,{className:"my-6"}),e.jsxs("div",{className:"flex flex-1 flex-col space-y-8 overflow-auto lg:flex-row lg:space-x-12 lg:space-y-0",children:[e.jsx("aside",{className:"sticky top-0 lg:w-1/5",children:e.jsx(_u,{items:wu})}),e.jsx("div",{className:"flex-1 w-full p-1 pr-4",children:e.jsx("div",{className:"pb-16",children:e.jsx(wa,{})})})]})]})]})}const Su=Object.freeze(Object.defineProperty({__proto__:null,default:Cu},Symbol.toStringTag,{value:"Module"})),Y=u.forwardRef(({className:s,...n},t)=>e.jsx(nr,{className:N("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...n,ref:t,children:e.jsx(vo,{className:N("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));Y.displayName=nr.displayName;const ys=u.forwardRef(({className:s,...n},t)=>e.jsx("textarea",{className:N("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",s),ref:t,...n}));ys.displayName="Textarea";const ku=x.object({logo:x.string().nullable().default(""),force_https:x.number().nullable().default(0),stop_register:x.number().nullable().default(0),app_name:x.string().nullable().default(""),app_description:x.string().nullable().default(""),app_url:x.string().nullable().default(""),subscribe_url:x.string().nullable().default(""),try_out_plan_id:x.number().nullable().default(0),try_out_hour:x.coerce.number().nullable().default(0),tos_url:x.string().nullable().default(""),currency:x.string().nullable().default(""),currency_symbol:x.string().nullable().default("")});function Tu(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),{data:a}=re({queryKey:["settings","site"],queryFn:()=>gs("site")}),{data:i}=re({queryKey:["plans"],queryFn:()=>qs()}),l=ge({resolver:Ne(ku),defaultValues:{},mode:"onBlur"}),{mutateAsync:d}=es({mutationFn:js,onSuccess:c=>{c.data&&A.success(s("common.autoSaved"))}});u.useEffect(()=>{if(a?.data?.site){const c=a?.data?.site;Object.entries(c).forEach(([h,_])=>{l.setValue(h,_)}),r.current=c}},[a]);const m=u.useCallback(Se.debounce(async c=>{if(!Se.isEqual(c,r.current)){t(!0);try{const h=Object.entries(c).reduce((_,[E,C])=>(_[E]=C===null?"":C,_),{});await d(h),r.current=c}finally{t(!1)}}},1e3),[d]),o=u.useCallback(c=>{m(c)},[m]);return u.useEffect(()=>{const c=l.watch(h=>{o(h)});return()=>c.unsubscribe()},[l.watch,o]),e.jsx(_e,{...l,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:l.control,name:"app_name",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.siteName.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.siteName.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.siteName.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"app_description",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.siteDescription.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.siteDescription.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.siteDescription.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"app_url",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.siteUrl.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.siteUrl.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.siteUrl.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"force_https",render:({field:c})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("site.form.forceHttps.label")}),e.jsx(F,{children:s("site.form.forceHttps.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:!!c.value,onCheckedChange:h=>{c.onChange(Number(h)),o(l.getValues())}})})]})}),e.jsx(g,{control:l.control,name:"logo",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.logo.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.logo.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.logo.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"subscribe_url",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.subscribeUrl.label")}),e.jsx(y,{children:e.jsx(ys,{placeholder:s("site.form.subscribeUrl.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.subscribeUrl.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"tos_url",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.tosUrl.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.tosUrl.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.tosUrl.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"stop_register",render:({field:c})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("site.form.stopRegister.label")}),e.jsx(F,{children:s("site.form.stopRegister.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:!!c.value,onCheckedChange:h=>{c.onChange(Number(h)),o(l.getValues())}})})]})}),e.jsx(g,{control:l.control,name:"try_out_plan_id",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.tryOut.label")}),e.jsx(y,{children:e.jsxs(G,{value:c.value?.toString(),onValueChange:h=>{c.onChange(Number(h)),o(l.getValues())},children:[e.jsx(K,{children:e.jsx(W,{placeholder:s("site.form.tryOut.placeholder")})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("site.form.tryOut.placeholder")}),i?.data?.map(h=>e.jsx(z,{value:h.id.toString(),children:h.name},h.id.toString()))]})]})}),e.jsx(F,{children:s("site.form.tryOut.description")}),e.jsx(D,{})]})}),!!l.watch("try_out_plan_id")&&e.jsx(g,{control:l.control,name:"try_out_hour",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"",children:s("site.form.tryOut.duration.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.tryOut.duration.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.tryOut.duration.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"currency",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.currency.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.currency.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.currency.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:l.control,name:"currency_symbol",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("site.form.currencySymbol.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("site.form.currencySymbol.placeholder"),...c,value:c.value||"",onChange:h=>{c.onChange(h),o(l.getValues())}})}),e.jsx(F,{children:s("site.form.currencySymbol.description")}),e.jsx(D,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("site.form.saving")})]})})}function Du(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("site.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("site.description")})]}),e.jsx(ke,{}),e.jsx(Tu,{})]})}const Pu=Object.freeze(Object.defineProperty({__proto__:null,default:Du},Symbol.toStringTag,{value:"Module"})),Eu=x.object({email_verify:x.boolean().nullable(),safe_mode_enable:x.boolean().nullable(),secure_path:x.string().nullable(),email_whitelist_enable:x.boolean().nullable(),email_whitelist_suffix:x.array(x.string().nullable()).nullable(),email_gmail_limit_enable:x.boolean().nullable(),recaptcha_enable:x.boolean().nullable(),recaptcha_key:x.string().nullable(),recaptcha_site_key:x.string().nullable(),register_limit_by_ip_enable:x.boolean().nullable(),register_limit_count:x.coerce.string().transform(s=>s===""?null:s).nullable(),register_limit_expire:x.coerce.string().transform(s=>s===""?null:s).nullable(),password_limit_enable:x.boolean().nullable(),password_limit_count:x.coerce.string().transform(s=>s===""?null:s).nullable(),password_limit_expire:x.coerce.string().transform(s=>s===""?null:s).nullable()}),Ru={email_verify:!1,safe_mode_enable:!1,secure_path:"",email_whitelist_enable:!1,email_whitelist_suffix:[],email_gmail_limit_enable:!1,recaptcha_enable:!1,recaptcha_key:"",recaptcha_site_key:"",register_limit_by_ip_enable:!1,register_limit_count:"",register_limit_expire:"",password_limit_enable:!1,password_limit_count:"",password_limit_expire:""};function Iu(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),a=ge({resolver:Ne(Eu),defaultValues:Ru,mode:"onBlur"}),{data:i}=re({queryKey:["settings","safe"],queryFn:()=>gs("safe")}),{mutateAsync:l}=es({mutationFn:js,onSuccess:o=>{o.data&&A.success(s("common.autoSaved"))}});u.useEffect(()=>{if(i?.data.safe){const o=i.data.safe;Object.entries(o).forEach(([c,h])=>{typeof h=="number"?a.setValue(c,String(h)):a.setValue(c,h)}),r.current=o}},[i]);const d=u.useCallback(Se.debounce(async o=>{if(!Se.isEqual(o,r.current)){t(!0);try{await l(o),r.current=o}finally{t(!1)}}},1e3),[l]),m=u.useCallback(o=>{d(o)},[d]);return u.useEffect(()=>{const o=a.watch(c=>{m(c)});return()=>o.unsubscribe()},[a.watch,m]),e.jsx(_e,{...a,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:a.control,name:"email_verify",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.emailVerify.label")}),e.jsx(F,{children:s("safe.form.emailVerify.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"email_gmail_limit_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.gmailLimit.label")}),e.jsx(F,{children:s("safe.form.gmailLimit.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"safe_mode_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.safeMode.label")}),e.jsx(F,{children:s("safe.form.safeMode.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"secure_path",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.securePath.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.securePath.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.securePath.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"email_whitelist_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.emailWhitelist.label")}),e.jsx(F,{children:s("safe.form.emailWhitelist.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),a.watch("email_whitelist_enable")&&e.jsx(g,{control:a.control,name:"email_whitelist_suffix",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.emailWhitelist.suffixes.label")}),e.jsx(y,{children:e.jsx(ys,{placeholder:s("safe.form.emailWhitelist.suffixes.placeholder"),...o,value:(o.value||[]).join(` +`),onChange:c=>{const h=c.target.value.split(` +`).filter(Boolean);o.onChange(h),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.emailWhitelist.suffixes.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"recaptcha_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.recaptcha.enable.label")}),e.jsx(F,{children:s("safe.form.recaptcha.enable.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),a.watch("recaptcha_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(g,{control:a.control,name:"recaptcha_site_key",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.recaptcha.siteKey.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.recaptcha.siteKey.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.recaptcha.siteKey.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"recaptcha_key",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.recaptcha.key.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.recaptcha.key.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.recaptcha.key.description")}),e.jsx(D,{})]})})]}),e.jsx(g,{control:a.control,name:"register_limit_by_ip_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.registerLimit.enable.label")}),e.jsx(F,{children:s("safe.form.registerLimit.enable.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),a.watch("register_limit_by_ip_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(g,{control:a.control,name:"register_limit_count",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.registerLimit.count.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.registerLimit.count.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.registerLimit.count.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"register_limit_expire",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.registerLimit.expire.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.registerLimit.expire.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.registerLimit.expire.description")}),e.jsx(D,{})]})})]}),e.jsx(g,{control:a.control,name:"password_limit_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("safe.form.passwordLimit.enable.label")}),e.jsx(F,{children:s("safe.form.passwordLimit.enable.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),a.watch("password_limit_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(g,{control:a.control,name:"password_limit_count",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.passwordLimit.count.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.passwordLimit.count.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.passwordLimit.count.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"password_limit_expire",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("safe.form.passwordLimit.expire.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("safe.form.passwordLimit.expire.placeholder"),...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(F,{children:s("safe.form.passwordLimit.expire.description")}),e.jsx(D,{})]})})]}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("safe.form.saving")})]})})}function Vu(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("safe.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("safe.description")})]}),e.jsx(ke,{}),e.jsx(Iu,{})]})}const Mu=Object.freeze(Object.defineProperty({__proto__:null,default:Vu},Symbol.toStringTag,{value:"Module"})),Fu=x.object({plan_change_enable:x.boolean().nullable().default(!1),reset_traffic_method:x.coerce.number().nullable().default(0),surplus_enable:x.boolean().nullable().default(!1),new_order_event_id:x.coerce.number().nullable().default(0),renew_order_event_id:x.coerce.number().nullable().default(0),change_order_event_id:x.coerce.number().nullable().default(0),show_info_to_server_enable:x.boolean().nullable().default(!1),show_protocol_to_server_enable:x.boolean().nullable().default(!1),default_remind_expire:x.boolean().nullable().default(!1),default_remind_traffic:x.boolean().nullable().default(!1),subscribe_path:x.string().nullable().default("s")}),Ou={plan_change_enable:!1,reset_traffic_method:0,surplus_enable:!1,new_order_event_id:0,renew_order_event_id:0,change_order_event_id:0,show_info_to_server_enable:!1,show_protocol_to_server_enable:!1,default_remind_expire:!1,default_remind_traffic:!1,subscribe_path:"s"};function Lu(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),a=ge({resolver:Ne(Fu),defaultValues:Ou,mode:"onBlur"}),{data:i}=re({queryKey:["settings","subscribe"],queryFn:()=>gs("subscribe")}),{mutateAsync:l}=es({mutationFn:js,onSuccess:o=>{o.data&&A.success(s("common.autoSaved"))}});u.useEffect(()=>{if(i?.data?.subscribe){const o=i?.data?.subscribe;Object.entries(o).forEach(([c,h])=>{a.setValue(c,h)}),r.current=o}},[i]);const d=u.useCallback(Se.debounce(async o=>{if(!Se.isEqual(o,r.current)){t(!0);try{await l(o),r.current=o}finally{t(!1)}}},1e3),[l]),m=u.useCallback(o=>{d(o)},[d]);return u.useEffect(()=>{const o=a.watch(c=>{m(c)});return()=>o.unsubscribe()},[a.watch,m]),e.jsx(_e,{...a,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:a.control,name:"plan_change_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.plan_change_enable.title")}),e.jsx(F,{children:s("subscribe.plan_change_enable.description")}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"reset_traffic_method",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.reset_traffic_method.title")}),e.jsxs(G,{onValueChange:o.onChange,value:o.value?.toString()||"0",children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:"请选择重置方式"})})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("subscribe.reset_traffic_method.options.monthly_first")}),e.jsx(z,{value:"1",children:s("subscribe.reset_traffic_method.options.monthly_reset")}),e.jsx(z,{value:"2",children:s("subscribe.reset_traffic_method.options.no_reset")}),e.jsx(z,{value:"3",children:s("subscribe.reset_traffic_method.options.yearly_first")}),e.jsx(z,{value:"4",children:s("subscribe.reset_traffic_method.options.yearly_reset")})]})]}),e.jsx(F,{children:s("subscribe.reset_traffic_method.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"surplus_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.surplus_enable.title")}),e.jsx(F,{children:s("subscribe.surplus_enable.description")}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"new_order_event_id",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.new_order_event.title")}),e.jsx("div",{className:"relative w-max",children:e.jsx(y,{children:e.jsxs(G,{onValueChange:o.onChange,value:o.value?.toString(),children:[e.jsx(K,{children:e.jsx(W,{placeholder:"请选择"})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("subscribe.new_order_event.options.no_action")}),e.jsx(z,{value:"1",children:s("subscribe.new_order_event.options.reset_traffic")})]})]})})}),e.jsx(F,{children:s("subscribe.new_order_event.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"renew_order_event_id",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.renew_order_event.title")}),e.jsx("div",{className:"relative w-max",children:e.jsx(y,{children:e.jsxs(G,{onValueChange:o.onChange,value:o.value?.toString(),children:[e.jsx(K,{children:e.jsx(W,{placeholder:"请选择"})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("subscribe.renew_order_event.options.no_action")}),e.jsx(z,{value:"1",children:s("subscribe.renew_order_event.options.reset_traffic")})]})]})})}),e.jsx(F,{children:s("renew_order_event.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"change_order_event_id",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.change_order_event.title")}),e.jsx("div",{className:"relative w-max",children:e.jsx(y,{children:e.jsxs(G,{onValueChange:o.onChange,value:o.value?.toString(),children:[e.jsx(K,{children:e.jsx(W,{placeholder:"请选择"})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("subscribe.change_order_event.options.no_action")}),e.jsx(z,{value:"1",children:s("subscribe.change_order_event.options.reset_traffic")})]})]})})}),e.jsx(F,{children:s("subscribe.change_order_event.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"subscribe_path",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("subscribe.subscribe_path.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:"subscribe",...o,value:o.value||"",onChange:c=>{o.onChange(c),m(a.getValues())}})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[s("subscribe.subscribe_path.description"),e.jsx("br",{}),s("subscribe.subscribe_path.current_format",{path:o.value||"s"})]}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"show_info_to_server_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("subscribe.show_info_to_server.title")}),e.jsx(F,{children:s("subscribe.show_info_to_server.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"show_protocol_to_server_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("subscribe.show_protocol_to_server.title")}),e.jsx(F,{children:s("subscribe.show_protocol_to_server.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value||!1,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function zu(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("subscribe.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("subscribe.description")})]}),e.jsx(ke,{}),e.jsx(Lu,{})]})}const Au=Object.freeze(Object.defineProperty({__proto__:null,default:zu},Symbol.toStringTag,{value:"Module"})),$u=x.object({invite_force:x.boolean().default(!1),invite_commission:x.coerce.string().default("0"),invite_gen_limit:x.coerce.string().default("0"),invite_never_expire:x.boolean().default(!1),commission_first_time_enable:x.boolean().default(!1),commission_auto_check_enable:x.boolean().default(!1),commission_withdraw_limit:x.coerce.string().default("0"),commission_withdraw_method:x.array(x.string()).default(["支付宝","USDT","Paypal"]),withdraw_close_enable:x.boolean().default(!1),commission_distribution_enable:x.boolean().default(!1),commission_distribution_l1:x.coerce.number().default(0),commission_distribution_l2:x.coerce.number().default(0),commission_distribution_l3:x.coerce.number().default(0)}),Uu={invite_force:!1,invite_commission:"0",invite_gen_limit:"0",invite_never_expire:!1,commission_first_time_enable:!1,commission_auto_check_enable:!1,commission_withdraw_limit:"0",commission_withdraw_method:["支付宝","USDT","Paypal"],withdraw_close_enable:!1,commission_distribution_enable:!1,commission_distribution_l1:0,commission_distribution_l2:0,commission_distribution_l3:0};function Hu(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),a=ge({resolver:Ne($u),defaultValues:Uu,mode:"onBlur"}),{data:i}=re({queryKey:["settings","invite"],queryFn:()=>gs("invite")}),{mutateAsync:l}=es({mutationFn:js,onSuccess:o=>{o.data&&A.success(s("common.autoSaved"))}});u.useEffect(()=>{if(i?.data?.invite){const o=i?.data?.invite;Object.entries(o).forEach(([c,h])=>{typeof h=="number"?a.setValue(c,String(h)):a.setValue(c,h)}),r.current=o}},[i]);const d=u.useCallback(Se.debounce(async o=>{if(!Se.isEqual(o,r.current)){t(!0);try{await l(o),r.current=o}finally{t(!1)}}},1e3),[l]),m=u.useCallback(o=>{d(o)},[d]);return u.useEffect(()=>{const o=a.watch(c=>{m(c)});return()=>o.unsubscribe()},[a.watch,m]),e.jsx(_e,{...a,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:a.control,name:"invite_force",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("invite.invite_force.title")}),e.jsx(F,{children:s("invite.invite_force.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"invite_commission",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("invite.invite_commission.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("invite.invite_commission.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("invite.invite_commission.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"invite_gen_limit",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("invite.invite_gen_limit.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("invite.invite_gen_limit.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("invite.invite_gen_limit.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"invite_never_expire",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("invite.invite_never_expire.title")}),e.jsx(F,{children:s("invite.invite_never_expire.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"commission_first_time_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("invite.commission_first_time.title")}),e.jsx(F,{children:s("invite.commission_first_time.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"commission_auto_check_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("invite.commission_auto_check.title")}),e.jsx(F,{children:s("invite.commission_auto_check.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"commission_withdraw_limit",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("invite.commission_withdraw_limit.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("invite.commission_withdraw_limit.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("invite.commission_withdraw_limit.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"commission_withdraw_method",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("invite.commission_withdraw_method.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("invite.commission_withdraw_method.placeholder"),...o,value:Array.isArray(o.value)?o.value.join(","):"",onChange:c=>{const h=c.target.value.split(",").filter(Boolean);o.onChange(h),m(a.getValues())}})}),e.jsx(F,{children:s("invite.commission_withdraw_method.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"withdraw_close_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("invite.withdraw_close.title")}),e.jsx(F,{children:s("invite.withdraw_close.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),e.jsx(g,{control:a.control,name:"commission_distribution_enable",render:({field:o})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("invite.commission_distribution.title")}),e.jsx(F,{children:s("invite.commission_distribution.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:c=>{o.onChange(c),m(a.getValues())}})})]})}),a.watch("commission_distribution_enable")&&e.jsxs(e.Fragment,{children:[e.jsx(g,{control:a.control,name:"commission_distribution_l1",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:s("invite.commission_distribution.l1")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:s("invite.commission_distribution.placeholder"),...o,value:o.value||"",onChange:c=>{const h=c.target.value?Number(c.target.value):0;o.onChange(h),m(a.getValues())}})}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"commission_distribution_l2",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:s("invite.commission_distribution.l2")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:s("invite.commission_distribution.placeholder"),...o,value:o.value||"",onChange:c=>{const h=c.target.value?Number(c.target.value):0;o.onChange(h),m(a.getValues())}})}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"commission_distribution_l3",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:s("invite.commission_distribution.l3")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:s("invite.commission_distribution.placeholder"),...o,value:o.value||"",onChange:c=>{const h=c.target.value?Number(c.target.value):0;o.onChange(h),m(a.getValues())}})}),e.jsx(D,{})]})})]}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("invite.saving")})]})})}function qu(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("invite.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("invite.description")})]}),e.jsx(ke,{}),e.jsx(Hu,{})]})}const Ku=Object.freeze(Object.defineProperty({__proto__:null,default:qu},Symbol.toStringTag,{value:"Module"})),Bu=x.object({frontend_theme:x.string().nullable(),frontend_theme_sidebar:x.string().nullable(),frontend_theme_header:x.string().nullable(),frontend_theme_color:x.string().nullable(),frontend_background_url:x.string().url().nullable()}),Gu={frontend_theme:"",frontend_theme_sidebar:"",frontend_theme_header:"",frontend_theme_color:"",frontend_background_url:""};function Wu(){const{data:s}=re({queryKey:["settings","frontend"],queryFn:()=>gs("frontend")}),n=ge({resolver:Ne(Bu),defaultValues:Gu,mode:"onChange"});u.useEffect(()=>{if(s?.data?.frontend){const r=s?.data?.frontend;Object.entries(r).forEach(([a,i])=>{n.setValue(a,i)})}},[s]);function t(r){js(r).then(({data:a})=>{a&&A.success("更新成功")})}return e.jsx(_e,{...n,children:e.jsxs("form",{onSubmit:n.handleSubmit(t),className:"space-y-8",children:[e.jsx(g,{control:n.control,name:"frontend_theme_sidebar",render:({field:r})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:"边栏风格"}),e.jsx(F,{children:"边栏风格"})]}),e.jsx(y,{children:e.jsx(Y,{checked:r.value,onCheckedChange:r.onChange})})]})}),e.jsx(g,{control:n.control,name:"frontend_theme_header",render:({field:r})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:"头部风格"}),e.jsx(F,{children:"边栏风格"})]}),e.jsx(y,{children:e.jsx(Y,{checked:r.value,onCheckedChange:r.onChange})})]})}),e.jsx(g,{control:n.control,name:"frontend_theme_color",render:({field:r})=>e.jsxs(f,{children:[e.jsx(j,{children:"主题色"}),e.jsxs("div",{className:"relative w-max",children:[e.jsx(y,{children:e.jsxs("select",{className:N(nt({variant:"outline"}),"w-[200px] appearance-none font-normal"),...r,children:[e.jsx("option",{value:"default",children:"默认"}),e.jsx("option",{value:"black",children:"黑色"}),e.jsx("option",{value:"blackblue",children:"暗蓝色"}),e.jsx("option",{value:"green",children:"奶绿色"})]})}),e.jsx(Ta,{className:"absolute right-3 top-2.5 h-4 w-4 opacity-50"})]}),e.jsx(F,{children:"主题色"}),e.jsx(D,{})]})}),e.jsx(g,{control:n.control,name:"frontend_background_url",render:({field:r})=>e.jsxs(f,{children:[e.jsx(j,{children:"背景"}),e.jsx(y,{children:e.jsx(T,{placeholder:"请输入图片地址",...r})}),e.jsx(F,{children:"将会在后台登录页面进行展示。"}),e.jsx(D,{})]})}),e.jsx(P,{type:"submit",children:"保存设置"})]})})}function Yu(){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:"个性化设置"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"自定义系统界面外观,包括主题风格、布局、颜色方案、背景图等个性化选项。"})]}),e.jsx(ke,{}),e.jsx(Wu,{})]})}const Qu=Object.freeze(Object.defineProperty({__proto__:null,default:Yu},Symbol.toStringTag,{value:"Module"})),Ju=x.object({server_pull_interval:x.coerce.number().nullable(),server_push_interval:x.coerce.number().nullable(),server_token:x.string().nullable(),device_limit_mode:x.coerce.number().nullable()}),Xu={server_pull_interval:0,server_push_interval:0,server_token:"",device_limit_mode:0};function Zu(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),a=ge({resolver:Ne(Ju),defaultValues:Xu,mode:"onBlur"}),{data:i}=re({queryKey:["settings","server"],queryFn:()=>gs("server")}),{mutateAsync:l}=es({mutationFn:js,onSuccess:c=>{c.data&&A.success(s("common.AutoSaved"))}});u.useEffect(()=>{if(i?.data.server){const c=i.data.server;Object.entries(c).forEach(([h,_])=>{a.setValue(h,_)}),r.current=c}},[i]);const d=u.useCallback(Se.debounce(async c=>{if(!Se.isEqual(c,r.current)){t(!0);try{await l(c),r.current=c}finally{t(!1)}}},1e3),[l]),m=u.useCallback(c=>{d(c)},[d]);u.useEffect(()=>{const c=a.watch(h=>{m(h)});return()=>c.unsubscribe()},[a.watch,m]);const o=()=>{const c=Math.floor(Math.random()*17)+16,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let _="";for(let E=0;Ee.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("server.server_token.title")}),e.jsx(y,{children:e.jsxs("div",{className:"relative",children:[e.jsx(T,{placeholder:s("server.server_token.placeholder"),...c,value:c.value||"",className:"pr-10"}),e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(J,{type:"button",variant:"ghost",size:"icon",className:"absolute right-0 top-0 h-full px-3 py-2",onClick:h=>{h.preventDefault(),o()},children:e.jsx(bo,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"})})}),e.jsx(ce,{children:e.jsx("p",{children:s("server.server_token.generate_tooltip")})})]})})]})}),e.jsx(F,{children:s("server.server_token.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"server_pull_interval",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("server.server_pull_interval.title")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:s("server.server_pull_interval.placeholder"),...c,value:c.value||"",onChange:h=>{const _=h.target.value?Number(h.target.value):null;c.onChange(_)}})}),e.jsx(F,{children:s("server.server_pull_interval.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"server_push_interval",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("server.server_push_interval.title")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:s("server.server_push_interval.placeholder"),...c,value:c.value||"",onChange:h=>{const _=h.target.value?Number(h.target.value):null;c.onChange(_)}})}),e.jsx(F,{children:s("server.server_push_interval.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"device_limit_mode",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("server.device_limit_mode.title")}),e.jsxs(G,{onValueChange:c.onChange,value:c.value?.toString()||"0",children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:s("server.device_limit_mode.placeholder")})})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("server.device_limit_mode.strict")}),e.jsx(z,{value:"1",children:s("server.device_limit_mode.relaxed")})]})]}),e.jsx(F,{children:s("server.device_limit_mode.description")}),e.jsx(D,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("server.saving")})]})})}function em(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("server.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("server.description")})]}),e.jsx(ke,{}),e.jsx(Zu,{})]})}const sm=Object.freeze(Object.defineProperty({__proto__:null,default:em},Symbol.toStringTag,{value:"Module"}));function tm({open:s,onOpenChange:n,result:t}){const r=!t.error;return e.jsx(be,{open:s,onOpenChange:n,children:e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(tr,{className:"h-5 w-5 text-green-500"}):e.jsx(ar,{className:"h-5 w-5 text-destructive"}),e.jsx(ye,{children:r?"邮件发送成功":"邮件发送失败"})]}),e.jsx(Te,{children:r?"测试邮件已成功发送,请检查收件箱":"发送测试邮件时遇到错误"})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"font-medium",children:"发送详情"}),e.jsxs("div",{className:"grid grid-cols-[100px_1fr] items-center gap-2 text-sm",children:[e.jsx("div",{className:"text-muted-foreground",children:"收件地址"}),e.jsx("div",{children:t.email}),e.jsx("div",{className:"text-muted-foreground",children:"邮件主题"}),e.jsx("div",{children:t.subject}),e.jsx("div",{className:"text-muted-foreground",children:"模板名称"}),e.jsx("div",{children:t.template_name})]})]}),t.error&&e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"font-medium text-destructive",children:"错误信息"}),e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive break-all",children:t.error})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx("div",{className:"font-medium",children:"配置信息"}),e.jsx(zs,{className:"h-[200px] rounded-md border p-4",children:e.jsx("div",{className:"grid gap-2 text-sm",children:e.jsxs("div",{className:"grid grid-cols-[100px_1fr] items-center gap-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"驱动"}),e.jsx("div",{children:t.config.driver}),e.jsx("div",{className:"text-muted-foreground",children:"服务器"}),e.jsx("div",{children:t.config.host}),e.jsx("div",{className:"text-muted-foreground",children:"端口"}),e.jsx("div",{children:t.config.port}),e.jsx("div",{className:"text-muted-foreground",children:"加密方式"}),e.jsx("div",{children:t.config.encryption||"无"}),e.jsx("div",{className:"text-muted-foreground",children:"发件人"}),e.jsx("div",{children:t.config.from.address?`${t.config.from.address}${t.config.from.name?` (${t.config.from.name})`:""}`:"未设置"}),e.jsx("div",{className:"text-muted-foreground",children:"用户名"}),e.jsx("div",{children:t.config.username||"未设置"})]})})})]})]})]})})}const am=x.object({email_template:x.string().nullable().default("classic"),email_host:x.string().nullable().default(""),email_port:x.coerce.number().nullable().default(465),email_username:x.string().nullable().default(""),email_password:x.string().nullable().default(""),email_encryption:x.string().nullable().default(""),email_from_address:x.string().email().nullable().default(""),remind_mail_enable:x.boolean().nullable().default(!1)});function nm(){const{t:s}=V("settings"),[n,t]=u.useState(null),[r,a]=u.useState(!1),i=u.useRef(null),[l,d]=u.useState(!1),m=ge({resolver:Ne(am),defaultValues:{},mode:"onBlur"}),{data:o}=re({queryKey:["settings","email"],queryFn:()=>gs("email")}),{data:c}=re({queryKey:["emailTemplate"],queryFn:()=>jd()}),{mutateAsync:h}=es({mutationFn:js,onSuccess:w=>{w.data&&A.success(s("common.autoSaved"))}}),{mutate:_,isPending:E}=es({mutationFn:vd,onMutate:()=>{t(null),a(!1)},onSuccess:w=>{t(w.data),a(!0),w.data.error?A.error(s("email.test.error")):A.success(s("email.test.success"))}});u.useEffect(()=>{if(o?.data.email){const w=o.data.email;Object.entries(w).forEach(([b,k])=>{m.setValue(b,k)}),i.current=w}},[o]);const C=u.useCallback(Se.debounce(async w=>{if(!Se.isEqual(w,i.current)){d(!0);try{await h(w),i.current=w}finally{d(!1)}}},1e3),[h]),S=u.useCallback(w=>{C(w)},[C]);return u.useEffect(()=>{const w=m.watch(b=>{S(b)});return()=>w.unsubscribe()},[m.watch,S]),e.jsxs(e.Fragment,{children:[e.jsx(_e,{...m,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:m.control,name:"email_host",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_host.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...w,value:w.value||""})}),e.jsx(F,{children:s("email.email_host.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"email_port",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_port.title")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:s("common.placeholder"),...w,value:w.value||"",onChange:b=>{const k=b.target.value?Number(b.target.value):null;w.onChange(k)}})}),e.jsx(F,{children:s("email.email_port.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"email_encryption",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_encryption.title")}),e.jsxs(G,{onValueChange:w.onChange,value:w.value||"none",children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:"请选择加密方式"})})}),e.jsxs(B,{children:[e.jsx(z,{value:"none",children:s("email.email_encryption.none")}),e.jsx(z,{value:"ssl",children:s("email.email_encryption.ssl")}),e.jsx(z,{value:"tls",children:s("email.email_encryption.tls")})]})]}),e.jsx(F,{children:s("email.email_encryption.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"email_username",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_username.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...w,value:w.value||""})}),e.jsx(F,{children:s("email.email_username.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"email_password",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_password.title")}),e.jsx(y,{children:e.jsx(T,{type:"password",placeholder:s("common.placeholder"),...w,value:w.value||""})}),e.jsx(F,{children:s("email.email_password.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"email_from_address",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_from.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...w,value:w.value||""})}),e.jsx(F,{children:s("email.email_from.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"email_template",render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("email.email_template.title")}),e.jsxs(G,{onValueChange:b=>{w.onChange(b),S(m.getValues())},value:w.value||void 0,children:[e.jsx(y,{children:e.jsx(K,{className:"w-[200px]",children:e.jsx(W,{placeholder:s("email.email_template.placeholder")})})}),e.jsx(B,{children:c?.data?.map(b=>e.jsx(z,{value:b,children:b},b))})]}),e.jsx(F,{children:s("email.email_template.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"remind_mail_enable",render:({field:w})=>e.jsxs(f,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:s("email.remind_mail.title")}),e.jsx(F,{children:s("email.remind_mail.description")})]}),e.jsx(y,{children:e.jsx(Y,{checked:w.value||!1,onCheckedChange:b=>{w.onChange(b),S(m.getValues())}})})]})}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(P,{onClick:()=>_(),loading:E,disabled:E,children:s(E?"test.sending":"test.title")})})]})}),l&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("saving")}),n&&e.jsx(tm,{open:r,onOpenChange:a,result:n})]})}function rm(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("email.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("email.description")})]}),e.jsx(ke,{}),e.jsx(nm,{})]})}const lm=Object.freeze(Object.defineProperty({__proto__:null,default:rm},Symbol.toStringTag,{value:"Module"})),im=x.object({telegram_bot_enable:x.boolean().nullable(),telegram_bot_token:x.string().nullable(),telegram_discuss_link:x.string().nullable()}),om={telegram_bot_enable:!1,telegram_bot_token:"",telegram_discuss_link:""};function cm(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),a=ge({resolver:Ne(im),defaultValues:om,mode:"onBlur"}),{data:i}=re({queryKey:["settings","telegram"],queryFn:()=>gs("telegram")}),{mutateAsync:l}=es({mutationFn:js,onSuccess:h=>{h.data&&A.success(s("common.autoSaved"))}}),{mutate:d,isPending:m}=es({mutationFn:bd,onSuccess:h=>{h.data&&A.success(s("telegram.webhook.success"))}});u.useEffect(()=>{if(i?.data.telegram){const h=i.data.telegram;Object.entries(h).forEach(([_,E])=>{a.setValue(_,E)}),r.current=h}},[i]);const o=u.useCallback(Se.debounce(async h=>{if(!Se.isEqual(h,r.current)){t(!0);try{await l(h),r.current=h}finally{t(!1)}}},1e3),[l]),c=u.useCallback(h=>{o(h)},[o]);return u.useEffect(()=>{const h=a.watch(_=>{c(_)});return()=>h.unsubscribe()},[a.watch,c]),e.jsx(_e,{...a,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:a.control,name:"telegram_bot_token",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("telegram.bot_token.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("telegram.bot_token.placeholder"),...h,value:h.value||""})}),e.jsx(F,{children:s("telegram.bot_token.description")}),e.jsx(D,{})]})}),a.watch("telegram_bot_token")&&e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("telegram.webhook.title")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(P,{loading:m,disabled:m,onClick:()=>d(),children:s(m?"telegram.webhook.setting":"telegram.webhook.button")}),n&&e.jsx("span",{className:"text-sm text-muted-foreground",children:s("common.saving")})]}),e.jsx(F,{children:s("telegram.webhook.description")}),e.jsx(D,{})]}),e.jsx(g,{control:a.control,name:"telegram_bot_enable",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("telegram.bot_enable.title")}),e.jsx(F,{children:s("telegram.bot_enable.description")}),e.jsx(y,{children:e.jsx(Y,{checked:h.value||!1,onCheckedChange:_=>{h.onChange(_),c(a.getValues())}})}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"telegram_discuss_link",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("telegram.discuss_link.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("telegram.discuss_link.placeholder"),...h,value:h.value||""})}),e.jsx(F,{children:s("telegram.discuss_link.description")}),e.jsx(D,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function dm(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("telegram.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("telegram.description")})]}),e.jsx(ke,{}),e.jsx(cm,{})]})}const um=Object.freeze(Object.defineProperty({__proto__:null,default:dm},Symbol.toStringTag,{value:"Module"})),mm=x.object({windows_version:x.string().nullable(),windows_download_url:x.string().nullable(),macos_version:x.string().nullable(),macos_download_url:x.string().nullable(),android_version:x.string().nullable(),android_download_url:x.string().nullable()}),xm={windows_version:"",windows_download_url:"",macos_version:"",macos_download_url:"",android_version:"",android_download_url:""};function hm(){const{t:s}=V("settings"),[n,t]=u.useState(!1),r=u.useRef(null),a=ge({resolver:Ne(mm),defaultValues:xm,mode:"onBlur"}),{data:i}=re({queryKey:["settings","app"],queryFn:()=>gs("app")}),{mutateAsync:l}=es({mutationFn:js,onSuccess:o=>{o.data&&A.success(s("app.save_success"))}});u.useEffect(()=>{if(i?.data.app){const o=i.data.app;Object.entries(o).forEach(([c,h])=>{a.setValue(c,h)}),r.current=o}},[i]);const d=u.useCallback(Se.debounce(async o=>{if(!Se.isEqual(o,r.current)){t(!0);try{await l(o),r.current=o}finally{t(!1)}}},1e3),[l]),m=u.useCallback(o=>{d(o)},[d]);return u.useEffect(()=>{const o=a.watch(c=>{m(c)});return()=>o.unsubscribe()},[a.watch,m]),e.jsx(_e,{...a,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:a.control,name:"windows_version",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("app.windows.version.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("app.windows.version.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"windows_download_url",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("app.windows.download.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("app.windows.download.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"macos_version",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("app.macos.version.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("app.macos.version.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"macos_download_url",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("app.macos.download.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("app.macos.download.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"android_version",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("app.android.version.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("app.android.version.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"android_download_url",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{className:"text-base",children:s("app.android.download.title")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("common.placeholder"),...o,value:o.value||""})}),e.jsx(F,{children:s("app.android.download.description")}),e.jsx(D,{})]})}),n&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("common.saving")})]})})}function pm(){const{t:s}=V("settings");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-medium",children:s("app.title")}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s("app.description")})]}),e.jsx(ke,{}),e.jsx(hm,{})]})}const fm=Object.freeze(Object.defineProperty({__proto__:null,default:pm},Symbol.toStringTag,{value:"Module"})),Ia=u.forwardRef(({className:s,...n},t)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:t,className:N("w-full caption-bottom text-sm",s),...n})}));Ia.displayName="Table";const Va=u.forwardRef(({className:s,...n},t)=>e.jsx("thead",{ref:t,className:N("[&_tr]:border-b",s),...n}));Va.displayName="TableHeader";const Ma=u.forwardRef(({className:s,...n},t)=>e.jsx("tbody",{ref:t,className:N("[&_tr:last-child]:border-0",s),...n}));Ma.displayName="TableBody";const gm=u.forwardRef(({className:s,...n},t)=>e.jsx("tfoot",{ref:t,className:N("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...n}));gm.displayName="TableFooter";const Is=u.forwardRef(({className:s,...n},t)=>e.jsx("tr",{ref:t,className:N("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",s),...n}));Is.displayName="TableRow";const Fa=u.forwardRef(({className:s,...n},t)=>e.jsx("th",{ref:t,className:N("h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",s),...n}));Fa.displayName="TableHead";const Zs=u.forwardRef(({className:s,...n},t)=>e.jsx("td",{ref:t,className:N("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",s),...n}));Zs.displayName="TableCell";const jm=u.forwardRef(({className:s,...n},t)=>e.jsx("caption",{ref:t,className:N("mt-4 text-sm text-muted-foreground",s),...n}));jm.displayName="TableCaption";function vm({table:s}){const[n,t]=u.useState(""),{t:r}=V("common");u.useEffect(()=>{t((s.getState().pagination.pageIndex+1).toString())},[s.getState().pagination.pageIndex]);const a=i=>{const l=parseInt(i);!isNaN(l)&&l>=1&&l<=s.getPageCount()?s.setPageIndex(l-1):t((s.getState().pagination.pageIndex+1).toString())};return e.jsxs("div",{className:"flex flex-col-reverse gap-4 px-2 py-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:r("table.pagination.selected",{selected:s.getFilteredSelectedRowModel().rows.length,total:s.getFilteredRowModel().rows.length})}),e.jsxs("div",{className:"flex flex-col-reverse items-center gap-4 sm:flex-row sm:gap-6 lg:gap-8",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("p",{className:"text-sm font-medium",children:r("table.pagination.itemsPerPage")}),e.jsxs(G,{value:`${s.getState().pagination.pageSize}`,onValueChange:i=>{s.setPageSize(Number(i))},children:[e.jsx(K,{className:"h-8 w-[70px]",children:e.jsx(W,{placeholder:s.getState().pagination.pageSize})}),e.jsx(B,{side:"top",children:[10,20,30,40,50,100,500].map(i=>e.jsx(z,{value:`${i}`,children:i},i))})]})]}),e.jsxs("div",{className:"flex items-center justify-center space-x-2 text-sm font-medium",children:[e.jsx("span",{children:r("table.pagination.page")}),e.jsx(T,{type:"text",value:n,onChange:i=>t(i.target.value),onBlur:i=>a(i.target.value),onKeyDown:i=>{i.key==="Enter"&&a(i.currentTarget.value)},className:"h-8 w-[50px] text-center"}),e.jsx("span",{children:r("table.pagination.pageOf",{total:s.getPageCount()})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs(P,{variant:"outline",className:"hidden h-8 w-8 p-0 lg:flex",onClick:()=>s.setPageIndex(0),disabled:!s.getCanPreviousPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.firstPage")}),e.jsx(yo,{className:"h-4 w-4"})]}),e.jsxs(P,{variant:"outline",className:"h-8 w-8 p-0",onClick:()=>s.previousPage(),disabled:!s.getCanPreviousPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.previousPage")}),e.jsx(Zn,{className:"h-4 w-4"})]}),e.jsxs(P,{variant:"outline",className:"h-8 w-8 p-0",onClick:()=>s.nextPage(),disabled:!s.getCanNextPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.nextPage")}),e.jsx(Sa,{className:"h-4 w-4"})]}),e.jsxs(P,{variant:"outline",className:"hidden h-8 w-8 p-0 lg:flex",onClick:()=>s.setPageIndex(s.getPageCount()-1),disabled:!s.getCanNextPage(),children:[e.jsx("span",{className:"sr-only",children:r("table.pagination.lastPage")}),e.jsx(No,{className:"h-4 w-4"})]})]})]})]})}function hs({table:s,toolbar:n,draggable:t=!1,onDragStart:r,onDragEnd:a,onDragOver:i,onDragLeave:l,onDrop:d,showPagination:m=!0,isLoading:o=!1}){const{t:c}=V("common"),h=u.useRef(null),_=s.getAllColumns().filter(w=>w.getIsPinned()==="left"),E=s.getAllColumns().filter(w=>w.getIsPinned()==="right"),C=w=>_.slice(0,w).reduce((b,k)=>b+(k.getSize()??0),0),S=w=>E.slice(w+1).reduce((b,k)=>b+(k.getSize()??0),0);return e.jsxs("div",{className:"space-y-4",children:[typeof n=="function"?n(s):n,e.jsx("div",{ref:h,className:"relative overflow-auto rounded-md border bg-card",children:e.jsx("div",{className:"overflow-auto",children:e.jsxs(Ia,{children:[e.jsx(Va,{children:s.getHeaderGroups().map(w=>e.jsx(Is,{className:"hover:bg-transparent",children:w.headers.map((b,k)=>{const p=b.column.getIsPinned()==="left",v=b.column.getIsPinned()==="right",M=p?C(_.indexOf(b.column)):void 0,H=v?S(E.indexOf(b.column)):void 0;return e.jsx(Fa,{colSpan:b.colSpan,style:{width:b.getSize(),...p&&{left:M},...v&&{right:H}},className:N("h-11 bg-card px-4 text-muted-foreground",(p||v)&&["sticky z-20","before:absolute before:bottom-0 before:top-0 before:w-[1px] before:bg-border",p&&"before:right-0",v&&"before:left-0"]),children:b.isPlaceholder?null:Rt(b.column.columnDef.header,b.getContext())},b.id)})},w.id))}),e.jsx(Ma,{children:s.getRowModel().rows?.length?s.getRowModel().rows.map((w,b)=>e.jsx(Is,{"data-state":w.getIsSelected()&&"selected",className:"hover:bg-muted/50",draggable:t,onDragStart:k=>r?.(k,b),onDragEnd:a,onDragOver:i,onDragLeave:l,onDrop:k=>d?.(k,b),children:w.getVisibleCells().map((k,p)=>{const v=k.column.getIsPinned()==="left",M=k.column.getIsPinned()==="right",H=v?C(_.indexOf(k.column)):void 0,se=M?S(E.indexOf(k.column)):void 0;return e.jsx(Zs,{style:{width:k.column.getSize(),...v&&{left:H},...M&&{right:se}},className:N("bg-card",(v||M)&&["sticky z-20","before:absolute before:bottom-0 before:top-0 before:w-[1px] before:bg-border",v&&"before:right-0",M&&"before:left-0"]),children:Rt(k.column.columnDef.cell,k.getContext())},k.id)})},w.id)):e.jsx(Is,{children:e.jsx(Zs,{colSpan:s.getAllColumns().length,className:"h-24 text-center",children:c("table.noData")})})})]})})}),m&&e.jsx(vm,{table:s})]})}const bm=s=>x.object({id:x.number().nullable(),name:x.string().min(2,s("form.validation.name.min")).max(30,s("form.validation.name.max")),icon:x.string().optional().nullable(),notify_domain:x.string().refine(t=>!t||/^https?:\/\/\S+/.test(t),s("form.validation.notify_domain.url")).optional().nullable(),handling_fee_fixed:x.coerce.number().min(0).optional().nullable(),handling_fee_percent:x.coerce.number().min(0).max(100).optional().nullable(),payment:x.string().min(1,s("form.validation.payment.required")),config:x.record(x.string(),x.string())}),on={id:null,name:"",icon:"",notify_domain:"",handling_fee_fixed:0,handling_fee_percent:0,payment:"",config:{}};function qr({refetch:s,dialogTrigger:n,type:t="add",defaultFormValues:r=on}){const{t:a}=V("payment"),[i,l]=u.useState(!1),[d,m]=u.useState(!1),[o,c]=u.useState([]),[h,_]=u.useState([]),E=bm(a),C=ge({resolver:Ne(E),defaultValues:r,mode:"onChange"}),S=C.watch("payment");u.useEffect(()=>{i&&(async()=>{const{data:k}=await Oc();c(k)})()},[i]),u.useEffect(()=>{if(!S||!i)return;(async()=>{const k={payment:S,...t==="edit"&&{id:Number(C.getValues("id"))}};Lc(k).then(({data:p})=>{_(p);const v=p.reduce((M,H)=>(H.field_name&&(M[H.field_name]=H.value??""),M),{});C.setValue("config",v)})})()},[S,i,C,t]);const w=async b=>{m(!0);try{(await zc(b)).data&&(A.success(a("form.messages.success")),C.reset(on),s(),l(!1))}finally{m(!1)}};return e.jsxs(be,{open:i,onOpenChange:l,children:[e.jsx(Je,{asChild:!0,children:n||e.jsxs(P,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Ve,{icon:"ion:add"})," ",e.jsx("div",{children:a("form.add.button")})]})}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsx(Ce,{children:e.jsx(ye,{children:a(t==="add"?"form.add.title":"form.edit.title")})}),e.jsx(_e,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(w),className:"space-y-4",children:[e.jsx(g,{control:C.control,name:"name",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:a("form.fields.name.placeholder"),...b})}),e.jsx(F,{children:a("form.fields.name.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"icon",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.icon.label")}),e.jsx(y,{children:e.jsx(T,{...b,value:b.value||"",placeholder:a("form.fields.icon.placeholder")})}),e.jsx(F,{children:a("form.fields.icon.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"notify_domain",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.notify_domain.label")}),e.jsx(y,{children:e.jsx(T,{...b,value:b.value||"",placeholder:a("form.fields.notify_domain.placeholder")})}),e.jsx(F,{children:a("form.fields.notify_domain.description")}),e.jsx(D,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(g,{control:C.control,name:"handling_fee_percent",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.handling_fee_percent.label")}),e.jsx(y,{children:e.jsx(T,{type:"number",...b,value:b.value||"",placeholder:a("form.fields.handling_fee_percent.placeholder")})}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"handling_fee_fixed",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.handling_fee_fixed.label")}),e.jsx(y,{children:e.jsx(T,{type:"number",...b,value:b.value||"",placeholder:a("form.fields.handling_fee_fixed.placeholder")})}),e.jsx(D,{})]})})]}),e.jsx(g,{control:C.control,name:"payment",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.payment.label")}),e.jsxs(G,{onValueChange:b.onChange,defaultValue:b.value,children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:a("form.fields.payment.placeholder")})})}),e.jsx(B,{children:o.map(k=>e.jsx(z,{value:k,children:k},k))})]}),e.jsx(F,{children:a("form.fields.payment.description")}),e.jsx(D,{})]})}),h.length>0&&e.jsx("div",{className:"space-y-4",children:h.map(b=>e.jsx(g,{control:C.control,name:`config.${b.field_name}`,render:({field:k})=>e.jsxs(f,{children:[e.jsx(j,{children:b.label}),e.jsx(y,{children:e.jsx(T,{...k,value:k.value||""})}),e.jsx(D,{})]})},b.field_name))}),e.jsxs(ze,{children:[e.jsx(yt,{asChild:!0,children:e.jsx(P,{type:"button",variant:"outline",children:a("form.buttons.cancel")})}),e.jsx(P,{type:"submit",disabled:d,children:a("form.buttons.submit")})]})]})})]})]})}function O({column:s,title:n,tooltip:t,className:r}){return s.getCanSort()?e.jsx("div",{className:"flex items-center gap-1",children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(P,{variant:"ghost",size:"default",className:N("-ml-3 flex h-8 items-center gap-2 text-nowrap font-medium hover:bg-muted/60",r),onClick:()=>s.toggleSorting(s.getIsSorted()==="asc"),children:[e.jsx("span",{children:n}),t&&e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(Qa,{className:"h-4 w-4 cursor-pointer text-muted-foreground"})}),e.jsx(ce,{children:t})]})}),s.getIsSorted()==="asc"?e.jsx(pa,{className:"h-4 w-4 text-foreground/70"}):s.getIsSorted()==="desc"?e.jsx(fa,{className:"h-4 w-4 text-foreground/70"}):e.jsx(_o,{className:"h-4 w-4 text-muted-foreground/70 transition-colors hover:text-foreground/70"})]})})}):e.jsxs("div",{className:N("flex items-center space-x-1 text-nowrap py-2 font-medium text-muted-foreground",r),children:[e.jsx("span",{children:n}),t&&e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{children:e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(ce,{children:t})]})})]})}const Oa=wo,Kr=Co,ym=So,Br=u.forwardRef(({className:s,...n},t)=>e.jsx(rr,{className:N("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...n,ref:t}));Br.displayName=rr.displayName;const Yt=u.forwardRef(({className:s,...n},t)=>e.jsxs(ym,{children:[e.jsx(Br,{}),e.jsx(lr,{ref:t,className:N("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...n})]}));Yt.displayName=lr.displayName;const Qt=({className:s,...n})=>e.jsx("div",{className:N("flex flex-col space-y-2 text-center sm:text-left",s),...n});Qt.displayName="AlertDialogHeader";const Jt=({className:s,...n})=>e.jsx("div",{className:N("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...n});Jt.displayName="AlertDialogFooter";const Xt=u.forwardRef(({className:s,...n},t)=>e.jsx(ir,{ref:t,className:N("text-lg font-semibold",s),...n}));Xt.displayName=ir.displayName;const Zt=u.forwardRef(({className:s,...n},t)=>e.jsx(or,{ref:t,className:N("text-sm text-muted-foreground",s),...n}));Zt.displayName=or.displayName;const ea=u.forwardRef(({className:s,...n},t)=>e.jsx(cr,{ref:t,className:N(st(),s),...n}));ea.displayName=cr.displayName;const sa=u.forwardRef(({className:s,...n},t)=>e.jsx(dr,{ref:t,className:N(st({variant:"outline"}),"mt-2 sm:mt-0",s),...n}));sa.displayName=dr.displayName;function Qe({onConfirm:s,children:n,title:t="确认操作",description:r="确定要执行此操作吗?",cancelText:a="取消",confirmText:i="确认",variant:l="default",className:d}){return e.jsxs(Oa,{children:[e.jsx(Kr,{asChild:!0,children:n}),e.jsxs(Yt,{className:N("sm:max-w-[425px]",d),children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:t}),e.jsx(Zt,{children:r})]}),e.jsxs(Jt,{children:[e.jsx(sa,{asChild:!0,children:e.jsx(P,{variant:"outline",children:a})}),e.jsx(ea,{asChild:!0,children:e.jsx(P,{variant:l,onClick:s,children:i})})]})]})]})}const Gr=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M11.29 15.29a2 2 0 0 0-.12.15a.8.8 0 0 0-.09.18a.6.6 0 0 0-.06.18a1.4 1.4 0 0 0 0 .2a.84.84 0 0 0 .08.38a.9.9 0 0 0 .54.54a.94.94 0 0 0 .76 0a.9.9 0 0 0 .54-.54A1 1 0 0 0 13 16a1 1 0 0 0-.29-.71a1 1 0 0 0-1.42 0M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2m0 18a8 8 0 1 1 8-8a8 8 0 0 1-8 8m0-13a3 3 0 0 0-2.6 1.5a1 1 0 1 0 1.73 1A1 1 0 0 1 12 9a1 1 0 0 1 0 2a1 1 0 0 0-1 1v1a1 1 0 0 0 2 0v-.18A3 3 0 0 0 12 7"})}),Nm=({refetch:s,isSortMode:n=!1})=>{const{t}=V("payment");return[{id:"drag-handle",header:()=>null,cell:()=>e.jsx("div",{className:n?"cursor-move":"opacity-0",children:e.jsx(Ht,{className:"size-4"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:r})=>e.jsx(O,{column:r,title:t("table.columns.id")}),cell:({row:r})=>e.jsx(q,{variant:"outline",children:r.getValue("id")}),enableSorting:!0,size:60},{accessorKey:"enable",header:({column:r})=>e.jsx(O,{column:r,title:t("table.columns.enable")}),cell:({row:r})=>e.jsx(Y,{defaultChecked:r.getValue("enable"),onCheckedChange:async()=>{const{data:a}=await $c({id:r.original.id});a||s()}}),enableSorting:!1,size:100},{accessorKey:"name",header:({column:r})=>e.jsx(O,{column:r,title:t("table.columns.name")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{className:"max-w-[200px] truncate font-medium",children:r.getValue("name")})}),enableSorting:!1,size:200},{accessorKey:"payment",header:({column:r})=>e.jsx(O,{column:r,title:t("table.columns.payment")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{className:"max-w-[200px] truncate font-medium",children:r.getValue("payment")})}),enableSorting:!1,size:200},{accessorKey:"notify_url",header:({column:r})=>e.jsxs("div",{className:"flex items-center",children:[e.jsx(O,{column:r,title:t("table.columns.notify_url")}),e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{className:"ml-1",children:e.jsx(Gr,{className:"h-4 w-4"})}),e.jsx(ce,{children:t("table.columns.notify_url_tooltip")})]})})]}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{className:"max-w-[300px] truncate font-medium",children:r.getValue("notify_url")})}),enableSorting:!1,size:3e3},{id:"actions",header:({column:r})=>e.jsx(O,{className:"justify-end",column:r,title:t("table.columns.actions")}),cell:({row:r})=>e.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[e.jsx(qr,{refetch:s,dialogTrigger:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:t("table.actions.edit")})]}),type:"edit",defaultFormValues:r.original}),e.jsx(Qe,{title:t("table.actions.delete.title"),description:t("table.actions.delete.description"),onConfirm:async()=>{const{data:a}=await Ac({id:r.original.id});a&&s()},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-destructive/10",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-destructive"}),e.jsx("span",{className:"sr-only",children:t("table.actions.delete.title")})]})})]}),size:100}]};function _m({table:s,refetch:n,saveOrder:t,isSortMode:r}){const{t:a}=V("payment"),i=s.getState().columnFilters.length>0;return e.jsxs("div",{className:"flex items-center justify-between",children:[r?e.jsx("p",{className:"text-sm text-muted-foreground",children:a("table.toolbar.sort.hint")}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qr,{refetch:n}),e.jsx(T,{placeholder:a("table.toolbar.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:l=>s.getColumn("name")?.setFilterValue(l.target.value),className:"h-8 w-[250px]"}),i&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),children:[a("table.toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(P,{variant:r?"default":"outline",onClick:t,size:"sm",children:a(r?"table.toolbar.sort.save":"table.toolbar.sort.edit")})})]})}function wm(){const[s,n]=u.useState([]),[t,r]=u.useState([]),[a,i]=u.useState(!1),[l,d]=u.useState([]),[m,o]=u.useState({"drag-handle":!1}),[c,h]=u.useState({pageSize:20,pageIndex:0}),{refetch:_}=re({queryKey:["paymentList"],queryFn:async()=>{const{data:b}=await Fc();return d(b?.map(k=>({...k,enable:!!k.enable}))||[]),b}});u.useEffect(()=>{o({"drag-handle":a,actions:!a}),h({pageSize:a?99999:10,pageIndex:0})},[a]);const E=(b,k)=>{a&&(b.dataTransfer.setData("text/plain",k.toString()),b.currentTarget.classList.add("opacity-50"))},C=(b,k)=>{if(!a)return;b.preventDefault(),b.currentTarget.classList.remove("bg-muted");const p=parseInt(b.dataTransfer.getData("text/plain"));if(p===k)return;const v=[...l],[M]=v.splice(p,1);v.splice(k,0,M),d(v)},S=async()=>{a?Uc({ids:l.map(b=>b.id)}).then(()=>{_(),i(!1),A.success("排序保存成功")}):i(!0)},w=ns({data:l,columns:Nm({refetch:_,isSortMode:a}),state:{sorting:t,columnFilters:s,columnVisibility:m,pagination:c},onSortingChange:r,onColumnFiltersChange:n,onColumnVisibilityChange:o,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),initialState:{columnPinning:{right:["actions"]}},pageCount:a?1:void 0});return e.jsx(hs,{table:w,toolbar:b=>e.jsx(_m,{table:b,refetch:_,saveOrder:S,isSortMode:a}),draggable:a,onDragStart:E,onDragEnd:b=>b.currentTarget.classList.remove("opacity-50"),onDragOver:b=>{b.preventDefault(),b.currentTarget.classList.add("bg-muted")},onDragLeave:b=>b.currentTarget.classList.remove("bg-muted"),onDrop:C,showPagination:!a})}function Cm(){const{t:s}=V("payment");return e.jsxs(Ee,{children:[e.jsxs(Re,{className:"flex items-center justify-between",children:[e.jsx(Ke,{}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{children:[e.jsx("header",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("div",{className:"mb-2",children:e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")})}),e.jsx("p",{className:"text-muted-foreground",children:s("description")})]})}),e.jsx("section",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(wm,{})})]})]})}const Sm=Object.freeze(Object.defineProperty({__proto__:null,default:Cm},Symbol.toStringTag,{value:"Module"}));function km({pluginName:s,onClose:n,onSuccess:t}){const{t:r}=V("plugin"),[a,i]=u.useState(!0),[l,d]=u.useState(!1),[m,o]=u.useState(null),c=ko({config:To(Do())}),h=ge({resolver:Ne(c),defaultValues:{config:{}}});u.useEffect(()=>{(async()=>{try{const{data:S}=await _s.getPluginConfig(s);o(S),h.reset({config:Object.fromEntries(Object.entries(S).map(([w,b])=>[w,b.value]))})}catch{A.error(r("messages.configLoadError"))}finally{i(!1)}})()},[s]);const _=async C=>{d(!0);try{await _s.updatePluginConfig(s,C.config),A.success(r("messages.configSaveSuccess")),t()}catch{A.error(r("messages.configSaveError"))}finally{d(!1)}},E=(C,S)=>{switch(S.type){case"string":return e.jsx(g,{control:h.control,name:`config.${C}`,render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{children:S.label||S.description}),e.jsx(y,{children:e.jsx(T,{placeholder:S.placeholder,...w})}),S.description&&S.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.description}),e.jsx(D,{})]})},C);case"number":case"percentage":return e.jsx(g,{control:h.control,name:`config.${C}`,render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{children:S.label||S.description}),e.jsx(y,{children:e.jsxs("div",{className:"relative",children:[e.jsx(T,{type:"number",placeholder:S.placeholder,...w,onChange:b=>{const k=Number(b.target.value);S.type==="percentage"?w.onChange(Math.min(100,Math.max(0,k))):w.onChange(k)},className:S.type==="percentage"?"pr-8":"",min:S.type==="percentage"?0:void 0,max:S.type==="percentage"?100:void 0,step:S.type==="percentage"?1:void 0}),S.type==="percentage"&&e.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3",children:e.jsx(Po,{className:"h-4 w-4 text-muted-foreground"})})]})}),S.description&&S.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.description}),e.jsx(D,{})]})},C);case"select":return e.jsx(g,{control:h.control,name:`config.${C}`,render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{children:S.label||S.description}),e.jsxs(G,{onValueChange:w.onChange,defaultValue:w.value,children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:S.placeholder})})}),e.jsx(B,{children:S.options?.map(b=>e.jsx(z,{value:b.value,children:b.label},b.value))})]}),S.description&&S.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.description}),e.jsx(D,{})]})},C);case"boolean":return e.jsx(g,{control:h.control,name:`config.${C}`,render:({field:w})=>e.jsxs(f,{className:"flex flex-row items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(j,{className:"text-base",children:S.label||S.description}),S.description&&S.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.description})]}),e.jsx(y,{children:e.jsx(Y,{checked:w.value,onCheckedChange:w.onChange})})]})},C);case"text":return e.jsx(g,{control:h.control,name:`config.${C}`,render:({field:w})=>e.jsxs(f,{children:[e.jsx(j,{children:S.label||S.description}),e.jsx(y,{children:e.jsx(ys,{placeholder:S.placeholder,...w})}),S.description&&S.label&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.description}),e.jsx(D,{})]})},C);default:return null}};return a?e.jsxs("div",{className:"space-y-4",children:[e.jsx(oe,{className:"h-4 w-[200px]"}),e.jsx(oe,{className:"h-10 w-full"}),e.jsx(oe,{className:"h-4 w-[200px]"}),e.jsx(oe,{className:"h-10 w-full"})]}):e.jsx(_e,{...h,children:e.jsxs("form",{onSubmit:h.handleSubmit(_),className:"space-y-4",children:[m&&Object.entries(m).map(([C,S])=>E(C,S)),e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(P,{type:"button",variant:"outline",onClick:n,disabled:l,children:r("config.cancel")}),e.jsx(P,{type:"submit",loading:l,disabled:l,children:r("config.save")})]})]})})}function Tm(){const{t:s}=V("plugin"),[n,t]=u.useState(null),[r,a]=u.useState(!1),[i,l]=u.useState(null),[d,m]=u.useState(""),[o,c]=u.useState("all"),[h,_]=u.useState(!1),[E,C]=u.useState(!1),[S,w]=u.useState(!1),b=u.useRef(null),{data:k,isLoading:p,refetch:v}=re({queryKey:["pluginList"],queryFn:async()=>{const{data:R}=await _s.getPluginList();return R}});k&&[...new Set(k.map(R=>R.category||"other"))];const M=k?.filter(R=>{const X=R.name.toLowerCase().includes(d.toLowerCase())||R.description.toLowerCase().includes(d.toLowerCase())||R.code.toLowerCase().includes(d.toLowerCase()),Ns=o==="all"||R.category===o;return X&&Ns}),H=async R=>{t(R),_s.installPlugin(R).then(()=>{A.success(s("messages.installSuccess")),v()}).catch(X=>{A.error(X.message||s("messages.installError"))}).finally(()=>{t(null)})},se=async R=>{t(R),_s.uninstallPlugin(R).then(()=>{A.success(s("messages.uninstallSuccess")),v()}).catch(X=>{A.error(X.message||s("messages.uninstallError"))}).finally(()=>{t(null)})},L=async(R,X)=>{t(R),(X?_s.disablePlugin:_s.enablePlugin)(R).then(()=>{A.success(s(X?"messages.disableSuccess":"messages.enableSuccess")),v()}).catch(De=>{A.error(De.message||s(X?"messages.disableError":"messages.enableError"))}).finally(()=>{t(null)})},Z=R=>{k?.find(X=>X.code===R),l(R),a(!0)},de=async R=>{if(!R.name.endsWith(".zip")){A.error(s("upload.error.format"));return}_(!0),_s.uploadPlugin(R).then(()=>{A.success(s("messages.uploadSuccess")),C(!1),v()}).catch(X=>{A.error(X.message||s("messages.uploadError"))}).finally(()=>{_(!1),b.current&&(b.current.value="")})},Q=R=>{R.preventDefault(),R.stopPropagation(),R.type==="dragenter"||R.type==="dragover"?w(!0):R.type==="dragleave"&&w(!1)},te=R=>{R.preventDefault(),R.stopPropagation(),w(!1),R.dataTransfer.files&&R.dataTransfer.files[0]&&de(R.dataTransfer.files[0])},$=async R=>{t(R),_s.deletePlugin(R).then(()=>{A.success(s("messages.deleteSuccess")),v()}).catch(X=>{A.error(X.message||s("messages.deleteError"))}).finally(()=>{t(null)})};return e.jsxs(Ee,{children:[e.jsxs(Re,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(ka,{className:"h-6 w-6"}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:s("title")})]}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{children:[e.jsxs("div",{className:"mb-8 space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(An,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(T,{placeholder:s("search.placeholder"),value:d,onChange:R=>m(R.target.value),className:"pl-9"})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(P,{onClick:()=>C(!0),variant:"outline",className:"shrink-0",size:"sm",children:[e.jsx(pt,{className:"mr-2 h-4 w-4"}),s("upload.button")]})})]}),e.jsxs(Gt,{defaultValue:"all",className:"w-full",children:[e.jsxs(vt,{children:[e.jsx(Ge,{value:"all",children:s("tabs.all")}),e.jsx(Ge,{value:"installed",children:s("tabs.installed")}),e.jsx(Ge,{value:"available",children:s("tabs.available")})]}),e.jsx(ws,{value:"all",className:"mt-6",children:e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[e.jsx(oa,{}),e.jsx(oa,{}),e.jsx(oa,{})]}):M?.map(R=>e.jsx(ia,{plugin:R,onInstall:H,onUninstall:se,onToggleEnable:L,onOpenConfig:Z,onDelete:$,isLoading:n===R.name},R.name))})}),e.jsx(ws,{value:"installed",className:"mt-6",children:e.jsx("div",{className:"space-y-4",children:M?.filter(R=>R.is_installed).map(R=>e.jsx(ia,{plugin:R,onInstall:H,onUninstall:se,onToggleEnable:L,onOpenConfig:Z,onDelete:$,isLoading:n===R.name},R.name))})}),e.jsx(ws,{value:"available",className:"mt-6",children:e.jsx("div",{className:"space-y-4",children:M?.filter(R=>!R.is_installed).map(R=>e.jsx(ia,{plugin:R,onInstall:H,onUninstall:se,onToggleEnable:L,onOpenConfig:Z,onDelete:$,isLoading:n===R.name},R.code))})})]})]}),e.jsx(be,{open:r,onOpenChange:a,children:e.jsxs(fe,{className:"sm:max-w-lg",children:[e.jsxs(Ce,{children:[e.jsxs(ye,{children:[k?.find(R=>R.code===i)?.name," ",s("config.title")]}),e.jsx(Te,{children:s("config.description")})]}),i&&e.jsx(km,{pluginName:i,onClose:()=>a(!1),onSuccess:()=>{a(!1),v()}})]})}),e.jsx(be,{open:E,onOpenChange:C,children:e.jsxs(fe,{className:"sm:max-w-md",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:s("upload.title")}),e.jsx(Te,{children:s("upload.description")})]}),e.jsxs("div",{className:N("relative mt-4 flex h-64 flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 px-5 py-10 text-center transition-colors",S&&"border-primary/50 bg-muted/50"),onDragEnter:Q,onDragLeave:Q,onDragOver:Q,onDrop:te,children:[e.jsx("input",{type:"file",ref:b,className:"hidden",accept:".zip",onChange:R=>{const X=R.target.files?.[0];X&&de(X)}}),h?e.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-b-2 border-primary"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s("upload.uploading")})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[e.jsx("div",{className:"rounded-full border-2 border-muted-foreground/25 p-3",children:e.jsx(pt,{className:"h-6 w-6 text-muted-foreground/50"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[s("upload.dragText")," ",e.jsx("button",{type:"button",onClick:()=>b.current?.click(),className:"mx-1 text-primary hover:underline",children:s("upload.clickText")})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("upload.supportText")})]})]})})]})]})})]})]})}function ia({plugin:s,onInstall:n,onUninstall:t,onToggleEnable:r,onOpenConfig:a,onDelete:i,isLoading:l}){const{t:d}=V("plugin");return e.jsxs(We,{className:"group relative overflow-hidden transition-all hover:shadow-md",children:[e.jsxs(ts,{children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cs,{children:s.name}),s.is_installed&&e.jsx(q,{variant:s.is_enabled?"success":"secondary",children:s.is_enabled?d("status.enabled"):d("status.disabled")})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-4 w-4"}),e.jsx("code",{className:"rounded bg-muted px-1 py-0.5",children:s.code})]}),e.jsxs("div",{children:["v",s.version]})]})]})}),e.jsx(et,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"mt-2",children:s.description}),e.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:e.jsxs("div",{className:"flex items-center gap-1",children:[d("author"),": ",s.author]})})]})})]}),e.jsx(as,{children:e.jsx("div",{className:"flex items-center justify-end space-x-2",children:s.is_installed?e.jsxs(e.Fragment,{children:[e.jsxs(P,{variant:"outline",size:"sm",onClick:()=>a(s.code),disabled:!s.is_enabled||l,children:[e.jsx(Eo,{className:"mr-2 h-4 w-4"}),d("button.config")]}),e.jsxs(P,{variant:s.is_enabled?"destructive":"default",size:"sm",onClick:()=>r(s.code,s.is_enabled),disabled:l,children:[e.jsx(Ro,{className:"mr-2 h-4 w-4"}),s.is_enabled?d("button.disable"):d("button.enable")]}),e.jsx(Qe,{title:d("uninstall.title"),description:d("uninstall.description"),cancelText:d("common:cancel"),confirmText:d("uninstall.button"),variant:"destructive",onConfirm:()=>t(s.code),children:e.jsxs(P,{variant:"outline",size:"sm",className:"text-muted-foreground hover:text-destructive",disabled:l,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),d("button.uninstall")]})})]}):e.jsxs(e.Fragment,{children:[e.jsx(P,{onClick:()=>n(s.code),disabled:l,loading:l,children:d("button.install")}),e.jsx(Qe,{title:d("delete.title"),description:d("delete.description"),cancelText:d("common:cancel"),confirmText:d("delete.button"),variant:"destructive",onConfirm:()=>i(s.code),children:e.jsx(P,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",disabled:l,children:e.jsx(cs,{className:"h-4 w-4"})})})]})})})]})}function oa(){return e.jsxs(We,{children:[e.jsxs(ts,{children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"h-6 w-[200px]"}),e.jsx(oe,{className:"h-6 w-[80px]"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(oe,{className:"h-5 w-[120px]"}),e.jsx(oe,{className:"h-5 w-[60px]"})]})]})}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(oe,{className:"h-4 w-[300px]"}),e.jsx(oe,{className:"h-4 w-[150px]"})]})]}),e.jsx(as,{children:e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(oe,{className:"h-9 w-[100px]"}),e.jsx(oe,{className:"h-9 w-[100px]"}),e.jsx(oe,{className:"h-8 w-8"})]})})]})}const Dm=Object.freeze(Object.defineProperty({__proto__:null,default:Tm},Symbol.toStringTag,{value:"Module"})),Pm=(s,n)=>{let t=null;switch(s.field_type){case"input":t=e.jsx(T,{placeholder:s.placeholder,...n});break;case"textarea":t=e.jsx(ys,{placeholder:s.placeholder,...n});break;case"select":t=e.jsx("select",{className:N(st({variant:"outline"}),"w-full appearance-none font-normal"),...n,children:s.select_options&&Object.keys(s.select_options).map(r=>e.jsx("option",{value:r,children:s.select_options?.[r]},r))});break;default:t=null;break}return t};function Em({themeKey:s,themeInfo:n}){const{t}=V("theme"),[r,a]=u.useState(!1),[i,l]=u.useState(!1),[d,m]=u.useState(!1),o=ge({defaultValues:n.configs.reduce((_,E)=>(_[E.field_name]="",_),{})}),c=async()=>{l(!0),Nc(s).then(({data:_})=>{Object.entries(_).forEach(([E,C])=>{o.setValue(E,C)})}).finally(()=>{l(!1)})},h=async _=>{m(!0),_c(s,_).then(()=>{A.success(t("config.success")),a(!1)}).finally(()=>{m(!1)})};return e.jsxs(be,{open:r,onOpenChange:_=>{a(_),_?c():o.reset()},children:[e.jsx(Je,{asChild:!0,children:e.jsx(P,{variant:"outline",children:t("card.configureTheme")})}),e.jsxs(fe,{className:"max-h-[90vh] overflow-auto sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:t("config.title",{name:n.name})}),e.jsx(Te,{children:t("config.description")})]}),i?e.jsx("div",{className:"flex h-40 items-center justify-center",children:e.jsx(Da,{className:"h-6 w-6 animate-spin"})}):e.jsx(_e,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(h),className:"space-y-4",children:[n.configs.map(_=>e.jsx(g,{control:o.control,name:_.field_name,render:({field:E})=>e.jsxs(f,{children:[e.jsx(j,{children:_.label}),e.jsx(y,{children:Pm(_,E)}),e.jsx(D,{})]})},_.field_name)),e.jsxs(ze,{className:"mt-6 gap-2",children:[e.jsx(P,{type:"button",variant:"secondary",onClick:()=>a(!1),children:t("config.cancel")}),e.jsx(P,{type:"submit",loading:d,children:t("config.save")})]})]})})]})]})}function Rm(){const{t:s}=V("theme"),[n,t]=u.useState(null),[r,a]=u.useState(!1),[i,l]=u.useState(!1),[d,m]=u.useState(!1),[o,c]=u.useState(null),h=u.useRef(null),[_,E]=u.useState(0),{data:C,isLoading:S,refetch:w}=re({queryKey:["themeList"],queryFn:async()=>{const{data:L}=await yc();return L}}),b=async L=>{t(L),Sc({frontend_theme:L}).then(()=>{A.success("主题切换成功"),w()}).finally(()=>{t(null)})},k=async L=>{if(!L.name.endsWith(".zip")){A.error(s("upload.error.format"));return}a(!0),wc(L).then(()=>{A.success("主题上传成功"),l(!1),w()}).finally(()=>{a(!1),h.current&&(h.current.value="")})},p=L=>{L.preventDefault(),L.stopPropagation(),L.type==="dragenter"||L.type==="dragover"?m(!0):L.type==="dragleave"&&m(!1)},v=L=>{L.preventDefault(),L.stopPropagation(),m(!1),L.dataTransfer.files&&L.dataTransfer.files[0]&&k(L.dataTransfer.files[0])},M=()=>{o&&E(L=>L===0?o.images.length-1:L-1)},H=()=>{o&&E(L=>L===o.images.length-1?0:L+1)},se=(L,Z)=>{E(0),c({name:L,images:Z})};return e.jsxs(Ee,{children:[e.jsxs(Re,{className:"flex items-center justify-between",children:[e.jsx(Ke,{}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"",children:[e.jsxs("header",{className:"mb-8",children:[e.jsx("div",{className:"mb-2",children:e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:s("title")})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-muted-foreground",children:s("description")}),e.jsxs(P,{onClick:()=>l(!0),variant:"outline",className:"ml-4 shrink-0",size:"sm",children:[e.jsx(pt,{className:"mr-2 h-4 w-4"}),s("upload.button")]})]})]}),e.jsx("section",{className:"grid gap-6 md:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3",children:S?e.jsxs(e.Fragment,{children:[e.jsx(cn,{}),e.jsx(cn,{})]}):C?.themes&&Object.entries(C.themes).map(([L,Z])=>e.jsx(We,{className:"group relative overflow-hidden transition-all hover:shadow-md",style:{backgroundImage:Z.background_url?`url(${Z.background_url})`:"none",backgroundSize:"cover",backgroundPosition:"center"},children:e.jsxs("div",{className:N("relative z-10 h-full transition-colors",Z.background_url?"group-hover:from-background/98 bg-gradient-to-t from-background/95 via-background/80 to-background/60 backdrop-blur-[1px] group-hover:via-background/90 group-hover:to-background/70":"bg-background"),children:[!!Z.can_delete&&e.jsx("div",{className:"absolute right-2 top-2",children:e.jsx(Qe,{title:s("card.delete.title"),description:s("card.delete.description"),confirmText:s("card.delete.button"),variant:"destructive",onConfirm:async()=>{if(L===C?.active){A.error(s("card.delete.error.active"));return}t(L),Cc(L).then(()=>{A.success("主题删除成功"),w()}).finally(()=>{t(null)})},children:e.jsx(P,{disabled:n===L,loading:n===L,variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",children:e.jsx(cs,{className:"h-4 w-4"})})})}),e.jsxs(ts,{children:[e.jsx(Cs,{children:Z.name}),e.jsx(et,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{children:Z.description}),Z.version&&e.jsx("div",{className:"text-sm text-muted-foreground",children:s("card.version",{version:Z.version})})]})})]}),e.jsxs(as,{className:"flex items-center justify-end space-x-3",children:[Z.images&&Array.isArray(Z.images)&&Z.images.length>0&&e.jsx(P,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>se(Z.name,Z.images),children:e.jsx(Io,{className:"h-4 w-4"})}),e.jsx(Em,{themeKey:L,themeInfo:Z}),e.jsx(P,{onClick:()=>b(L),disabled:n===L||L===C.active,loading:n===L,variant:L===C.active?"secondary":"default",children:L===C.active?s("card.currentTheme"):s("card.activateTheme")})]})]})},L))}),e.jsx(be,{open:i,onOpenChange:l,children:e.jsxs(fe,{className:"sm:max-w-md",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:s("upload.title")}),e.jsx(Te,{children:s("upload.description")})]}),e.jsxs("div",{className:N("relative mt-4 flex h-64 flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 px-5 py-10 text-center transition-colors",d&&"border-primary/50 bg-muted/50"),onDragEnter:p,onDragLeave:p,onDragOver:p,onDrop:v,children:[e.jsx("input",{type:"file",ref:h,className:"hidden",accept:".zip",onChange:L=>{const Z=L.target.files?.[0];Z&&k(Z)}}),r?e.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-b-2 border-primary"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:s("upload.uploading")})]}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[e.jsx("div",{className:"rounded-full border-2 border-muted-foreground/25 p-3",children:e.jsx(pt,{className:"h-6 w-6 text-muted-foreground/50"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[s("upload.dragText")," ",e.jsx("button",{type:"button",onClick:()=>h.current?.click(),className:"mx-1 text-primary hover:underline",children:s("upload.clickText")})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("upload.supportText")})]})]})})]})]})}),e.jsx(be,{open:!!o,onOpenChange:L=>{L||(c(null),E(0))},children:e.jsxs(fe,{className:"max-w-4xl",children:[e.jsxs(Ce,{children:[e.jsxs(ye,{children:[o?.name," ",s("preview.title")]}),e.jsx(Te,{className:"text-center",children:o&&s("preview.imageCount",{current:_+1,total:o.images.length})})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[16/9] overflow-hidden rounded-lg border bg-muted",children:o?.images[_]&&e.jsx("img",{src:o.images[_],alt:`${o.name} 预览图 ${_+1}`,className:"h-full w-full object-contain"})}),o&&o.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"outline",size:"icon",className:"absolute left-4 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full bg-background/80 hover:bg-background",onClick:M,children:e.jsx(Vo,{className:"h-4 w-4"})}),e.jsx(P,{variant:"outline",size:"icon",className:"absolute right-4 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full bg-background/80 hover:bg-background",onClick:H,children:e.jsx(Mo,{className:"h-4 w-4"})})]})]}),o&&o.images.length>1&&e.jsx("div",{className:"mt-4 flex gap-2 overflow-x-auto pb-2",children:o.images.map((L,Z)=>e.jsx("button",{onClick:()=>E(Z),className:N("relative h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border-2",_===Z?"border-primary":"border-transparent"),children:e.jsx("img",{src:L,alt:`缩略图 ${Z+1}`,className:"h-full w-full object-cover"})},Z))})]})})]})]})}function cn(){return e.jsxs(We,{children:[e.jsxs(ts,{children:[e.jsx(oe,{className:"h-6 w-[200px]"}),e.jsx(oe,{className:"h-4 w-[300px]"})]}),e.jsxs(as,{className:"flex items-center justify-end space-x-3",children:[e.jsx(oe,{className:"h-10 w-[100px]"}),e.jsx(oe,{className:"h-10 w-[100px]"})]})]})}const Im=Object.freeze(Object.defineProperty({__proto__:null,default:Rm},Symbol.toStringTag,{value:"Module"})),La=u.forwardRef(({className:s,value:n,onChange:t,...r},a)=>{const[i,l]=u.useState("");u.useEffect(()=>{if(i.includes(",")){const m=new Set([...n,...i.split(",").map(o=>o.trim())]);t(Array.from(m)),l("")}},[i,t,n]);const d=()=>{if(i){const m=new Set([...n,i]);t(Array.from(m)),l("")}};return e.jsxs("div",{className:N(" has-[:focus-visible]:outline-none has-[:focus-visible]:ring-1 has-[:focus-visible]:ring-neutral-950 dark:has-[:focus-visible]:ring-neutral-300 flex w-full flex-wrap gap-2 rounded-md border border-input shadow-sm px-3 py-2 text-sm ring-offset-white disabled:cursor-not-allowed disabled:opacity-50",s),children:[n.map(m=>e.jsxs(q,{variant:"secondary",children:[m,e.jsx(J,{variant:"ghost",size:"icon",className:"ml-2 h-3 w-3",onClick:()=>{t(n.filter(o=>o!==m))},children:e.jsx(ga,{className:"w-3"})})]},m)),e.jsx("input",{className:"flex-1 outline-none placeholder:text-muted-foreground bg-transparent",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>{m.key==="Enter"||m.key===","?(m.preventDefault(),d()):m.key==="Backspace"&&i.length===0&&n.length>0&&(m.preventDefault(),t(n.slice(0,-1)))},...r,ref:a})]})});La.displayName="InputTags";const Vm=x.object({id:x.number().nullable(),title:x.string().min(1).max(250),content:x.string().min(1),show:x.boolean(),tags:x.array(x.string()),img_url:x.string().nullable()}),Mm={id:null,show:!1,tags:[],img_url:"",title:"",content:""};function Wr({refetch:s,dialogTrigger:n,type:t="add",defaultFormValues:r=Mm}){const{t:a}=V("notice"),[i,l]=u.useState(!1),d=ge({resolver:Ne(Vm),defaultValues:r,mode:"onChange",shouldFocusError:!0}),m=new Pa({html:!0});return e.jsx(_e,{...d,children:e.jsxs(be,{onOpenChange:l,open:i,children:[e.jsx(Je,{asChild:!0,children:n||e.jsxs(P,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Ve,{icon:"ion:add"})," ",e.jsx("div",{children:a("form.add.button")})]})}),e.jsxs(fe,{className:"sm:max-w-[1025px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:a(t==="add"?"form.add.title":"form.edit.title")}),e.jsx(Te,{})]}),e.jsx(g,{control:d.control,name:"title",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.title.label")}),e.jsx("div",{className:"relative ",children:e.jsx(y,{children:e.jsx(T,{placeholder:a("form.fields.title.placeholder"),...o})})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"content",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.content.label")}),e.jsx(y,{children:e.jsx(Ea,{style:{height:"500px"},value:o.value,renderHTML:c=>m.render(c),onChange:({text:c})=>{o.onChange(c)}})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"img_url",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.img_url.label")}),e.jsx("div",{className:"relative",children:e.jsx(y,{children:e.jsx(T,{type:"text",placeholder:a("form.fields.img_url.placeholder"),...o,value:o.value||""})})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"show",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.show.label")}),e.jsx("div",{className:"relative py-2",children:e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:o.onChange})})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"tags",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.fields.tags.label")}),e.jsx(y,{children:e.jsx(La,{value:o.value,onChange:o.onChange,placeholder:a("form.fields.tags.placeholder"),className:"w-full"})}),e.jsx(D,{})]})}),e.jsxs(ze,{children:[e.jsx(yt,{asChild:!0,children:e.jsx(P,{type:"button",variant:"outline",children:a("form.buttons.cancel")})}),e.jsx(P,{type:"submit",onClick:o=>{o.preventDefault(),d.handleSubmit(async c=>{Hc(c).then(({data:h})=>{h&&(A.success(a("form.buttons.success")),s(),l(!1))})})()},children:a("form.buttons.submit")})]})]})]})})}function Fm({table:s,refetch:n,saveOrder:t,isSortMode:r}){const{t:a}=V("notice"),i=s.getState().columnFilters.length>0;return e.jsxs("div",{className:"flex items-center justify-between space-x-2 ",children:[e.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[!r&&e.jsx(Wr,{refetch:n}),!r&&e.jsx(T,{placeholder:a("table.toolbar.search"),value:s.getColumn("title")?.getFilterValue()??"",onChange:l=>s.getColumn("title")?.setFilterValue(l.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),i&&!r&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-9 px-2 lg:px-3",children:[a("table.toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(P,{variant:r?"default":"outline",onClick:t,className:"h-8",size:"sm",children:a(r?"table.toolbar.sort.save":"table.toolbar.sort.edit")})})]})}const Om=s=>{const{t:n}=V("notice");return[{id:"drag-handle",header:"",cell:()=>e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground cursor-move"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.id")}),cell:({row:t})=>e.jsx(q,{variant:"outline",className:"font-mono",children:t.getValue("id")}),enableSorting:!0,size:60},{accessorKey:"show",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.show")}),cell:({row:t})=>e.jsx("div",{className:"flex items-center",children:e.jsx(Y,{defaultChecked:t.getValue("show"),onCheckedChange:async()=>{const{data:r}=await Kc({id:t.original.id});r||s()}})}),enableSorting:!1,size:100},{accessorKey:"title",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.title")}),cell:({row:t})=>e.jsx("div",{className:"flex max-w-[500px] items-center",children:e.jsx("span",{className:"truncate font-medium",children:t.getValue("title")})}),enableSorting:!1,size:6e3},{id:"actions",header:({column:t})=>e.jsx(O,{className:"justify-end",column:t,title:n("table.columns.actions")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[e.jsx(Wr,{refetch:s,dialogTrigger:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("table.actions.edit")})]}),type:"edit",defaultFormValues:t.original}),e.jsx(Qe,{title:n("table.actions.delete.title"),description:n("table.actions.delete.description"),onConfirm:async()=>{qc({id:t.original.id}).then(()=>{A.success(n("table.actions.delete.success")),s()})},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("table.actions.delete.title")})]})})]}),size:100}]};function Lm(){const[s,n]=u.useState({}),[t,r]=u.useState({}),[a,i]=u.useState([]),[l,d]=u.useState([]),[m,o]=u.useState(!1),[c,h]=u.useState({}),[_,E]=u.useState({pageSize:50,pageIndex:0}),[C,S]=u.useState([]),{refetch:w}=re({queryKey:["notices"],queryFn:async()=>{const{data:M}=await nn.getList();return S(M),M}});u.useEffect(()=>{r({"drag-handle":m,content:!m,created_at:!m,actions:!m}),E({pageSize:m?99999:50,pageIndex:0})},[m]);const b=(M,H)=>{m&&(M.dataTransfer.setData("text/plain",H.toString()),M.currentTarget.classList.add("opacity-50"))},k=(M,H)=>{if(!m)return;M.preventDefault(),M.currentTarget.classList.remove("bg-muted");const se=parseInt(M.dataTransfer.getData("text/plain"));if(se===H)return;const L=[...C],[Z]=L.splice(se,1);L.splice(H,0,Z),S(L)},p=async()=>{if(!m){o(!0);return}nn.sort(C.map(M=>M.id)).then(()=>{A.success("排序保存成功"),o(!1),w()}).finally(()=>{o(!1)})},v=ns({data:C??[],columns:Om(w),state:{sorting:l,columnVisibility:t,rowSelection:s,columnFilters:a,columnSizing:c,pagination:_},enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:d,onColumnFiltersChange:i,onColumnVisibilityChange:r,onColumnSizingChange:h,onPaginationChange:E,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx("div",{className:"space-y-4",children:e.jsx(hs,{table:v,toolbar:M=>e.jsx(Fm,{table:M,refetch:w,saveOrder:p,isSortMode:m}),draggable:m,onDragStart:b,onDragEnd:M=>M.currentTarget.classList.remove("opacity-50"),onDragOver:M=>{M.preventDefault(),M.currentTarget.classList.add("bg-muted")},onDragLeave:M=>M.currentTarget.classList.remove("bg-muted"),onDrop:k,showPagination:!m})})}function zm(){const{t:s}=V("notice");return e.jsxs(Ee,{children:[e.jsxs(Re,{className:"flex items-center justify-between",children:[e.jsx(Ke,{}),e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("div",{className:"mb-2",children:e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")})}),e.jsx("p",{className:"text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Lm,{})})]})]})}const Am=Object.freeze(Object.defineProperty({__proto__:null,default:zm},Symbol.toStringTag,{value:"Module"})),$m=x.object({id:x.number().nullable(),language:x.string().max(250),category:x.string().max(250),title:x.string().min(1).max(250),body:x.string().min(1),show:x.boolean()}),Um={id:null,language:"zh-CN",category:"",title:"",body:"",show:!1};function Yr({refreshData:s,dialogTrigger:n,type:t="add",defaultFormValues:r=Um}){const{t:a}=V("knowledge"),[i,l]=u.useState(!1),d=ge({resolver:Ne($m),defaultValues:r,mode:"onChange",shouldFocusError:!0}),m=new Pa({html:!0});return u.useEffect(()=>{i&&r.id&&Gc(r.id).then(({data:o})=>{d.reset(o)})},[r.id,d,i]),e.jsxs(be,{onOpenChange:l,open:i,children:[e.jsx(Je,{asChild:!0,children:n||e.jsxs(P,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Ve,{icon:"ion:add"})," ",e.jsx("div",{children:a("form.add")})]})}),e.jsxs(fe,{className:"sm:max-w-[1025px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:a(t==="add"?"form.add":"form.edit")}),e.jsx(Te,{})]}),e.jsxs(_e,{...d,children:[e.jsx(g,{control:d.control,name:"title",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.title")}),e.jsx("div",{className:"relative ",children:e.jsx(y,{children:e.jsx(T,{placeholder:a("form.titlePlaceholder"),...o})})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"category",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.category")}),e.jsx("div",{className:"relative ",children:e.jsx(y,{children:e.jsx(T,{placeholder:a("form.categoryPlaceholder"),...o})})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"language",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.language")}),e.jsx(y,{children:e.jsxs(G,{value:o.value,onValueChange:o.onChange,children:[e.jsx(K,{children:e.jsx(W,{placeholder:a("form.languagePlaceholder")})}),e.jsx(B,{children:[{value:"en-US"},{value:"ja-JP"},{value:"ko-KR"},{value:"vi-VN"},{value:"zh-CN"},{value:"zh-TW"}].map(c=>e.jsx(z,{value:c.value,className:"cursor-pointer",children:a(`languages.${c.value}`)},c.value))})]})})]})}),e.jsx(g,{control:d.control,name:"body",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.content")}),e.jsx(y,{children:e.jsx(Ea,{style:{height:"500px"},value:o.value,renderHTML:c=>m.render(c),onChange:({text:c})=>{o.onChange(c)}})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"show",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.show")}),e.jsx("div",{className:"relative py-2",children:e.jsx(y,{children:e.jsx(Y,{checked:o.value,onCheckedChange:o.onChange})})}),e.jsx(D,{})]})}),e.jsxs(ze,{children:[e.jsx(yt,{asChild:!0,children:e.jsx(P,{type:"button",variant:"outline",children:a("form.cancel")})}),e.jsx(P,{type:"submit",onClick:()=>{d.handleSubmit(o=>{Wc(o).then(({data:c})=>{c&&(d.reset(),A.success(a("messages.operationSuccess")),l(!1),s())})})()},children:a("form.submit")})]})]})]})]})}function Hm({column:s,title:n,options:t}){const r=s?.getFacetedUniqueValues(),a=new Set(s?.getFilterValue());return e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),n,a?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:a.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:a.size>2?e.jsxs(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[a.size," selected"]}):t.filter(i=>a.has(i.value)).map(i=>e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:i.label},i.value))})]})]})}),e.jsx(xs,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Ms,{children:[e.jsx(Ks,{placeholder:n}),e.jsxs(Fs,{children:[e.jsx(Bs,{children:"No results found."}),e.jsx(Ye,{children:t.map(i=>{const l=a.has(i.value);return e.jsxs(Me,{onSelect:()=>{l?a.delete(i.value):a.add(i.value);const d=Array.from(a);s?.setFilterValue(d.length?d:void 0)},children:[e.jsx("div",{className:N("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",l?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx($s,{className:N("h-4 w-4")})}),i.icon&&e.jsx(i.icon,{className:"mr-2 h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:i.label}),r?.get(i.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(i.value)})]},i.value)})}),a.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx(Ye,{children:e.jsx(Me,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}function qm({table:s,refetch:n,saveOrder:t,isSortMode:r}){const a=s.getState().columnFilters.length>0,{t:i}=V("knowledge");return e.jsxs("div",{className:"flex items-center justify-between",children:[r?e.jsx("p",{className:"text-sm text-muted-foreground",children:i("toolbar.sortModeHint")}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yr,{refreshData:n}),e.jsx(T,{placeholder:i("toolbar.searchPlaceholder"),value:s.getColumn("title")?.getFilterValue()??"",onChange:l=>s.getColumn("title")?.setFilterValue(l.target.value),className:"h-8 w-[250px]"}),s.getColumn("category")&&e.jsx(Hm,{column:s.getColumn("category"),title:i("columns.category"),options:Array.from(new Set(s.getCoreRowModel().rows.map(l=>l.getValue("category")))).map(l=>({label:l,value:l}))}),a&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),children:[i("toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(P,{variant:r?"default":"outline",onClick:t,size:"sm",children:i(r?"toolbar.saveSort":"toolbar.editSort")})})]})}const Km=({refetch:s,isSortMode:n=!1})=>{const{t}=V("knowledge");return[{id:"drag-handle",header:()=>null,cell:()=>e.jsx("div",{className:n?"cursor-move":"opacity-0",children:e.jsx(Ht,{className:"size-4"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:r})=>e.jsx(O,{column:r,title:t("columns.id")}),cell:({row:r})=>e.jsx(q,{variant:"outline",className:"justify-center",children:r.getValue("id")}),enableSorting:!0,size:70},{accessorKey:"show",header:({column:r})=>e.jsx(O,{column:r,title:t("columns.status")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center",children:e.jsx(Y,{defaultChecked:r.getValue("show"),onCheckedChange:async()=>{Qc({id:r.original.id}).then(({data:a})=>{a||s()})}})}),enableSorting:!1,size:100},{accessorKey:"title",header:({column:r})=>e.jsx(O,{column:r,title:t("columns.title")}),cell:({row:r})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"line-clamp-2 font-medium",children:r.getValue("title")})}),enableSorting:!0,size:600},{accessorKey:"category",header:({column:r})=>e.jsx(O,{column:r,title:t("columns.category")}),cell:({row:r})=>e.jsx(q,{variant:"secondary",className:"max-w-[180px] truncate",children:r.getValue("category")}),enableSorting:!0,size:1800},{id:"actions",header:({column:r})=>e.jsx(O,{className:"justify-end",column:r,title:t("columns.actions")}),cell:({row:r})=>e.jsxs("div",{className:"flex items-center justify-end space-x-1",children:[e.jsx(Yr,{refreshData:s,dialogTrigger:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:t("form.edit")})]}),type:"edit",defaultFormValues:r.original}),e.jsx(Qe,{title:t("messages.deleteConfirm"),description:t("messages.deleteDescription"),confirmText:t("messages.deleteButton"),variant:"destructive",onConfirm:async()=>{Yc({id:r.original.id}).then(({data:a})=>{a&&(A.success(t("messages.operationSuccess")),s())})},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:t("messages.deleteButton")})]})})]}),size:100}]};function Bm(){const[s,n]=u.useState([]),[t,r]=u.useState([]),[a,i]=u.useState(!1),[l,d]=u.useState([]),[m,o]=u.useState({"drag-handle":!1}),[c,h]=u.useState({pageSize:20,pageIndex:0}),{refetch:_,isLoading:E,data:C}=re({queryKey:["knowledge"],queryFn:async()=>{const{data:p}=await Bc();return d(p||[]),p}});u.useEffect(()=>{o({"drag-handle":a,actions:!a}),h({pageSize:a?99999:10,pageIndex:0})},[a]);const S=(p,v)=>{a&&(p.dataTransfer.setData("text/plain",v.toString()),p.currentTarget.classList.add("opacity-50"))},w=(p,v)=>{if(!a)return;p.preventDefault(),p.currentTarget.classList.remove("bg-muted");const M=parseInt(p.dataTransfer.getData("text/plain"));if(M===v)return;const H=[...l],[se]=H.splice(M,1);H.splice(v,0,se),d(H)},b=async()=>{a?Jc({ids:l.map(p=>p.id)}).then(()=>{_(),i(!1),A.success("排序保存成功")}):i(!0)},k=ns({data:l,columns:Km({refetch:_,isSortMode:a}),state:{sorting:t,columnFilters:s,columnVisibility:m,pagination:c},onSortingChange:r,onColumnFiltersChange:n,onColumnVisibilityChange:o,onPaginationChange:h,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(hs,{table:k,toolbar:p=>e.jsx(qm,{table:p,refetch:_,saveOrder:b,isSortMode:a}),draggable:a,onDragStart:S,onDragEnd:p=>p.currentTarget.classList.remove("opacity-50"),onDragOver:p=>{p.preventDefault(),p.currentTarget.classList.add("bg-muted")},onDragLeave:p=>p.currentTarget.classList.remove("bg-muted"),onDrop:w,showPagination:!a})}function Gm(){const{t:s}=V("knowledge");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight mb-2",children:s("title")}),e.jsx("p",{className:"text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Bm,{})})]})]})}const Wm=Object.freeze(Object.defineProperty({__proto__:null,default:Gm},Symbol.toStringTag,{value:"Module"}));function Ym(s,n){const[t,r]=u.useState(s);return u.useEffect(()=>{const a=setTimeout(()=>r(s),n);return()=>{clearTimeout(a)}},[s,n]),t}function ca(s,n){if(s.length===0)return{};if(!n)return{"":s};const t={};return s.forEach(r=>{const a=r[n]||"";t[a]||(t[a]=[]),t[a].push(r)}),t}function Qm(s,n){const t=JSON.parse(JSON.stringify(s));for(const[r,a]of Object.entries(t))t[r]=a.filter(i=>!n.find(l=>l.value===i.value));return t}function Jm(s,n){for(const[,t]of Object.entries(s))if(t.some(r=>n.find(a=>a.value===r.value)))return!0;return!1}const Qr=u.forwardRef(({className:s,...n},t)=>Oo(a=>a.filtered.count===0)?e.jsx("div",{ref:t,className:N("py-6 text-center text-sm",s),"cmdk-empty":"",role:"presentation",...n}):null);Qr.displayName="CommandEmpty";const at=u.forwardRef(({value:s,onChange:n,placeholder:t,defaultOptions:r=[],options:a,delay:i,onSearch:l,loadingIndicator:d,emptyIndicator:m,maxSelected:o=Number.MAX_SAFE_INTEGER,onMaxSelected:c,hidePlaceholderWhenSelected:h,disabled:_,groupBy:E,className:C,badgeClassName:S,selectFirstItem:w=!0,creatable:b=!1,triggerSearchOnFocus:k=!1,commandProps:p,inputProps:v,hideClearAllButton:M=!1},H)=>{const se=u.useRef(null),[L,Z]=u.useState(!1),de=u.useRef(!1),[Q,te]=u.useState(!1),[$,R]=u.useState(s||[]),[X,Ns]=u.useState(ca(r,E)),[De,le]=u.useState(""),Os=Ym(De,i||500);u.useImperativeHandle(H,()=>({selectedValue:[...$],input:se.current,focus:()=>se.current?.focus()}),[$]);const Ws=u.useCallback(ee=>{const ue=$.filter(Ue=>Ue.value!==ee.value);R(ue),n?.(ue)},[n,$]),bl=u.useCallback(ee=>{const ue=se.current;ue&&((ee.key==="Delete"||ee.key==="Backspace")&&ue.value===""&&$.length>0&&($[$.length-1].fixed||Ws($[$.length-1])),ee.key==="Escape"&&ue.blur())},[Ws,$]);u.useEffect(()=>{s&&R(s)},[s]),u.useEffect(()=>{if(!a||l)return;const ee=ca(a||[],E);JSON.stringify(ee)!==JSON.stringify(X)&&Ns(ee)},[r,a,E,l,X]),u.useEffect(()=>{const ee=async()=>{te(!0);const Ue=await l?.(Os);Ns(ca(Ue||[],E)),te(!1)};(async()=>{!l||!L||(k&&await ee(),Os&&await ee())})()},[Os,E,L,k]);const yl=()=>{if(!b||Jm(X,[{value:De,label:De}])||$.find(ue=>ue.value===De))return;const ee=e.jsx(Me,{value:De,className:"cursor-pointer",onMouseDown:ue=>{ue.preventDefault(),ue.stopPropagation()},onSelect:ue=>{if($.length>=o){c?.($.length);return}le("");const Ue=[...$,{value:ue,label:ue}];R(Ue),n?.(Ue)},children:`Create "${De}"`});if(!l&&De.length>0||l&&Os.length>0&&!Q)return ee},Nl=u.useCallback(()=>{if(m)return l&&!b&&Object.keys(X).length===0?e.jsx(Me,{value:"-",disabled:!0,children:m}):e.jsx(Qr,{children:m})},[b,m,l,X]),_l=u.useMemo(()=>Qm(X,$),[X,$]),wl=u.useCallback(()=>{if(p?.filter)return p.filter;if(b)return(ee,ue)=>ee.toLowerCase().includes(ue.toLowerCase())?1:-1},[b,p?.filter]),Cl=u.useCallback(()=>{const ee=$.filter(ue=>ue.fixed);R(ee),n?.(ee)},[n,$]);return e.jsxs(Ms,{...p,onKeyDown:ee=>{bl(ee),p?.onKeyDown?.(ee)},className:N("h-auto overflow-visible bg-transparent",p?.className),shouldFilter:p?.shouldFilter!==void 0?p.shouldFilter:!l,filter:wl(),children:[e.jsx("div",{className:N("rounded-md border border-input text-sm ring-offset-background focus-within:ring-1 focus-within:ring-ring ",{"px-3 py-2":$.length!==0,"cursor-text":!_&&$.length!==0},C),onClick:()=>{_||se.current?.focus()},children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[$.map(ee=>e.jsxs(q,{className:N("data-[disabled]:bg-muted-foreground data-[disabled]:text-muted data-[disabled]:hover:bg-muted-foreground","data-[fixed]:bg-muted-foreground data-[fixed]:text-muted data-[fixed]:hover:bg-muted-foreground",S),"data-fixed":ee.fixed,"data-disabled":_||void 0,children:[ee.label,e.jsx("button",{className:N("ml-1 rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",(_||ee.fixed)&&"hidden"),onKeyDown:ue=>{ue.key==="Enter"&&Ws(ee)},onMouseDown:ue=>{ue.preventDefault(),ue.stopPropagation()},onClick:()=>Ws(ee),children:e.jsx(ga,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},ee.value)),e.jsx(Le.Input,{...v,ref:se,value:De,disabled:_,onValueChange:ee=>{le(ee),v?.onValueChange?.(ee)},onBlur:ee=>{de.current===!1&&Z(!1),v?.onBlur?.(ee)},onFocus:ee=>{Z(!0),k&&l?.(Os),v?.onFocus?.(ee)},placeholder:h&&$.length!==0?"":t,className:N("flex-1 bg-transparent outline-none placeholder:text-muted-foreground",{"w-full":h,"px-3 py-2":$.length===0,"ml-1":$.length!==0},v?.className)}),e.jsx("button",{type:"button",onClick:Cl,className:N((M||_||$.length<1||$.filter(ee=>ee.fixed).length===$.length)&&"hidden"),children:e.jsx(ga,{})})]})}),e.jsx("div",{className:"relative",children:L&&e.jsx(Fs,{className:"absolute top-1 z-10 w-full rounded-md border bg-popover text-popover-foreground shadow-md outline-none animate-in",onMouseLeave:()=>{de.current=!1},onMouseEnter:()=>{de.current=!0},onMouseUp:()=>{se.current?.focus()},children:Q?e.jsx(e.Fragment,{children:d}):e.jsxs(e.Fragment,{children:[Nl(),yl(),!w&&e.jsx(Me,{value:"-",className:"hidden"}),Object.entries(_l).map(([ee,ue])=>e.jsx(Ye,{heading:ee,className:"h-full overflow-auto",children:e.jsx(e.Fragment,{children:ue.map(Ue=>e.jsx(Me,{value:Ue.value,disabled:Ue.disable,onMouseDown:lt=>{lt.preventDefault(),lt.stopPropagation()},onSelect:()=>{if($.length>=o){c?.($.length);return}le("");const lt=[...$,Ue];R(lt),n?.(lt)},className:N("cursor-pointer",Ue.disable&&"cursor-default text-muted-foreground"),children:Ue.label},Ue.value))})},ee))]})})})]})});at.displayName="MultipleSelector";const Xm=s=>x.object({id:x.number().optional(),name:x.string().min(2,s("messages.nameValidation.min")).max(50,s("messages.nameValidation.max")).regex(/^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/,s("messages.nameValidation.pattern"))});function ta({refetch:s,dialogTrigger:n,defaultValues:t={name:""},type:r="add"}){const{t:a}=V("group"),i=ge({resolver:Ne(Xm(a)),defaultValues:t,mode:"onChange"}),[l,d]=u.useState(!1),[m,o]=u.useState(!1),c=async h=>{o(!0),Rc(h).then(()=>{A.success(a(r==="edit"?"messages.updateSuccess":"messages.createSuccess")),s&&s(),i.reset(),d(!1)}).finally(()=>{o(!1)})};return e.jsxs(be,{open:l,onOpenChange:d,children:[e.jsx(Je,{asChild:!0,children:n||e.jsxs(P,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Ve,{icon:"ion:add"}),e.jsx("span",{children:a("form.add")})]})}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:a(r==="edit"?"form.edit":"form.create")}),e.jsx(Te,{children:a(r==="edit"?"form.editDescription":"form.createDescription")})]}),e.jsx(_e,{...i,children:e.jsxs("form",{onSubmit:i.handleSubmit(c),className:"space-y-4",children:[e.jsx(g,{control:i.control,name:"name",render:({field:h})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.name")}),e.jsx(y,{children:e.jsx(T,{placeholder:a("form.namePlaceholder"),...h,className:"w-full"})}),e.jsx(F,{children:a("form.nameDescription")}),e.jsx(D,{})]})}),e.jsxs(ze,{className:"gap-2",children:[e.jsx(yt,{asChild:!0,children:e.jsx(P,{type:"button",variant:"outline",children:a("form.cancel")})}),e.jsxs(P,{type:"submit",disabled:m||!i.formState.isValid,children:[m&&e.jsx(Da,{className:"mr-2 h-4 w-4 animate-spin"}),a(r==="edit"?"form.update":"form.create")]})]})]})})]})]})}const Jr=u.createContext(void 0);function Zm({children:s,refetch:n}){const[t,r]=u.useState(!1),[a,i]=u.useState(null),[l,d]=u.useState(ie.Shadowsocks);return e.jsx(Jr.Provider,{value:{isOpen:t,setIsOpen:r,editingServer:a,setEditingServer:i,serverType:l,setServerType:d,refetch:n},children:s})}function Xr(){const s=u.useContext(Jr);if(s===void 0)throw new Error("useServerEdit must be used within a ServerEditProvider");return s}function da({dialogTrigger:s,value:n,setValue:t,templateType:r}){const{t:a}=V("server");u.useEffect(()=>{console.log(n)},[n]);const[i,l]=u.useState(!1),[d,m]=u.useState(()=>{if(!n||Object.keys(n).length===0)return"";try{return JSON.stringify(n,null,2)}catch{return""}}),[o,c]=u.useState(null),h=b=>{if(!b)return null;try{const k=JSON.parse(b);return typeof k!="object"||k===null?a("network_settings.validation.must_be_object"):null}catch{return a("network_settings.validation.invalid_json")}},_={tcp:{label:"TCP",content:{acceptProxyProtocol:!1,header:{type:"none"}}},"tcp-http":{label:"TCP + HTTP",content:{acceptProxyProtocol:!1,header:{type:"http",request:{version:"1.1",method:"GET",path:["/"],headers:{Host:["www.example.com"]}},response:{version:"1.1",status:"200",reason:"OK"}}}},grpc:{label:"gRPC",content:{serviceName:"GunService"}},ws:{label:"WebSocket",content:{path:"/",headers:{Host:"v2ray.com"}}},httpupgrade:{label:"HttpUpgrade",content:{acceptProxyProtocol:!1,path:"/",host:"xray.com",headers:{key:"value"}}},xhttp:{label:"XHTTP",content:{host:"example.com",path:"/yourpath",mode:"auto",extra:{headers:{},xPaddingBytes:"100-1000",noGRPCHeader:!1,noSSEHeader:!1,scMaxEachPostBytes:1e6,scMinPostsIntervalMs:30,scMaxBufferedPosts:30,xmux:{maxConcurrency:"16-32",maxConnections:0,cMaxReuseTimes:"64-128",cMaxLifetimeMs:0,hMaxRequestTimes:"800-900",hKeepAlivePeriod:0},downloadSettings:{address:"",port:443,network:"xhttp",security:"tls",tlsSettings:{},xhttpSettings:{path:"/yourpath"},sockopt:{}}}}}},E=()=>{switch(r){case"tcp":return["tcp","tcp-http"];case"grpc":return["grpc"];case"ws":return["ws"];case"httpupgrade":return["httpupgrade"];case"xhttp":return["xhttp"];default:return[]}},C=()=>{const b=h(d||"");if(b){A.error(b);return}try{if(!d){t(null),l(!1);return}t(JSON.parse(d)),l(!1)}catch{A.error(a("network_settings.errors.save_failed"))}},S=b=>{m(b),c(h(b))},w=b=>{const k=_[b];if(k){const p=JSON.stringify(k.content,null,2);m(p),c(null)}};return u.useEffect(()=>{i&&console.log(n)},[i,n]),u.useEffect(()=>{i&&n&&Object.keys(n).length>0&&m(JSON.stringify(n,null,2))},[i,n]),e.jsxs(be,{open:i,onOpenChange:b=>{!b&&i&&C(),l(b)},children:[e.jsx(Je,{asChild:!0,children:s??e.jsx(J,{variant:"link",children:a("network_settings.edit_protocol")})}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsx(Ce,{children:e.jsx(ye,{children:a("network_settings.edit_protocol_config")})}),e.jsxs("div",{className:"space-y-4",children:[E().length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 pt-2",children:E().map(b=>e.jsx(J,{variant:"outline",size:"sm",onClick:()=>w(b),children:a("network_settings.use_template",{template:_[b].label})},b))}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ys,{className:`min-h-[200px] font-mono text-sm ${o?"border-red-500 focus-visible:ring-red-500":""}`,value:d,placeholder:E().length>0?a("network_settings.json_config_placeholder_with_template"):a("network_settings.json_config_placeholder"),onChange:b=>S(b.target.value)}),o&&e.jsx("p",{className:"text-sm text-red-500",children:o})]})]}),e.jsxs(ze,{className:"gap-2",children:[e.jsx(J,{variant:"outline",onClick:()=>l(!1),children:a("common.cancel")}),e.jsx(J,{onClick:C,disabled:!!o,children:a("common.confirm")})]})]})]})}function hp(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}const ex={},sx=Object.freeze(Object.defineProperty({__proto__:null,default:ex},Symbol.toStringTag,{value:"Module"})),pp=Jo(sx),dn=s=>s.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),tx=()=>{try{const s=Lo.box.keyPair(),n=dn(Ja.encodeBase64(s.secretKey)),t=dn(Ja.encodeBase64(s.publicKey));return{privateKey:n,publicKey:t}}catch(s){throw console.error("Error generating x25519 key pair:",s),s}},ax=()=>{try{return tx()}catch(s){throw console.error("Error generating key pair:",s),s}},nx=s=>{const n=new Uint8Array(Math.ceil(s/2));return window.crypto.getRandomValues(n),Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join("").substring(0,s)},rx=()=>{const s=Math.floor(Math.random()*8)*2+2;return nx(s)},lx=x.object({cipher:x.string().default("aes-128-gcm"),obfs:x.string().default("0"),obfs_settings:x.object({path:x.string().default(""),host:x.string().default("")}).default({})}),ix=x.object({tls:x.coerce.number().default(0),tls_settings:x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1)}).default({}),network:x.string().default("tcp"),network_settings:x.record(x.any()).default({})}),ox=x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1),network:x.string().default("tcp"),network_settings:x.record(x.any()).default({})}),cx=x.object({version:x.coerce.number().default(2),alpn:x.string().default("h2"),obfs:x.object({open:x.coerce.boolean().default(!1),type:x.string().default("salamander"),password:x.string().default("")}).default({}),tls:x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1)}).default({}),bandwidth:x.object({up:x.string().default(""),down:x.string().default("")}).default({})}),dx=x.object({tls:x.coerce.number().default(0),tls_settings:x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1)}).default({}),reality_settings:x.object({server_port:x.coerce.number().default(443),server_name:x.string().default(""),allow_insecure:x.boolean().default(!1),public_key:x.string().default(""),private_key:x.string().default(""),short_id:x.string().default("")}).default({}),network:x.string().default("tcp"),network_settings:x.record(x.any()).default({}),flow:x.string().default("")}),ux=x.object({version:x.coerce.number().default(5),congestion_control:x.string().default("bbr"),alpn:x.array(x.string()).default(["h3"]),udp_relay_mode:x.string().default("native"),tls:x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1)}).default({})}),mx=x.object({}),xx=x.object({tls:x.coerce.number().default(0),tls_settings:x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1)}).default({})}),hx=x.object({tls:x.coerce.number().default(0),tls_settings:x.object({server_name:x.string().default(""),allow_insecure:x.boolean().default(!1)}).default({})}),px=x.object({transport:x.string().default("tcp"),multiplexing:x.string().default("MULTIPLEXING_LOW")}),Ie={shadowsocks:{schema:lx,ciphers:["aes-128-gcm","aes-192-gcm","aes-256-gcm","chacha20-ietf-poly1305","2022-blake3-aes-128-gcm","2022-blake3-aes-256-gcm"]},vmess:{schema:ix,networkOptions:[{value:"tcp",label:"TCP"},{value:"ws",label:"Websocket"},{value:"grpc",label:"gRPC"}]},trojan:{schema:ox,networkOptions:[{value:"tcp",label:"TCP"},{value:"ws",label:"Websocket"},{value:"grpc",label:"gRPC"}]},hysteria:{schema:cx,versions:["1","2"],alpnOptions:["hysteria","http/1.1","h2","h3"]},vless:{schema:dx,networkOptions:[{value:"tcp",label:"TCP"},{value:"ws",label:"Websocket"},{value:"grpc",label:"gRPC"},{value:"kcp",label:"mKCP"},{value:"httpupgrade",label:"HttpUpgrade"},{value:"xhttp",label:"XHTTP"}],flowOptions:["none","xtls-rprx-direct","xtls-rprx-splice","xtls-rprx-vision"]},tuic:{schema:ux,versions:["5","4"],congestionControls:["bbr","cubic","new_reno"],alpnOptions:[{value:"h3",label:"HTTP/3"},{value:"h2",label:"HTTP/2"},{value:"http/1.1",label:"HTTP/1.1"}],udpRelayModes:[{value:"native",label:"Native"},{value:"quic",label:"QUIC"}]},socks:{schema:mx},naive:{schema:hx},http:{schema:xx},mieru:{schema:px,transportOptions:[{value:"tcp",label:"TCP"},{value:"udp",label:"UDP"}],multiplexingOptions:[{value:"MULTIPLEXING_OFF",label:"Off"},{value:"MULTIPLEXING_LOW",label:"Low"},{value:"MULTIPLEXING_MIDDLE",label:"Middle"},{value:"MULTIPLEXING_HIGH",label:"High"}]}},fx=({serverType:s,value:n,onChange:t})=>{const{t:r}=V("server"),a=s?Ie[s]:null,i=a?.schema||x.record(x.any()),l=s?i.parse({}):{},d=ge({resolver:Ne(i),defaultValues:l,mode:"onChange"});if(u.useEffect(()=>{if(!n||Object.keys(n).length===0){if(s){const p=i.parse({});d.reset(p)}}else d.reset(n)},[s,n,t,d,i]),u.useEffect(()=>{const p=d.watch(v=>{t(v)});return()=>p.unsubscribe()},[d,t]),!s||!a)return null;const k={shadowsocks:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"cipher",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.shadowsocks.cipher.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.shadowsocks.cipher.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.shadowsocks.ciphers.map(v=>e.jsx(z,{value:v,children:v},v))})})]})})]})}),e.jsx(g,{control:d.control,name:"obfs",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.shadowsocks.obfs.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.shadowsocks.obfs.placeholder")})}),e.jsx(B,{children:e.jsxs(He,{children:[e.jsx(z,{value:"0",children:r("dynamic_form.shadowsocks.obfs.none")}),e.jsx(z,{value:"http",children:r("dynamic_form.shadowsocks.obfs.http")})]})})]})})]})}),d.watch("obfs")==="http"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"obfs_settings.path",render:({field:p})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(y,{children:e.jsx(T,{type:"text",placeholder:r("dynamic_form.shadowsocks.obfs_settings.path"),...p})}),e.jsx(D,{})]})}),e.jsx(g,{control:d.control,name:"obfs_settings.host",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(y,{children:e.jsx(T,{type:"text",placeholder:r("dynamic_form.shadowsocks.obfs_settings.host"),...p})}),e.jsx(D,{})]})})]})]}),vmess:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"tls",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vmess.tls.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value?.toString(),onValueChange:v=>p.onChange(Number(v)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.vmess.tls.placeholder")})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:r("dynamic_form.vmess.tls.disabled")}),e.jsx(z,{value:"1",children:r("dynamic_form.vmess.tls.enabled")})]})]})})]})}),d.watch("tls")==1&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"tls_settings.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.vmess.tls_settings.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.vmess.tls_settings.server_name.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"tls_settings.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vmess.tls_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),e.jsx(g,{control:d.control,name:"network",render:({field:p})=>e.jsxs(f,{children:[e.jsxs(j,{children:[r("dynamic_form.vmess.network.label"),e.jsx(da,{value:d.watch("network_settings"),setValue:v=>d.setValue("network_settings",v),templateType:d.watch("network")})]}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.vmess.network.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.vmess.networkOptions.map(v=>e.jsx(z,{value:v.value,className:"cursor-pointer",children:v.label},v.value))})})]})})]})})]}),trojan:()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.trojan.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.trojan.server_name.placeholder"),...p,value:p.value||""})})]})}),e.jsx(g,{control:d.control,name:"allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.trojan.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value||!1,onCheckedChange:p.onChange})})})]})})]}),e.jsx(g,{control:d.control,name:"network",render:({field:p})=>e.jsxs(f,{children:[e.jsxs(j,{children:[r("dynamic_form.trojan.network.label"),e.jsx(da,{value:d.watch("network_settings")||{},setValue:v=>d.setValue("network_settings",v),templateType:d.watch("network")||"tcp"})]}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value||"tcp",children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.trojan.network.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.trojan.networkOptions.map(v=>e.jsx(z,{value:v.value,className:"cursor-pointer",children:v.label},v.value))})})]})})]})})]}),hysteria:()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"version",render:({field:p})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:r("dynamic_form.hysteria.version.label")}),e.jsx(y,{children:e.jsxs(G,{value:(p.value||2).toString(),onValueChange:v=>p.onChange(Number(v)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.hysteria.version.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.hysteria.versions.map(v=>e.jsxs(z,{value:v,className:"cursor-pointer",children:["V",v]},v))})})]})})]})}),d.watch("version")==1&&e.jsx(g,{control:d.control,name:"alpn",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.hysteria.alpn.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value||"h2",onValueChange:p.onChange,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.hysteria.alpn.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.hysteria.alpnOptions.map(v=>e.jsx(z,{value:v,children:v},v))})})]})})]})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"obfs.open",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.hysteria.obfs.label")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value||!1,onCheckedChange:p.onChange})})})]})}),!!d.watch("obfs.open")&&e.jsxs(e.Fragment,{children:[d.watch("version")=="2"&&e.jsx(g,{control:d.control,name:"obfs.type",render:({field:p})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:r("dynamic_form.hysteria.obfs.type.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value||"salamander",onValueChange:p.onChange,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.hysteria.obfs.type.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:e.jsx(z,{value:"salamander",children:r("dynamic_form.hysteria.obfs.type.salamander")})})})]})})]})}),e.jsx(g,{control:d.control,name:"obfs.password",render:({field:p})=>e.jsxs(f,{className:d.watch("version")==2?"w-full":"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.hysteria.obfs.password.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.hysteria.obfs.password.placeholder"),...p,value:p.value||"",className:"pr-9"})}),e.jsx(J,{type:"button",variant:"ghost",size:"icon",onClick:()=>{const v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",M=Array.from(crypto.getRandomValues(new Uint8Array(16))).map(H=>v[H%v.length]).join("");d.setValue("obfs.password",M),A.success(r("dynamic_form.hysteria.obfs.password.generate_success"))},className:"absolute right-0 top-0 h-full px-2 active:scale-90 transition-transform duration-150",children:e.jsx(Ve,{icon:"ion:refresh-outline",className:"h-4 w-4 transition-transform hover:rotate-180 duration-300"})})]})]})})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"tls.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.hysteria.tls.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.hysteria.tls.server_name.placeholder"),...p,value:p.value||""})})]})}),e.jsx(g,{control:d.control,name:"tls.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.hysteria.tls.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value||!1,onCheckedChange:p.onChange})})})]})})]}),e.jsx(g,{control:d.control,name:"bandwidth.up",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.hysteria.bandwidth.up.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:r("dynamic_form.hysteria.bandwidth.up.placeholder")+(d.watch("version")==2?r("dynamic_form.hysteria.bandwidth.up.bbr_tip"):""),className:"rounded-br-none rounded-tr-none",...p,value:p.value||""})}),e.jsx("div",{className:"pointer-events-none z-[-1] flex items-center rounded-md rounded-bl-none rounded-tl-none border border-l-0 border-input px-3 shadow-sm",children:e.jsx("span",{className:"text-gray-500",children:r("dynamic_form.hysteria.bandwidth.up.suffix")})})]})]})}),e.jsx(g,{control:d.control,name:"bandwidth.down",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.hysteria.bandwidth.down.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:r("dynamic_form.hysteria.bandwidth.down.placeholder")+(d.watch("version")==2?r("dynamic_form.hysteria.bandwidth.down.bbr_tip"):""),className:"rounded-br-none rounded-tr-none",...p,value:p.value||""})}),e.jsx("div",{className:"pointer-events-none z-[-1] flex items-center rounded-md rounded-bl-none rounded-tl-none border border-l-0 border-input px-3 shadow-sm",children:e.jsx("span",{className:"text-gray-500",children:r("dynamic_form.hysteria.bandwidth.down.suffix")})})]})]})})]}),vless:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"tls",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vless.tls.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value?.toString(),onValueChange:v=>p.onChange(Number(v)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.vless.tls.placeholder")})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:r("dynamic_form.vless.tls.none")}),e.jsx(z,{value:"1",children:r("dynamic_form.vless.tls.tls")}),e.jsx(z,{value:"2",children:r("dynamic_form.vless.tls.reality")})]})]})})]})}),d.watch("tls")=="1"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"tls_settings.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.vless.tls_settings.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.vless.tls_settings.server_name.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"tls_settings.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vless.tls_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),d.watch("tls")==2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"reality_settings.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.vless.reality_settings.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.vless.reality_settings.server_name.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"reality_settings.server_port",render:({field:p})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:r("dynamic_form.vless.reality_settings.server_port.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.vless.reality_settings.server_port.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"reality_settings.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vless.reality_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),e.jsx("div",{className:"flex items-end gap-2",children:e.jsx(g,{control:d.control,name:"reality_settings.private_key",render:({field:p})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:r("dynamic_form.vless.reality_settings.private_key.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(y,{children:e.jsx(T,{...p,className:"pr-9"})}),e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(J,{type:"button",variant:"ghost",size:"icon",onClick:()=>{try{const v=ax();d.setValue("reality_settings.private_key",v.privateKey),d.setValue("reality_settings.public_key",v.publicKey),A.success(r("dynamic_form.vless.reality_settings.key_pair.success"))}catch{A.error(r("dynamic_form.vless.reality_settings.key_pair.error"))}},className:"absolute right-0 top-0 h-full px-2 active:scale-90 transition-transform duration-150",children:e.jsx(Ve,{icon:"ion:key-outline",className:"h-4 w-4 transition-transform hover:rotate-180 duration-300"})})}),e.jsx(It,{children:e.jsx(ce,{children:e.jsx("p",{children:r("dynamic_form.vless.reality_settings.key_pair.generate")})})})]})]})]})})}),e.jsx(g,{control:d.control,name:"reality_settings.public_key",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vless.reality_settings.public_key.label")}),e.jsx(y,{children:e.jsx(T,{...p})})]})}),e.jsx(g,{control:d.control,name:"reality_settings.short_id",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vless.reality_settings.short_id.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(y,{children:e.jsx(T,{...p,className:"pr-9",placeholder:r("dynamic_form.vless.reality_settings.short_id.placeholder")})}),e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(J,{type:"button",variant:"ghost",size:"icon",onClick:()=>{const v=rx();d.setValue("reality_settings.short_id",v),A.success(r("dynamic_form.vless.reality_settings.short_id.success"))},className:"absolute right-0 top-0 h-full px-2 active:scale-90 transition-transform duration-150",children:e.jsx(Ve,{icon:"ion:refresh-outline",className:"h-4 w-4 transition-transform hover:rotate-180 duration-300"})})}),e.jsx(It,{children:e.jsx(ce,{children:e.jsx("p",{children:r("dynamic_form.vless.reality_settings.short_id.generate")})})})]})]}),e.jsx(F,{className:"text-xs text-muted-foreground",children:r("dynamic_form.vless.reality_settings.short_id.description")})]})})]}),e.jsx(g,{control:d.control,name:"network",render:({field:p})=>e.jsxs(f,{children:[e.jsxs(j,{children:[r("dynamic_form.vless.network.label"),e.jsx(da,{value:d.watch("network_settings"),setValue:v=>d.setValue("network_settings",v),templateType:d.watch("network")})]}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.vless.network.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.vless.networkOptions.map(v=>e.jsx(z,{value:v.value,className:"cursor-pointer",children:v.label},v.value))})})]})})]})}),e.jsx(g,{control:d.control,name:"flow",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.vless.flow.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:v=>p.onChange(v==="none"?null:v),value:p.value||"none",children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.vless.flow.placeholder")})}),e.jsx(B,{children:Ie.vless.flowOptions.map(v=>e.jsx(z,{value:v,children:v},v))})]})})]})})]}),tuic:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"version",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.tuic.version.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value?.toString(),onValueChange:v=>p.onChange(Number(v)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.tuic.version.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.tuic.versions.map(v=>e.jsxs(z,{value:v,children:["V",v]},v))})})]})})]})}),e.jsx(g,{control:d.control,name:"congestion_control",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.tuic.congestion_control.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.tuic.congestion_control.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.tuic.congestionControls.map(v=>e.jsx(z,{value:v,children:v.toUpperCase()},v))})})]})})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"tls.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.tuic.tls.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.tuic.tls.server_name.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"tls.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.tuic.tls.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value,onCheckedChange:p.onChange})})})]})})]}),e.jsx(g,{control:d.control,name:"alpn",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.tuic.tls.alpn.label")}),e.jsx(y,{children:e.jsx(at,{options:Ie.tuic.alpnOptions,onChange:v=>p.onChange(v.map(M=>M.value)),value:Ie.tuic.alpnOptions.filter(v=>p.value?.includes(v.value)),placeholder:r("dynamic_form.tuic.tls.alpn.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-lg leading-10 text-gray-600 dark:text-gray-400",children:r("dynamic_form.tuic.tls.alpn.empty")})})})]})}),e.jsx(g,{control:d.control,name:"udp_relay_mode",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.tuic.udp_relay_mode.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.tuic.udp_relay_mode.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.tuic.udpRelayModes.map(v=>e.jsx(z,{value:v.value,children:v.label},v.value))})})]})})]})})]}),socks:()=>e.jsx(e.Fragment,{}),naive:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"tls",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.naive.tls.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value?.toString(),onValueChange:v=>p.onChange(Number(v)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.naive.tls.placeholder")})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:r("dynamic_form.naive.tls.disabled")}),e.jsx(z,{value:"1",children:r("dynamic_form.naive.tls.enabled")})]})]})})]})}),d.watch("tls")==1&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"tls_settings.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.naive.tls_settings.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.naive.tls_settings.server_name.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"tls_settings.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.naive.tls_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value,onCheckedChange:p.onChange})})})]})})]})]}),http:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"tls",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.http.tls.label")}),e.jsx(y,{children:e.jsxs(G,{value:p.value?.toString(),onValueChange:v=>p.onChange(Number(v)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.http.tls.placeholder")})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:r("dynamic_form.http.tls.disabled")}),e.jsx(z,{value:"1",children:r("dynamic_form.http.tls.enabled")})]})]})})]})}),d.watch("tls")==1&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:d.control,name:"tls_settings.server_name",render:({field:p})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:r("dynamic_form.http.tls_settings.server_name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dynamic_form.http.tls_settings.server_name.placeholder"),...p})})]})}),e.jsx(g,{control:d.control,name:"tls_settings.allow_insecure",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.http.tls_settings.allow_insecure")}),e.jsx("div",{className:"py-2 text-center",children:e.jsx(y,{children:e.jsx(Y,{checked:p.value,onCheckedChange:p.onChange})})})]})})]})]}),mieru:()=>e.jsxs(e.Fragment,{children:[e.jsx(g,{control:d.control,name:"transport",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.mieru.transport.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.mieru.transport.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.mieru.transportOptions.map(v=>e.jsx(z,{value:v.value,children:v.label},v.value))})})]})})]})}),e.jsx(g,{control:d.control,name:"multiplexing",render:({field:p})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dynamic_form.mieru.multiplexing.label")}),e.jsx(y,{children:e.jsxs(G,{onValueChange:p.onChange,value:p.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dynamic_form.mieru.multiplexing.placeholder")})}),e.jsx(B,{children:e.jsx(He,{children:Ie.mieru.multiplexingOptions.map(v=>e.jsx(z,{value:v.value,children:v.label},v.value))})})]})})]})})]})};return e.jsx(ve,{children:k[s]?.()})},gx=x.object({id:x.number().optional().nullable(),code:x.string().optional(),name:x.string().min(1,"form.name.error"),rate:x.string().min(1,"form.rate.error"),tags:x.array(x.string()).default([]),excludes:x.array(x.string()).default([]),ips:x.array(x.string()).default([]),group_ids:x.array(x.string()).default([]),host:x.string().min(1,"form.host.error"),port:x.string().min(1,"form.port.error"),server_port:x.string().min(1,"form.server_port.error"),parent_id:x.string().default("0").nullable(),route_ids:x.array(x.string()).default([]),protocol_settings:x.record(x.any()).default({}).nullable()}),wt={id:null,code:"",name:"",rate:"1",tags:[],excludes:[],ips:[],group_ids:[],host:"",port:"",server_port:"",parent_id:"0",route_ids:[],protocol_settings:null};function jx(){const{t:s}=V("server"),{isOpen:n,setIsOpen:t,editingServer:r,setEditingServer:a,serverType:i,setServerType:l,refetch:d}=Xr(),[m,o]=u.useState([]),[c,h]=u.useState([]),[_,E]=u.useState([]),C=ge({resolver:Ne(gx),defaultValues:wt,mode:"onChange"});u.useEffect(()=>{S()},[n]),u.useEffect(()=>{r?.type&&r.type!==i&&l(r.type)},[r,i,l]),u.useEffect(()=>{r?r.type===i&&C.reset({...wt,...r}):C.reset({...wt,protocol_settings:Ie[i].schema.parse({})})},[r,C,i]);const S=async()=>{if(!n)return;const[v,M,H]=await Promise.all([bt(),Sr(),Cr()]);o(v.data?.map(se=>({label:se.name,value:se.id.toString()}))||[]),h(M.data?.map(se=>({label:se.remarks,value:se.id.toString()}))||[]),E(H.data||[])},w=u.useMemo(()=>_?.filter(v=>(v.parent_id===0||v.parent_id===null)&&v.type===i&&v.id!==C.watch("id")),[i,_,C]),b=()=>e.jsxs(Ss,{children:[e.jsx(ks,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Ve,{icon:"ion:add"}),e.jsx("div",{children:s("form.add_node")})]})}),e.jsx(fs,{align:"start",children:e.jsx(Od,{children:Xe.map(({type:v,label:M})=>e.jsx(je,{onClick:()=>{l(v),t(!0)},className:"cursor-pointer",children:e.jsx(q,{variant:"outline",className:"text-white",style:{background:qe[v]},children:M})},v))})})]}),k=()=>{t(!1),a(null),C.reset(wt)},p=async()=>{const v=C.getValues();(await kc({...v,type:i})).data&&(k(),A.success(s("form.success")),d())};return e.jsxs(be,{open:n,onOpenChange:k,children:[b(),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:s(r?"form.edit_node":"form.new_node")}),e.jsx(Te,{})]}),e.jsxs(_e,{...C,children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{control:C.control,name:"name",render:({field:v})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:s("form.name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("form.name.placeholder"),...v})}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"rate",render:({field:v})=>e.jsxs(f,{className:"flex-[1]",children:[e.jsx(j,{children:s("form.rate.label")}),e.jsx("div",{className:"relative flex",children:e.jsx(y,{children:e.jsx(T,{type:"number",min:"0",step:"0.1",...v})})}),e.jsx(D,{})]})})]}),e.jsx(g,{control:C.control,name:"code",render:({field:v})=>e.jsxs(f,{children:[e.jsxs(j,{children:[s("form.code.label"),e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:s("form.code.optional")})]}),e.jsx(y,{children:e.jsx(T,{placeholder:s("form.code.placeholder"),...v,value:v.value||""})}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"tags",render:({field:v})=>e.jsxs(f,{children:[e.jsx(j,{children:s("form.tags.label")}),e.jsx(y,{children:e.jsx(La,{value:v.value,onChange:v.onChange,placeholder:s("form.tags.placeholder"),className:"w-full"})}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"group_ids",render:({field:v})=>e.jsxs(f,{children:[e.jsxs(j,{className:"flex items-center justify-between",children:[s("form.groups.label"),e.jsx(ta,{dialogTrigger:e.jsx(P,{variant:"link",children:s("form.groups.add")}),refetch:S})]}),e.jsx(y,{children:e.jsx(at,{options:m,onChange:M=>v.onChange(M.map(H=>H.value)),value:m?.filter(M=>v.value.includes(M.value)),placeholder:s("form.groups.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-lg leading-10 text-gray-600 dark:text-gray-400",children:s("form.groups.empty")})})}),e.jsx(D,{})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:C.control,name:"host",render:({field:v})=>e.jsxs(f,{children:[e.jsx(j,{children:s("form.host.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:s("form.host.placeholder"),...v})}),e.jsx(D,{})]})}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(g,{control:C.control,name:"port",render:({field:v})=>e.jsxs(f,{className:"flex-1",children:[e.jsxs(j,{className:"flex items-center gap-1.5",children:[s("form.port.label"),e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(Ve,{icon:"ph:info-light",className:"size-3.5 cursor-help text-muted-foreground"})}),e.jsx(It,{children:e.jsx(ce,{side:"top",sideOffset:8,className:"max-w-80 p-3",children:e.jsx("p",{children:s("form.port.tooltip")})})})]})})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(y,{children:e.jsx(T,{placeholder:s("form.port.placeholder"),...v})}),e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(P,{type:"button",variant:"ghost",size:"icon",className:"size-6 shrink-0 text-muted-foreground/50 hover:text-muted-foreground",onClick:()=>{const M=v.value;M&&C.setValue("server_port",M)},children:e.jsx(Ve,{icon:"tabler:arrows-right",className:"size-3"})})}),e.jsx(ce,{side:"right",children:e.jsx("p",{children:s("form.port.sync")})})]})})]}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"server_port",render:({field:v})=>e.jsxs(f,{className:"flex-1",children:[e.jsxs(j,{className:"flex items-center gap-1.5",children:[s("form.server_port.label"),e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(Ve,{icon:"ph:info-light",className:"size-3.5 cursor-help text-muted-foreground"})}),e.jsx(It,{children:e.jsx(ce,{side:"top",sideOffset:8,className:"max-w-80 p-3",children:e.jsx("p",{children:s("form.server_port.tooltip")})})})]})})]}),e.jsx(y,{children:e.jsx(T,{placeholder:s("form.server_port.placeholder"),...v})}),e.jsx(D,{})]})})]})]}),n&&e.jsx(fx,{serverType:i,value:C.watch("protocol_settings"),onChange:v=>C.setValue("protocol_settings",v,{shouldDirty:!0,shouldTouch:!0,shouldValidate:!0})}),e.jsx(g,{control:C.control,name:"parent_id",render:({field:v})=>e.jsxs(f,{children:[e.jsx(j,{children:s("form.parent.label")}),e.jsxs(G,{onValueChange:v.onChange,value:v.value?.toString()||"0",children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:s("form.parent.placeholder")})})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("form.parent.none")}),w?.map(M=>e.jsx(z,{value:M.id.toString(),className:"cursor-pointer",children:M.name},M.id))]})]}),e.jsx(D,{})]})}),e.jsx(g,{control:C.control,name:"route_ids",render:({field:v})=>e.jsxs(f,{children:[e.jsx(j,{children:s("form.route.label")}),e.jsx(y,{children:e.jsx(at,{options:c,onChange:M=>v.onChange(M.map(H=>H.value)),value:c?.filter(M=>v.value.includes(M.value)),placeholder:s("form.route.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-lg leading-10 text-gray-600 dark:text-gray-400",children:s("form.route.empty")})})}),e.jsx(D,{})]})})]}),e.jsxs(ze,{className:"mt-6",children:[e.jsx(P,{type:"button",variant:"outline",onClick:k,children:s("form.cancel")}),e.jsx(P,{type:"submit",onClick:p,children:s("form.submit")})]})]})]})]})}function un({column:s,title:n,options:t}){const r=s?.getFacetedUniqueValues(),a=new Set(s?.getFilterValue());return e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),n,a?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:a.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:a.size>2?e.jsxs(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[a.size," selected"]}):t.filter(i=>a.has(i.value)).map(i=>e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:i.label},i.value))})]})]})}),e.jsx(xs,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Ms,{children:[e.jsx(Ks,{placeholder:n}),e.jsxs(Fs,{children:[e.jsx(Bs,{children:"No results found."}),e.jsx(Ye,{children:t.map(i=>{const l=a.has(i.value);return e.jsxs(Me,{onSelect:()=>{l?a.delete(i.value):a.add(i.value);const d=Array.from(a);s?.setFilterValue(d.length?d:void 0)},className:"cursor-pointer",children:[e.jsx("div",{className:N("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",l?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx($s,{className:N("h-4 w-4")})}),i.icon&&e.jsx(i.icon,{className:`mr-2 h-4 w-4 text-muted-foreground text-${i.color}`}),e.jsx("span",{children:i.label}),r?.get(i.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(i.value)})]},i.value)})}),a.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx(Ye,{children:e.jsx(Me,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center cursor-pointer",children:"Clear filters"})})]})]})]})})]})}const vx=[{value:ie.Shadowsocks,label:Xe.find(s=>s.type===ie.Shadowsocks)?.label,color:qe[ie.Shadowsocks]},{value:ie.Vmess,label:Xe.find(s=>s.type===ie.Vmess)?.label,color:qe[ie.Vmess]},{value:ie.Trojan,label:Xe.find(s=>s.type===ie.Trojan)?.label,color:qe[ie.Trojan]},{value:ie.Hysteria,label:Xe.find(s=>s.type===ie.Hysteria)?.label,color:qe[ie.Hysteria]},{value:ie.Vless,label:Xe.find(s=>s.type===ie.Vless)?.label,color:qe[ie.Vless]},{value:ie.Tuic,label:Xe.find(s=>s.type===ie.Tuic)?.label,color:qe[ie.Tuic]},{value:ie.Socks,label:Xe.find(s=>s.type===ie.Socks)?.label,color:qe[ie.Socks]},{value:ie.Naive,label:Xe.find(s=>s.type===ie.Naive)?.label,color:qe[ie.Naive]},{value:ie.Http,label:Xe.find(s=>s.type===ie.Http)?.label,color:qe[ie.Http]},{value:ie.Mieru,label:Xe.find(s=>s.type===ie.Mieru)?.label,color:qe[ie.Mieru]}];function bx({table:s,saveOrder:n,isSortMode:t,groups:r}){const a=s.getState().columnFilters.length>0,{t:i}=V("server");return e.jsxs("div",{className:"flex items-center justify-between ",children:[e.jsxs("div",{className:"flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-2",children:[!t&&e.jsxs(e.Fragment,{children:[e.jsx(jx,{}),e.jsx(T,{placeholder:i("toolbar.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:l=>s.getColumn("name")?.setFilterValue(l.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),e.jsxs("div",{className:"flex gap-x-2",children:[s.getColumn("type")&&e.jsx(un,{column:s.getColumn("type"),title:i("toolbar.type"),options:vx}),s.getColumn("group_ids")&&e.jsx(un,{column:s.getColumn("group_ids"),title:i("columns.groups.title"),options:r.map(l=>({label:l.name,value:l.id.toString()}))})]}),a&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[i("toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]}),t&&e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:i("toolbar.sort.tip")})})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(P,{variant:t?"default":"outline",onClick:n,size:"sm",children:i(t?"toolbar.sort.save":"toolbar.sort.edit")})})]})}const gt=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M15.71 12.71a6 6 0 1 0-7.42 0a10 10 0 0 0-6.22 8.18a1 1 0 0 0 2 .22a8 8 0 0 1 15.9 0a1 1 0 0 0 1 .89h.11a1 1 0 0 0 .88-1.1a10 10 0 0 0-6.25-8.19M12 12a4 4 0 1 1 4-4a4 4 0 0 1-4 4"})}),Ct={0:"bg-destructive/80 shadow-sm shadow-destructive/50",1:"bg-yellow-500/80 shadow-sm shadow-yellow-500/50",2:"bg-emerald-500/80 shadow-sm shadow-emerald-500/50"},yx=s=>{const{t:n}=V("server");return[{id:"drag-handle",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.sort")}),cell:()=>e.jsx("div",{className:"flex items-center justify-center",children:e.jsx(Ht,{className:"size-4 cursor-move text-muted-foreground transition-colors hover:text-primary","aria-hidden":"true"})}),size:50},{accessorKey:"id",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.nodeId")}),cell:({row:t})=>{const r=t.getValue("id"),a=t.original.code;return e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsxs("div",{className:"group/id flex items-center space-x-2",children:[e.jsxs(q,{variant:"outline",className:N("border-2 font-medium transition-all duration-200 hover:opacity-80","flex items-center gap-1.5"),style:{borderColor:qe[t.original.type]},children:[e.jsx(ur,{className:"size-3"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"flex items-center gap-0.5",children:a??r}),t.original.parent?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground/30",children:"→"}),e.jsx("span",{children:t.original.parent?.code||t.original.parent?.id})]}):""]})]}),e.jsx(P,{variant:"ghost",size:"icon",className:"size-5 text-muted-foreground/40 opacity-0 transition-all duration-200 hover:text-muted-foreground group-hover/id:opacity-100",onClick:i=>{i.stopPropagation(),Ft(a||r.toString()).then(()=>{A.success(n("common:copy.success"))})},children:e.jsx(Xa,{className:"size-3"})})]})}),e.jsxs(ce,{side:"top",className:"flex flex-col gap-1 p-3",children:[e.jsxs("p",{className:"font-medium",children:[Xe.find(i=>i.type===t.original.type)?.label,t.original.parent_id?" (子节点)":""]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a?"点击括号内容或复制按钮可复制节点代码":"点击复制按钮可复制节点ID"})]})]})})},size:50,enableSorting:!0},{accessorKey:"show",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.show")}),cell:({row:t})=>{const[r,a]=u.useState(!!t.getValue("show"));return e.jsx(Y,{checked:r,onCheckedChange:async i=>{a(i),Pc({id:t.original.id,type:t.original.type,show:i?1:0}).catch(()=>{a(!i),s()})},style:{backgroundColor:r?qe[t.original.type]:void 0}})},size:50,enableSorting:!1},{accessorKey:"name",header:({column:t})=>e.jsx("div",{className:"flex items-center",children:e.jsx(O,{column:t,title:n("columns.node"),tooltip:e.jsxs("div",{className:"grid grid-cols-1 gap-3 p-2",children:[e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:N("h-2.5 w-2.5 rounded-full",Ct[0])}),e.jsx("span",{className:"text-sm font-medium",children:n("columns.status.0")})]}),e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:N("h-2.5 w-2.5 rounded-full",Ct[1])}),e.jsx("span",{className:"text-sm font-medium",children:n("columns.status.1")})]}),e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:N("h-2.5 w-2.5 rounded-full",Ct[2])}),e.jsx("span",{className:"text-sm font-medium",children:n("columns.status.2")})]})]})})}),cell:({row:t})=>e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{children:e.jsxs("div",{className:"flex items-center space-x-2.5",children:[e.jsx("span",{className:N("size-2.5 flex-shrink-0 rounded-full transition-all duration-200",Ct[t.original.available_status])}),e.jsx("span",{className:"text-left font-medium transition-colors hover:text-primary",children:t.getValue("name")})]})}),e.jsx(ce,{children:e.jsx("p",{className:"font-medium",children:n(`columns.status.${t.original.available_status}`)})})]})}),enableSorting:!1,size:200},{accessorKey:"host",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.address")}),cell:({row:t})=>{const r=`${t.original.host}:${t.original.port}`,a=t.original.port!==t.original.server_port;return e.jsxs("div",{className:"group relative flex min-w-0 items-start",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-baseline gap-x-1 gap-y-0.5 pr-7",children:[e.jsx("div",{className:"flex items-center ",children:e.jsxs("span",{className:"font-mono text-sm font-medium text-foreground/90",children:[t.original.host,":",t.original.port]})}),a&&e.jsxs("span",{className:"whitespace-nowrap text-[0.7rem] tracking-tight text-muted-foreground/40",children:["(",n("columns.internalPort")," ",t.original.server_port,")"]})]}),e.jsx("div",{className:"absolute right-0 top-0",children:e.jsx(ve,{delayDuration:0,children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(P,{variant:"ghost",size:"icon",className:"size-6 text-muted-foreground/40 opacity-0 transition-all duration-200 hover:bg-muted/50 hover:text-muted-foreground group-hover:opacity-100",onClick:i=>{i.stopPropagation(),Ft(r).then(()=>{A.success(n("common:copy.success"))})},children:e.jsx(Xa,{className:"size-3"})})}),e.jsx(ce,{side:"top",sideOffset:10,children:n("columns.copyAddress")})]})})})]})},enableSorting:!1,enableHiding:!0},{accessorKey:"online",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.onlineUsers.title"),tooltip:n("columns.onlineUsers.tooltip")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center space-x-2 px-4",children:[e.jsx(gt,{className:"size-4"}),e.jsx("span",{className:"font-medium",children:t.getValue("online")})]}),size:80,enableSorting:!0,enableHiding:!0},{accessorKey:"rate",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.rate.title"),tooltip:n("columns.rate.tooltip")}),cell:({row:t})=>e.jsxs(q,{variant:"secondary",className:"font-medium",children:[t.getValue("rate")," x"]}),size:80,enableSorting:!1,enableHiding:!0},{accessorKey:"group_ids",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.groups.title"),tooltip:n("columns.groups.tooltip")}),cell:({row:t})=>{const r=t.original.groups||[];return e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r.map((a,i)=>e.jsx(q,{variant:"secondary",className:N("px-2 py-0.5 font-medium","bg-secondary/50 hover:bg-secondary/70","border border-border/50","transition-all duration-200","cursor-default select-none","flex items-center gap-1.5"),children:a.name},i)),r.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:n("columns.groups.empty")})]})},enableSorting:!1,filterFn:(t,r,a)=>{const i=t.getValue(r);return i?a.some(l=>i.includes(l)):!1}},{accessorKey:"type",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.type")}),cell:({row:t})=>{const r=t.getValue("type");return e.jsx(q,{variant:"outline",className:"border-2 font-medium transition-colors",style:{borderColor:qe[r]},children:r})},enableSorting:!1,enableHiding:!0,enableColumnFilter:!1,size:8e3},{id:"actions",header:({column:t})=>e.jsx(O,{className:"justify-end",column:t,title:n("columns.actions")}),cell:({row:t})=>{const{setIsOpen:r,setEditingServer:a,setServerType:i}=Xr();return e.jsx("div",{className:"flex justify-center",children:e.jsxs(Ss,{modal:!1,children:[e.jsx(ks,{asChild:!0,children:e.jsx(P,{variant:"ghost",className:"h-8 w-8 p-0 hover:bg-muted","aria-label":n("columns.actions"),children:e.jsx(Vt,{className:"size-4"})})}),e.jsxs(fs,{align:"end",className:"w-40",children:[e.jsx(je,{className:"cursor-pointer",onClick:()=>{i(t.original.type),a(t.original),r(!0)},children:e.jsxs("div",{className:"flex w-full items-center",children:[e.jsx(zo,{className:"mr-2 size-4"}),n("columns.actions_dropdown.edit")]})}),e.jsxs(je,{className:"cursor-pointer",onClick:async()=>{Dc({id:t.original.id}).then(({data:l})=>{l&&(A.success(n("columns.actions_dropdown.copy_success")),s())})},children:[e.jsx(Ao,{className:"mr-2 size-4"}),n("columns.actions_dropdown.copy")]}),e.jsx(tt,{}),e.jsx(je,{className:"cursor-pointer text-destructive focus:text-destructive",onSelect:l=>l.preventDefault(),children:e.jsx(Qe,{title:n("columns.actions_dropdown.delete.title"),description:n("columns.actions_dropdown.delete.description"),confirmText:n("columns.actions_dropdown.delete.confirm"),variant:"destructive",onConfirm:async()=>{Tc({id:t.original.id}).then(({data:l})=>{l&&(A.success(n("columns.actions_dropdown.delete_success")),s())})},children:e.jsxs("div",{className:"flex w-full items-center",children:[e.jsx(cs,{className:"mr-2 size-4"}),n("columns.actions_dropdown.delete.confirm")]})})})]})]})})},size:50}]};function Nx(){const[s,n]=u.useState({}),[t,r]=u.useState({"drag-handle":!1}),[a,i]=u.useState([]),[l,d]=u.useState({pageSize:500,pageIndex:0}),[m,o]=u.useState([]),[c,h]=u.useState(!1),[_,E]=u.useState({}),[C,S]=u.useState([]),{refetch:w}=re({queryKey:["nodeList"],queryFn:async()=>{const{data:H}=await Cr();return S(H),H}}),{data:b}=re({queryKey:["groups"],queryFn:async()=>{const{data:H}=await bt();return H}});u.useEffect(()=>{r({"drag-handle":c,show:!c,host:!c,online:!c,rate:!c,groups:!c,type:!1,actions:!c}),E({name:c?2e3:200}),d({pageSize:c?99999:500,pageIndex:0})},[c]);const k=(H,se)=>{c&&(H.dataTransfer.setData("text/plain",se.toString()),H.currentTarget.classList.add("opacity-50"))},p=(H,se)=>{if(!c)return;H.preventDefault(),H.currentTarget.classList.remove("bg-muted");const L=parseInt(H.dataTransfer.getData("text/plain"));if(L===se)return;const Z=[...C],[de]=Z.splice(L,1);Z.splice(se,0,de),S(Z)},v=async()=>{if(!c){h(!0);return}const H=C?.map((se,L)=>({id:se.id,order:L+1}));Ec(H).then(()=>{A.success("排序保存成功"),h(!1),w()}).finally(()=>{h(!1)})},M=ns({data:C||[],columns:yx(w),state:{sorting:m,columnVisibility:t,rowSelection:s,columnFilters:a,columnSizing:_,pagination:l},enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:o,onColumnFiltersChange:i,onColumnVisibilityChange:r,onColumnSizingChange:E,onPaginationChange:d,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(Zm,{refetch:w,children:e.jsx("div",{className:"space-y-4",children:e.jsx(hs,{table:M,toolbar:H=>e.jsx(bx,{table:H,refetch:w,saveOrder:v,isSortMode:c,groups:b||[]}),draggable:c,onDragStart:k,onDragEnd:H=>H.currentTarget.classList.remove("opacity-50"),onDragOver:H=>{H.preventDefault(),H.currentTarget.classList.add("bg-muted")},onDragLeave:H=>H.currentTarget.classList.remove("bg-muted"),onDrop:p,showPagination:!c})})})}function _x(){const{t:s}=V("server");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("manage.title")}),e.jsx("p",{className:"text-muted-foreground mt-2",children:s("manage.description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Nx,{})})]})]})}const wx=Object.freeze(Object.defineProperty({__proto__:null,default:_x},Symbol.toStringTag,{value:"Module"}));function Cx({table:s,refetch:n}){const t=s.getState().columnFilters.length>0,{t:r}=V("group");return e.jsx("div",{className:"flex items-center justify-between space-x-4",children:e.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[e.jsx(ta,{refetch:n}),e.jsx(T,{placeholder:r("toolbar.searchPlaceholder"),value:s.getColumn("name")?.getFilterValue()??"",onChange:a=>s.getColumn("name")?.setFilterValue(a.target.value),className:N("h-8 w-[150px] lg:w-[250px]",t&&"border-primary/50 ring-primary/20")}),t&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[r("toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]})})}const Sx=s=>{const{t:n}=V("group");return[{accessorKey:"id",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.id")}),cell:({row:t})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(q,{variant:"outline",children:t.getValue("id")})}),enableSorting:!0},{accessorKey:"name",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.name")}),cell:({row:t})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium",children:t.getValue("name")})})},{accessorKey:"users_count",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.usersCount")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center space-x-2 px-4",children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:t.getValue("users_count")})]}),enableSorting:!0},{accessorKey:"server_count",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.serverCount")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center space-x-2 px-4",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:t.getValue("server_count")})]}),enableSorting:!0,size:8e3},{id:"actions",header:({column:t})=>e.jsx(O,{className:"justify-end",column:t,title:n("columns.actions")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(ta,{defaultValues:t.original,refetch:s,type:"edit",dialogTrigger:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("form.edit")})]})}),e.jsx(Qe,{title:n("messages.deleteConfirm"),description:n("messages.deleteDescription"),confirmText:n("messages.deleteButton"),variant:"destructive",onConfirm:async()=>{Ic({id:t.original.id}).then(({data:r})=>{r&&(A.success(n("messages.updateSuccess")),s())})},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("messages.deleteButton")})]})})]})}]};function kx(){const[s,n]=u.useState({}),[t,r]=u.useState({}),[a,i]=u.useState([]),[l,d]=u.useState([]),{data:m,refetch:o,isLoading:c}=re({queryKey:["serverGroupList"],queryFn:async()=>{const{data:_}=await bt();return _}}),h=ns({data:m||[],columns:Sx(o),state:{sorting:l,columnVisibility:t,rowSelection:s,columnFilters:a},enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:d,onColumnFiltersChange:i,onColumnVisibilityChange:r,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(hs,{table:h,toolbar:_=>e.jsx(Cx,{table:_,refetch:o}),isLoading:c})}function Tx(){const{t:s}=V("group");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(kx,{})})]})]})}const Dx=Object.freeze(Object.defineProperty({__proto__:null,default:Tx},Symbol.toStringTag,{value:"Module"})),Px=s=>x.object({remarks:x.string().min(1,s("form.validation.remarks")),match:x.array(x.string()),action:x.enum(["block","dns"]),action_value:x.string().optional()});function Zr({refetch:s,dialogTrigger:n,defaultValues:t={remarks:"",match:[],action:"block",action_value:""},type:r="add"}){const{t:a}=V("route"),i=ge({resolver:Ne(Px(a)),defaultValues:t,mode:"onChange"}),[l,d]=u.useState(!1);return e.jsxs(be,{open:l,onOpenChange:d,children:[e.jsx(Je,{asChild:!0,children:n||e.jsxs(P,{variant:"outline",size:"sm",className:"space-x-2",children:[e.jsx(Ve,{icon:"ion:add"})," ",e.jsx("div",{children:a("form.add")})]})}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:a(r==="edit"?"form.edit":"form.create")}),e.jsx(Te,{})]}),e.jsxs(_e,{...i,children:[e.jsx(g,{control:i.control,name:"remarks",render:({field:m})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:a("form.remarks")}),e.jsx("div",{className:"relative",children:e.jsx(y,{children:e.jsx(T,{type:"text",placeholder:a("form.remarksPlaceholder"),...m})})}),e.jsx(D,{})]})}),e.jsx(g,{control:i.control,name:"match",render:({field:m})=>e.jsxs(f,{className:"flex-[2]",children:[e.jsx(j,{children:a("form.match")}),e.jsx("div",{className:"relative",children:e.jsx(y,{children:e.jsx(ys,{className:"min-h-[120px]",placeholder:a("form.matchPlaceholder"),value:m.value.join(` +`),onChange:o=>{m.onChange(o.target.value.split(` +`))}})})}),e.jsx(D,{})]})}),e.jsx(g,{control:i.control,name:"action",render:({field:m})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.action")}),e.jsx("div",{className:"relative",children:e.jsx(y,{children:e.jsxs(G,{onValueChange:m.onChange,defaultValue:m.value,children:[e.jsx(K,{children:e.jsx(W,{placeholder:a("form.actionPlaceholder")})}),e.jsxs(B,{children:[e.jsx(z,{value:"block",children:a("actions.block")}),e.jsx(z,{value:"dns",children:a("actions.dns")})]})]})})}),e.jsx(D,{})]})}),i.watch("action")==="dns"&&e.jsx(g,{control:i.control,name:"action_value",render:({field:m})=>e.jsxs(f,{children:[e.jsx(j,{children:a("form.dns")}),e.jsx("div",{className:"relative",children:e.jsx(y,{children:e.jsx(T,{type:"text",placeholder:a("form.dnsPlaceholder"),...m})})})]})}),e.jsxs(ze,{children:[e.jsx(yt,{asChild:!0,children:e.jsx(P,{variant:"outline",children:a("form.cancel")})}),e.jsx(P,{type:"submit",onClick:()=>{Vc(i.getValues()).then(({data:m})=>{m&&(d(!1),s&&s(),toast.success(a(r==="edit"?"messages.updateSuccess":"messages.createSuccess")),i.reset())})},children:a("form.submit")})]})]})]})]})}function Ex({table:s,refetch:n}){const t=s.getState().columnFilters.length>0,{t:r}=V("route");return e.jsx("div",{className:"flex items-center justify-between ",children:e.jsxs("div",{className:"flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-2",children:[e.jsx(Zr,{refetch:n}),e.jsx(T,{placeholder:r("toolbar.searchPlaceholder"),value:s.getColumn("remarks")?.getFilterValue()??"",onChange:a=>s.getColumn("remarks")?.setFilterValue(a.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),t&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[r("toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]})})}function Rx({columns:s,data:n,refetch:t}){const[r,a]=u.useState({}),[i,l]=u.useState({}),[d,m]=u.useState([]),[o,c]=u.useState([]),h=ns({data:n,columns:s,state:{sorting:o,columnVisibility:i,rowSelection:r,columnFilters:d},enableRowSelection:!0,onRowSelectionChange:a,onSortingChange:c,onColumnFiltersChange:m,onColumnVisibilityChange:l,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(hs,{table:h,toolbar:_=>e.jsx(Ex,{table:_,refetch:t})})}const Ix=s=>{const{t:n}=V("route"),t={block:{icon:$o,variant:"destructive",className:"bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-800"},dns:{icon:Uo,variant:"secondary",className:"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-800"}};return[{accessorKey:"id",header:({column:r})=>e.jsx(O,{column:r,title:n("columns.id")}),cell:({row:r})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(q,{variant:"outline",children:r.getValue("id")})}),enableSorting:!0,enableHiding:!1},{accessorKey:"remarks",header:({column:r})=>e.jsx(O,{column:r,title:n("columns.remarks")}),cell:({row:r})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium sm:max-w-72 md:max-w-[31rem]",children:r.original.remarks})}),enableHiding:!1,enableSorting:!1},{accessorKey:"action_value",header:({column:r})=>e.jsx(O,{column:r,title:n("columns.action_value.title")}),cell:({row:r})=>{const a=r.original.action,i=r.original.action_value,l=r.original.match?.length||0;return e.jsxs("div",{className:"flex flex-col space-y-1",children:[e.jsx("span",{className:"text-sm font-medium",children:a==="dns"&&i?n("columns.action_value.dns",{value:i}):a==="block"?e.jsx("span",{className:"text-destructive",children:n("columns.action_value.block")}):n("columns.action_value.direct")}),e.jsx("span",{className:"text-xs text-muted-foreground",children:n("columns.matchRules",{count:l})})]})},enableHiding:!1,enableSorting:!1,size:300},{accessorKey:"action",header:({column:r})=>e.jsx(O,{column:r,title:n("columns.action")}),cell:({row:r})=>{const a=r.getValue("action"),i=t[a]?.icon;return e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs(q,{variant:t[a]?.variant||"default",className:N("flex items-center gap-1.5 px-3 py-1 capitalize",t[a]?.className),children:[i&&e.jsx(i,{className:"h-3.5 w-3.5"}),n(`actions.${a}`)]})})},enableSorting:!1,size:9e3},{id:"actions",header:()=>e.jsx("div",{className:"text-right",children:n("columns.actions")}),cell:({row:r})=>e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(Zr,{defaultValues:r.original,refetch:s,type:"edit",dialogTrigger:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("form.edit")})]})}),e.jsx(Qe,{title:n("messages.deleteConfirm"),description:n("messages.deleteDescription"),confirmText:n("messages.deleteButton"),variant:"destructive",onConfirm:async()=>{Mc({id:r.original.id}).then(({data:a})=>{a&&(A.success(n("messages.deleteSuccess")),s())})},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("messages.deleteButton")})]})})]})}]};function Vx(){const{t:s}=V("route"),[n,t]=u.useState([]);function r(){Sr().then(({data:a})=>{t(a)})}return u.useEffect(()=>{r()},[]),e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Rx,{data:n,columns:Ix(r),refetch:r})})]})]})}const Mx=Object.freeze(Object.defineProperty({__proto__:null,default:Vx},Symbol.toStringTag,{value:"Module"})),el=u.createContext(void 0);function Fx({children:s,refreshData:n}){const[t,r]=u.useState(!1),[a,i]=u.useState(null);return e.jsx(el.Provider,{value:{isOpen:t,setIsOpen:r,editingPlan:a,setEditingPlan:i,refreshData:n},children:s})}function za(){const s=u.useContext(el);if(s===void 0)throw new Error("usePlanEdit must be used within a PlanEditProvider");return s}function Ox({table:s,saveOrder:n,isSortMode:t}){const{setIsOpen:r}=za(),{t:a}=V("subscribe");return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-1 items-center space-x-2",children:[e.jsxs(P,{variant:"outline",className:"space-x-2",size:"sm",onClick:()=>r(!0),children:[e.jsx(Ve,{icon:"ion:add"}),e.jsx("div",{children:a("plan.add")})]}),e.jsx(T,{placeholder:a("plan.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:i=>s.getColumn("name")?.setFilterValue(i.target.value),className:"h-8 w-[150px] lg:w-[250px]"})]}),s.getRowCount()>0&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(P,{variant:t?"default":"outline",onClick:n,size:"sm",children:a(t?"plan.sort.save":"plan.sort.edit")})})]})}const mn={monthly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},quarterly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},half_yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},two_yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},three_yearly:{color:"text-slate-700",bgColor:"bg-slate-100/80"},onetime:{color:"text-slate-700",bgColor:"bg-slate-100/80"},reset_traffic:{color:"text-slate-700",bgColor:"bg-slate-100/80"}},Lx=s=>{const{t:n}=V("subscribe");return[{id:"drag-handle",header:()=>null,cell:()=>e.jsx("div",{className:"cursor-move",children:e.jsx(Ht,{className:"size-4"})}),size:40,enableSorting:!1},{accessorKey:"id",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.id")}),cell:({row:t})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(q,{variant:"outline",children:t.getValue("id")})}),enableSorting:!0,enableHiding:!1},{accessorKey:"show",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.show")}),cell:({row:t})=>e.jsx(Y,{defaultChecked:t.getValue("show"),onCheckedChange:r=>{aa({id:t.original.id,show:r}).then(({data:a})=>{!a&&s()})}}),enableSorting:!1,enableHiding:!1},{accessorKey:"sell",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.sell")}),cell:({row:t})=>e.jsx(Y,{defaultChecked:t.getValue("sell"),onCheckedChange:r=>{aa({id:t.original.id,sell:r}).then(({data:a})=>{!a&&s()})}}),enableSorting:!1,enableHiding:!1},{accessorKey:"renew",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.renew"),tooltip:n("plan.columns.renew_tooltip")}),cell:({row:t})=>e.jsx(Y,{defaultChecked:t.getValue("renew"),onCheckedChange:r=>{aa({id:t.original.id,renew:r}).then(({data:a})=>{!a&&s()})}}),enableSorting:!1,enableHiding:!1},{accessorKey:"name",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.name")}),cell:({row:t})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium sm:max-w-72 md:max-w-[31rem]",children:t.getValue("name")})}),enableSorting:!1,enableHiding:!1,size:900},{accessorKey:"users_count",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.stats")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center space-x-2 px-2",children:[e.jsx(gt,{}),e.jsx("span",{className:"max-w-32 truncate font-medium sm:max-w-72 md:max-w-[31rem]",children:t.getValue("users_count")})]}),enableSorting:!0},{accessorKey:"group",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.group")}),cell:({row:t})=>e.jsx("div",{className:"flex max-w-[600px] flex-wrap items-center gap-1.5 text-nowrap",children:e.jsx(q,{variant:"secondary",className:N("px-2 py-0.5 font-medium","bg-secondary/50 hover:bg-secondary/70","border border-border/50","transition-all duration-200","cursor-default select-none","flex items-center gap-1.5"),children:t.getValue("group")?.name})}),enableSorting:!1,enableHiding:!1},{accessorKey:"prices",header:({column:t})=>e.jsx(O,{column:t,title:n("plan.columns.price")}),cell:({row:t})=>{const r=t.getValue("prices"),a=[{period:n("plan.columns.price_period.monthly"),key:"monthly",unit:n("plan.columns.price_period.unit.month")},{period:n("plan.columns.price_period.quarterly"),key:"quarterly",unit:n("plan.columns.price_period.unit.quarter")},{period:n("plan.columns.price_period.half_yearly"),key:"half_yearly",unit:n("plan.columns.price_period.unit.half_year")},{period:n("plan.columns.price_period.yearly"),key:"yearly",unit:n("plan.columns.price_period.unit.year")},{period:n("plan.columns.price_period.two_yearly"),key:"two_yearly",unit:n("plan.columns.price_period.unit.two_year")},{period:n("plan.columns.price_period.three_yearly"),key:"three_yearly",unit:n("plan.columns.price_period.unit.three_year")},{period:n("plan.columns.price_period.onetime"),key:"onetime",unit:""},{period:n("plan.columns.price_period.reset_traffic"),key:"reset_traffic",unit:n("plan.columns.price_period.unit.times")}];return e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:a.map(({period:i,key:l,unit:d})=>r[l]!=null&&e.jsxs(q,{variant:"secondary",className:N("px-2 py-0.5 font-medium transition-colors text-nowrap",mn[l].color,mn[l].bgColor,"border border-border/50","hover:bg-slate-200/80"),children:[i," ¥",r[l],d]},l))})},enableSorting:!1,size:9e3},{id:"actions",header:({column:t})=>e.jsx(O,{className:"justify-end",column:t,title:n("plan.columns.actions")}),cell:({row:t})=>{const{setIsOpen:r,setEditingPlan:a}=za();return e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",onClick:()=>{a(t.original),r(!0)},children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("plan.columns.edit")})]}),e.jsx(Qe,{title:n("plan.columns.delete_confirm.title"),description:n("plan.columns.delete_confirm.description"),confirmText:n("plan.columns.delete"),variant:"destructive",onConfirm:async()=>{Zc({id:t.original.id}).then(({data:i})=>{i&&(A.success(n("plan.columns.delete_confirm.success")),s())})},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("plan.columns.delete")})]})})]})}}]},zx=x.object({id:x.number().nullable(),group_id:x.union([x.number(),x.string()]).nullable().optional(),name:x.string().min(1).max(250),content:x.string().nullable().optional(),transfer_enable:x.union([x.number().min(0),x.string().min(1)]),prices:x.object({monthly:x.union([x.number(),x.string()]).nullable().optional(),quarterly:x.union([x.number(),x.string()]).nullable().optional(),half_yearly:x.union([x.number(),x.string()]).nullable().optional(),yearly:x.union([x.number(),x.string()]).nullable().optional(),two_yearly:x.union([x.number(),x.string()]).nullable().optional(),three_yearly:x.union([x.number(),x.string()]).nullable().optional(),onetime:x.union([x.number(),x.string()]).nullable().optional(),reset_traffic:x.union([x.number(),x.string()]).nullable().optional()}).default({}),speed_limit:x.union([x.number(),x.string()]).nullable().optional(),capacity_limit:x.union([x.number(),x.string()]).nullable().optional(),device_limit:x.union([x.number(),x.string()]).nullable().optional(),force_update:x.boolean().optional(),reset_traffic_method:x.number().nullable(),users_count:x.number().optional()}),sl=u.forwardRef(({className:s,...n},t)=>e.jsx(mr,{ref:t,className:N("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",s),...n,children:e.jsx(Ho,{className:N("flex items-center justify-center text-current"),children:e.jsx($s,{className:"h-4 w-4"})})}));sl.displayName=mr.displayName;const St={id:null,group_id:null,name:"",content:"",transfer_enable:"",prices:{monthly:"",quarterly:"",half_yearly:"",yearly:"",two_yearly:"",three_yearly:"",onetime:"",reset_traffic:""},speed_limit:"",capacity_limit:"",device_limit:"",force_update:!1,reset_traffic_method:null},kt={monthly:{label:"月付",months:1,discount:1},quarterly:{label:"季付",months:3,discount:.95},half_yearly:{label:"半年付",months:6,discount:.9},yearly:{label:"年付",months:12,discount:.85},two_yearly:{label:"两年付",months:24,discount:.8},three_yearly:{label:"三年付",months:36,discount:.75},onetime:{label:"流量包",months:1,discount:1},reset_traffic:{label:"重置包",months:1,discount:1}},Ax=[{value:null,label:"follow_system"},{value:0,label:"monthly_first"},{value:1,label:"monthly_reset"},{value:2,label:"no_reset"},{value:3,label:"yearly_first"},{value:4,label:"yearly_reset"}];function $x(){const{isOpen:s,setIsOpen:n,editingPlan:t,setEditingPlan:r,refreshData:a}=za(),[i,l]=u.useState(!1),{t:d}=V("subscribe"),m=ge({resolver:Ne(zx),defaultValues:{...St,...t||{}},mode:"onChange"});u.useEffect(()=>{t?m.reset({...St,...t}):m.reset(St)},[t,m]);const o=new Pa({html:!0}),[c,h]=u.useState();async function _(){bt().then(({data:S})=>{h(S)})}u.useEffect(()=>{s&&_()},[s]);const E=S=>{if(isNaN(S))return;const w=Object.entries(kt).reduce((b,[k,p])=>{const v=S*p.months*p.discount;return{...b,[k]:v.toFixed(2)}},{});m.setValue("prices",w,{shouldDirty:!0})},C=()=>{n(!1),r(null),m.reset(St)};return e.jsx(be,{open:s,onOpenChange:C,children:e.jsxs(fe,{children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:d(t?"plan.form.edit_title":"plan.form.add_title")}),e.jsx(Te,{})]}),e.jsxs(_e,{...m,children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(g,{control:m.control,name:"name",render:({field:S})=>e.jsxs(f,{children:[e.jsx(j,{children:d("plan.form.name.label")}),e.jsx(y,{children:e.jsx(T,{placeholder:d("plan.form.name.placeholder"),...S})}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"group_id",render:({field:S})=>e.jsxs(f,{children:[e.jsxs(j,{className:"flex items-center justify-between",children:[d("plan.form.group.label"),e.jsx(ta,{dialogTrigger:e.jsx(P,{variant:"link",children:d("plan.form.group.add")}),refetch:_})]}),e.jsxs(G,{value:S.value?.toString()??"",onValueChange:w=>S.onChange(w?Number(w):null),children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:d("plan.form.group.placeholder")})})}),e.jsx(B,{children:c?.map(w=>e.jsx(z,{value:w.id.toString(),children:w.name},w.id))})]}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"transfer_enable",render:({field:S})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:d("plan.form.transfer.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(y,{children:e.jsx(T,{type:"number",min:0,placeholder:d("plan.form.transfer.placeholder"),className:"rounded-r-none",...S})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:d("plan.form.transfer.unit")})]}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"speed_limit",render:({field:S})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:d("plan.form.speed.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(y,{children:e.jsx(T,{type:"number",min:0,placeholder:d("plan.form.speed.placeholder"),className:"rounded-r-none",...S,value:S.value??""})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:d("plan.form.speed.unit")})]}),e.jsx(D,{})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-1 items-center",children:[e.jsx("div",{className:"flex-grow border-t border-gray-200 dark:border-gray-700"}),e.jsx("h3",{className:"mx-4 text-sm font-medium text-gray-500 dark:text-gray-400",children:d("plan.form.price.title")}),e.jsx("div",{className:"flex-grow border-t border-gray-200 dark:border-gray-700"})]}),e.jsxs("div",{className:"ml-4 flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2",children:e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"¥"})}),e.jsx(T,{type:"number",placeholder:d("plan.form.price.base_price"),className:"h-7 w-32 border-0 bg-gray-50 pl-6 pr-2 text-sm shadow-none ring-1 ring-gray-200 transition-shadow focus-visible:ring-2 focus-visible:ring-primary dark:bg-gray-800/50 dark:ring-gray-700 dark:placeholder:text-gray-500",onChange:S=>{const w=parseFloat(S.target.value);E(w)}})]}),e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(P,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{const S=Object.keys(kt).reduce((w,b)=>({...w,[b]:""}),{});m.setValue("prices",S,{shouldDirty:!0})},children:d("plan.form.price.clear.button")})}),e.jsx(ce,{side:"top",align:"end",children:e.jsx("p",{className:"text-xs",children:d("plan.form.price.clear.tooltip")})})]})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-3",children:Object.entries(kt).filter(([S])=>!["onetime","reset_traffic"].includes(S)).map(([S,w])=>e.jsx("div",{className:"group relative rounded-md bg-card p-2 ring-1 ring-gray-200 transition-all hover:ring-primary dark:ring-gray-800",children:e.jsx(g,{control:m.control,name:`prices.${S}`,render:({field:b})=>e.jsxs(f,{children:[e.jsxs(j,{className:"text-xs font-medium text-muted-foreground",children:[d(`plan.columns.price_period.${S}`),e.jsxs("span",{className:"ml-1 text-[10px] text-gray-400",children:["(",w.months===1?d("plan.form.price.period.monthly"):d("plan.form.price.period.months",{count:w.months}),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2",children:e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"¥"})}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:"0.00",min:0,...b,value:b.value??"",onChange:k=>b.onChange(k.target.value),className:"h-7 border-0 bg-gray-50 pl-6 pr-2 text-sm shadow-none ring-1 ring-gray-200 transition-shadow focus-visible:ring-2 focus-visible:ring-primary dark:bg-gray-800/50 dark:ring-gray-700 dark:placeholder:text-gray-500"})})]})]})})},S))}),e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:Object.entries(kt).filter(([S])=>["onetime","reset_traffic"].includes(S)).map(([S,w])=>e.jsx("div",{className:"rounded-md border border-dashed border-gray-200 bg-muted/30 p-3 dark:border-gray-700",children:e.jsx(g,{control:m.control,name:`prices.${S}`,render:({field:b})=>e.jsx(f,{children:e.jsxs("div",{className:"flex flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-0",children:[e.jsx(j,{className:"text-xs font-medium",children:d(`plan.columns.price_period.${S}`)}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:d(S==="onetime"?"plan.form.price.onetime_desc":"plan.form.price.reset_desc")})]}),e.jsxs("div",{className:"relative w-full md:w-32",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2",children:e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"¥"})}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:"0.00",min:0,...b,className:"h-7 border-0 bg-gray-50 pl-6 pr-2 text-sm shadow-none ring-1 ring-gray-200 transition-shadow focus-visible:ring-2 focus-visible:ring-primary dark:bg-gray-800/50 dark:ring-gray-700 dark:placeholder:text-gray-500"})})]})]})})})},S))})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(g,{control:m.control,name:"device_limit",render:({field:S})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:d("plan.form.device.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(y,{children:e.jsx(T,{type:"number",min:0,placeholder:d("plan.form.device.placeholder"),className:"rounded-r-none",...S,value:S.value??""})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:d("plan.form.device.unit")})]}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"capacity_limit",render:({field:S})=>e.jsxs(f,{className:"flex-1",children:[e.jsx(j,{children:d("plan.form.capacity.label")}),e.jsxs("div",{className:"relative flex",children:[e.jsx(y,{children:e.jsx(T,{type:"number",min:0,placeholder:d("plan.form.capacity.placeholder"),className:"rounded-r-none",...S,value:S.value??""})}),e.jsx("div",{className:"flex items-center rounded-r-md border border-l-0 border-input bg-muted px-3 text-sm text-muted-foreground",children:d("plan.form.capacity.unit")})]}),e.jsx(D,{})]})})]}),e.jsx(g,{control:m.control,name:"reset_traffic_method",render:({field:S})=>e.jsxs(f,{children:[e.jsx(j,{children:d("plan.form.reset_method.label")}),e.jsxs(G,{value:S.value?.toString()??"null",onValueChange:w=>S.onChange(w=="null"?null:Number(w)),children:[e.jsx(y,{children:e.jsx(K,{children:e.jsx(W,{placeholder:d("plan.form.reset_method.placeholder")})})}),e.jsx(B,{children:Ax.map(w=>e.jsx(z,{value:w.value?.toString()??"null",children:d(`plan.form.reset_method.options.${w.label}`)},w.value))})]}),e.jsx(F,{className:"text-xs",children:d("plan.form.reset_method.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:m.control,name:"content",render:({field:S})=>{const[w,b]=u.useState(!1);return e.jsxs(f,{className:"space-y-2",children:[e.jsxs(j,{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d("plan.form.content.label"),e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(P,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>b(!w),children:w?e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-4 w-4",children:[e.jsx("path",{d:"M10 12.5a2.5 2.5 0 100-5 2.5 2.5 0 000 5z"}),e.jsx("path",{fillRule:"evenodd",d:"M.664 10.59a1.651 1.651 0 010-1.186A10.004 10.004 0 0110 3c4.257 0 7.893 2.66 9.336 6.41.147.381.146.804 0 1.186A10.004 10.004 0 0110 17c-4.257 0-7.893-2.66-9.336-6.41zM14 10a4 4 0 11-8 0 4 4 0 018 0z",clipRule:"evenodd"})]}):e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-4 w-4",children:[e.jsx("path",{fillRule:"evenodd",d:"M3.28 2.22a.75.75 0 00-1.06 1.06l14.5 14.5a.75.75 0 101.06-1.06l-1.745-1.745a10.029 10.029 0 003.3-4.38 1.651 1.651 0 000-1.185A10.004 10.004 0 009.999 3a9.956 9.956 0 00-4.744 1.194L3.28 2.22zM7.752 6.69l1.092 1.092a2.5 2.5 0 013.374 3.373l1.091 1.092a4 4 0 00-5.557-5.557z",clipRule:"evenodd"}),e.jsx("path",{d:"M10.748 13.93l2.523 2.523a9.987 9.987 0 01-3.27.547c-4.258 0-7.894-2.66-9.337-6.41a1.651 1.651 0 010-1.186A10.007 10.007 0 012.839 6.02L6.07 9.252a4 4 0 004.678 4.678z"})]})})}),e.jsx(ce,{side:"top",children:e.jsx("p",{className:"text-xs",children:d(w?"plan.form.content.preview_button.hide":"plan.form.content.preview_button.show")})})]})})]}),e.jsx(ve,{children:e.jsxs(he,{children:[e.jsx(pe,{asChild:!0,children:e.jsx(P,{variant:"outline",size:"sm",onClick:()=>{S.onChange(d("plan.form.content.template.content"))},children:d("plan.form.content.template.button")})}),e.jsx(ce,{side:"left",align:"center",children:e.jsx("p",{className:"text-xs",children:d("plan.form.content.template.tooltip")})})]})})]}),e.jsxs("div",{className:`grid gap-4 ${w?"grid-cols-1 lg:grid-cols-2":"grid-cols-1"}`,children:[e.jsx("div",{className:"space-y-2",children:e.jsx(y,{children:e.jsx(Ea,{style:{height:"400px"},value:S.value||"",renderHTML:k=>o.render(k),onChange:({text:k})=>S.onChange(k),config:{view:{menu:!0,md:!0,html:!1},canView:{menu:!0,md:!0,html:!1,fullScreen:!1,hideMenu:!1}},placeholder:d("plan.form.content.placeholder"),className:"rounded-md border"})})}),w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:d("plan.form.content.preview")}),e.jsx("div",{className:"prose prose-sm dark:prose-invert h-[400px] max-w-none overflow-y-auto rounded-md border p-4",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:o.render(S.value||"")}})})]})]}),e.jsx(F,{className:"text-xs",children:d("plan.form.content.description")}),e.jsx(D,{})]})}})]}),e.jsx(ze,{className:"mt-6",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("div",{className:"flex-shrink-0",children:t&&e.jsx(g,{control:m.control,name:"force_update",render:({field:S})=>e.jsxs(f,{className:"flex flex-row items-center space-x-2 space-y-0",children:[e.jsx(y,{children:e.jsx(sl,{checked:S.value,onCheckedChange:S.onChange})}),e.jsx("div",{className:"",children:e.jsx(j,{className:"text-sm",children:d("plan.form.force_update.label")})})]})})}),e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(P,{type:"button",variant:"outline",onClick:C,children:d("plan.form.submit.cancel")}),e.jsx(P,{type:"submit",disabled:i,onClick:()=>{m.handleSubmit(async S=>{l(!0),(await Xc(S)).data&&(A.success(d(t?"plan.form.submit.success.update":"plan.form.submit.success.add")),C(),a()),l(!1)})()},children:d(i?"plan.form.submit.submitting":"plan.form.submit.submit")})]})]})})]})]})})}function Ux(){const[s,n]=u.useState({}),[t,r]=u.useState({"drag-handle":!1}),[a,i]=u.useState([]),[l,d]=u.useState([]),[m,o]=u.useState(!1),[c,h]=u.useState({pageSize:20,pageIndex:0}),[_,E]=u.useState([]),{refetch:C}=re({queryKey:["planList"],queryFn:async()=>{const{data:p}=await qs();return E(p),p}});u.useEffect(()=>{r({"drag-handle":m}),h({pageSize:m?99999:10,pageIndex:0})},[m]);const S=(p,v)=>{m&&(p.dataTransfer.setData("text/plain",v.toString()),p.currentTarget.classList.add("opacity-50"))},w=(p,v)=>{if(!m)return;p.preventDefault(),p.currentTarget.classList.remove("bg-muted");const M=parseInt(p.dataTransfer.getData("text/plain"));if(M===v)return;const H=[..._],[se]=H.splice(M,1);H.splice(v,0,se),E(H)},b=async()=>{if(!m){o(!0);return}const p=_?.map(v=>v.id);ed(p).then(()=>{A.success("排序保存成功"),o(!1),C()}).finally(()=>{o(!1)})},k=ns({data:_||[],columns:Lx(C),state:{sorting:l,columnVisibility:t,rowSelection:s,columnFilters:a,pagination:c},enableRowSelection:!0,onPaginationChange:h,onRowSelectionChange:n,onSortingChange:d,onColumnFiltersChange:i,onColumnVisibilityChange:r,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}},pageCount:m?1:void 0});return e.jsx(Fx,{refreshData:C,children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(hs,{table:k,toolbar:p=>e.jsx(Ox,{table:p,refetch:C,saveOrder:b,isSortMode:m}),draggable:m,onDragStart:S,onDragEnd:p=>p.currentTarget.classList.remove("opacity-50"),onDragOver:p=>{p.preventDefault(),p.currentTarget.classList.add("bg-muted")},onDragLeave:p=>p.currentTarget.classList.remove("bg-muted"),onDrop:w,showPagination:!m}),e.jsx($x,{})]})})}function Hx(){const{t:s}=V("subscribe");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("plan.title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("plan.page.description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(Ux,{})})]})]})}const qx=Object.freeze(Object.defineProperty({__proto__:null,default:Hx},Symbol.toStringTag,{value:"Module"})),Js=[{value:ae.PENDING,label:ot[ae.PENDING],icon:qo,color:ct[ae.PENDING]},{value:ae.PROCESSING,label:ot[ae.PROCESSING],icon:xr,color:ct[ae.PROCESSING]},{value:ae.COMPLETED,label:ot[ae.COMPLETED],icon:ja,color:ct[ae.COMPLETED]},{value:ae.CANCELLED,label:ot[ae.CANCELLED],icon:hr,color:ct[ae.CANCELLED]},{value:ae.DISCOUNTED,label:ot[ae.DISCOUNTED],icon:ja,color:ct[ae.DISCOUNTED]}],ut=[{value:xe.PENDING,label:Nt[xe.PENDING],icon:Ko,color:_t[xe.PENDING]},{value:xe.PROCESSING,label:Nt[xe.PROCESSING],icon:xr,color:_t[xe.PROCESSING]},{value:xe.VALID,label:Nt[xe.VALID],icon:ja,color:_t[xe.VALID]},{value:xe.INVALID,label:Nt[xe.INVALID],icon:hr,color:_t[xe.INVALID]}];function Tt({column:s,title:n,options:t}){const r=s?.getFacetedUniqueValues(),a=s?.getFilterValue(),i=Array.isArray(a)?new Set(a):a!==void 0?new Set([a]):new Set;return e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),n,i?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:i.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:i.size>2?e.jsxs(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[i.size," selected"]}):t.filter(l=>i.has(l.value)).map(l=>e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:l.label},l.value))})]})]})}),e.jsx(xs,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Ms,{children:[e.jsx(Ks,{placeholder:n}),e.jsxs(Fs,{children:[e.jsx(Bs,{children:"No results found."}),e.jsx(Ye,{children:t.map(l=>{const d=i.has(l.value);return e.jsxs(Me,{onSelect:()=>{const m=new Set(i);d?m.delete(l.value):m.add(l.value);const o=Array.from(m);s?.setFilterValue(o.length?o:void 0)},children:[e.jsx("div",{className:N("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",d?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx($s,{className:N("h-4 w-4")})}),l.icon&&e.jsx(l.icon,{className:`mr-2 h-4 w-4 text-muted-foreground text-${l.color}`}),e.jsx("span",{children:l.label}),r?.get(l.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(l.value)})]},l.value)})}),i.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx(Ye,{children:e.jsx(Me,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}const Kx=x.object({email:x.string().min(1),plan_id:x.number(),period:x.string(),total_amount:x.number()}),Bx={email:"",plan_id:0,total_amount:0,period:""};function tl({refetch:s,trigger:n,defaultValues:t}){const{t:r}=V("order"),[a,i]=u.useState(!1),l=ge({resolver:Ne(Kx),defaultValues:{...Bx,...t},mode:"onChange"}),[d,m]=u.useState([]);return u.useEffect(()=>{a&&qs().then(({data:o})=>{m(o)})},[a]),e.jsxs(be,{open:a,onOpenChange:i,children:[e.jsx(Je,{asChild:!0,children:n||e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 space-x-2",children:[e.jsx(Ve,{icon:"ion:add"}),e.jsx("div",{children:r("dialog.addOrder")})]})}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:r("dialog.assignOrder")}),e.jsx(Te,{})]}),e.jsxs(_e,{...l,children:[e.jsx(g,{control:l.control,name:"email",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dialog.fields.userEmail")}),e.jsx(y,{children:e.jsx(T,{placeholder:r("dialog.placeholders.email"),...o})})]})}),e.jsx(g,{control:l.control,name:"plan_id",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dialog.fields.subscriptionPlan")}),e.jsx(y,{children:e.jsxs(G,{value:o.value?o.value?.toString():void 0,onValueChange:c=>o.onChange(parseInt(c)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dialog.placeholders.plan")})}),e.jsx(B,{children:d.map(c=>e.jsx(z,{value:c.id.toString(),children:c.name},c.id))})]})})]})}),e.jsx(g,{control:l.control,name:"period",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dialog.fields.orderPeriod")}),e.jsx(y,{children:e.jsxs(G,{value:o.value,onValueChange:o.onChange,children:[e.jsx(K,{children:e.jsx(W,{placeholder:r("dialog.placeholders.period")})}),e.jsx(B,{children:Object.keys(fu).map(c=>e.jsx(z,{value:c,children:r(`period.${c}`)},c))})]})})]})}),e.jsx(g,{control:l.control,name:"total_amount",render:({field:o})=>e.jsxs(f,{children:[e.jsx(j,{children:r("dialog.fields.paymentAmount")}),e.jsx(y,{children:e.jsx(T,{type:"number",placeholder:r("dialog.placeholders.amount"),value:o.value/100,onChange:c=>o.onChange(parseFloat(c.currentTarget.value)*100)})}),e.jsx(D,{})]})}),e.jsxs(ze,{children:[e.jsx(P,{variant:"outline",onClick:()=>i(!1),children:r("dialog.actions.cancel")}),e.jsx(P,{type:"submit",onClick:()=>{l.handleSubmit(o=>{rd(o).then(({data:c})=>{c&&(s&&s(),l.reset(),i(!1),A.success(r("dialog.messages.addSuccess")))})})()},children:r("dialog.actions.confirm")})]})]})]})]})}function Gx({table:s,refetch:n}){const{t}=V("order"),r=s.getState().columnFilters.length>0,a=Object.values(os).filter(m=>typeof m=="number").map(m=>({label:t(`type.${os[m]}`),value:m,color:m===os.NEW?"green-500":m===os.RENEWAL?"blue-500":m===os.UPGRADE?"purple-500":"orange-500"})),i=Object.values(Pe).map(m=>({label:t(`period.${m}`),value:m,color:m===Pe.MONTH_PRICE?"slate-500":m===Pe.QUARTER_PRICE?"cyan-500":m===Pe.HALF_YEAR_PRICE?"indigo-500":m===Pe.YEAR_PRICE?"violet-500":m===Pe.TWO_YEAR_PRICE?"fuchsia-500":m===Pe.THREE_YEAR_PRICE?"pink-500":m===Pe.ONETIME_PRICE?"rose-500":"orange-500"})),l=Object.values(ae).filter(m=>typeof m=="number").map(m=>({label:t(`status.${ae[m]}`),value:m,icon:m===ae.PENDING?Js[0].icon:m===ae.PROCESSING?Js[1].icon:m===ae.COMPLETED?Js[2].icon:m===ae.CANCELLED?Js[3].icon:Js[4].icon,color:m===ae.PENDING?"yellow-500":m===ae.PROCESSING?"blue-500":m===ae.COMPLETED?"green-500":m===ae.CANCELLED?"red-500":"green-500"})),d=Object.values(xe).filter(m=>typeof m=="number").map(m=>({label:t(`commission.${xe[m]}`),value:m,icon:m===xe.PENDING?ut[0].icon:m===xe.PROCESSING?ut[1].icon:m===xe.VALID?ut[2].icon:ut[3].icon,color:m===xe.PENDING?"yellow-500":m===xe.PROCESSING?"blue-500":m===xe.VALID?"green-500":"red-500"}));return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(tl,{refetch:n}),e.jsx(T,{placeholder:t("search.placeholder"),value:s.getColumn("trade_no")?.getFilterValue()??"",onChange:m=>s.getColumn("trade_no")?.setFilterValue(m.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),e.jsxs("div",{className:"flex flex-wrap gap-x-2",children:[s.getColumn("type")&&e.jsx(Tt,{column:s.getColumn("type"),title:t("table.columns.type"),options:a}),s.getColumn("period")&&e.jsx(Tt,{column:s.getColumn("period"),title:t("table.columns.period"),options:i}),s.getColumn("status")&&e.jsx(Tt,{column:s.getColumn("status"),title:t("table.columns.status"),options:l}),s.getColumn("commission_status")&&e.jsx(Tt,{column:s.getColumn("commission_status"),title:t("table.columns.commissionStatus"),options:d})]}),r&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[t("actions.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]})}function ls({label:s,value:n,className:t,valueClassName:r}){return e.jsxs("div",{className:N("flex items-center py-1.5",t),children:[e.jsx("div",{className:"w-28 shrink-0 text-sm text-muted-foreground",children:s}),e.jsx("div",{className:N("text-sm",r),children:n||"-"})]})}function Wx({status:s}){const{t:n}=V("order"),t={[ae.PENDING]:"bg-yellow-100 text-yellow-800 hover:bg-yellow-100",[ae.PROCESSING]:"bg-blue-100 text-blue-800 hover:bg-blue-100",[ae.CANCELLED]:"bg-red-100 text-red-800 hover:bg-red-100",[ae.COMPLETED]:"bg-green-100 text-green-800 hover:bg-green-100",[ae.DISCOUNTED]:"bg-gray-100 text-gray-800 hover:bg-gray-100"};return e.jsx(q,{variant:"secondary",className:N("font-medium",t[s]),children:n(`status.${ae[s]}`)})}function Yx({id:s,trigger:n}){const[t,r]=u.useState(!1),[a,i]=u.useState(),{t:l}=V("order");return u.useEffect(()=>{(async()=>{if(t){const{data:m}=await td({id:s});i(m)}})()},[t,s]),e.jsxs(be,{onOpenChange:r,open:t,children:[e.jsx(Je,{asChild:!0,children:n}),e.jsxs(fe,{className:"max-w-xl",children:[e.jsxs(Ce,{className:"space-y-2",children:[e.jsx(ye,{className:"text-lg font-medium",children:l("dialog.title")}),e.jsx("div",{className:"flex items-center justify-between text-sm",children:e.jsxs("div",{className:"flex items-center space-x-6",children:[e.jsxs("div",{className:"text-muted-foreground",children:[l("table.columns.tradeNo"),":",a?.trade_no]}),a?.status&&e.jsx(Wx,{status:a.status})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:l("dialog.basicInfo")}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ls,{label:l("dialog.fields.userEmail"),value:a?.user?.email?e.jsxs(Us,{to:`/user/manage?email=${a.user.email}`,className:"group inline-flex items-center gap-1 text-primary hover:underline",children:[a.user.email,e.jsx(pr,{className:"h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}):"-"}),e.jsx(ls,{label:l("dialog.fields.orderPeriod"),value:a&&l(`period.${a.period}`)}),e.jsx(ls,{label:l("dialog.fields.subscriptionPlan"),value:a?.plan?.name,valueClassName:"font-medium"}),e.jsx(ls,{label:l("dialog.fields.callbackNo"),value:a?.callback_no,valueClassName:"font-mono text-xs"})]})]}),e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:l("dialog.amountInfo")}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ls,{label:l("dialog.fields.paymentAmount"),value:Ls(a?.total_amount||0),valueClassName:"font-medium text-primary"}),e.jsx(ke,{className:"my-2"}),e.jsx(ls,{label:l("dialog.fields.balancePayment"),value:Ls(a?.balance_amount||0)}),e.jsx(ls,{label:l("dialog.fields.discountAmount"),value:Ls(a?.discount_amount||0),valueClassName:"text-green-600"}),e.jsx(ls,{label:l("dialog.fields.refundAmount"),value:Ls(a?.refund_amount||0),valueClassName:"text-red-600"}),e.jsx(ls,{label:l("dialog.fields.deductionAmount"),value:Ls(a?.surplus_amount||0)})]})]}),e.jsxs("div",{className:"rounded-lg border p-4",children:[e.jsx("div",{className:"mb-2 text-sm font-medium",children:l("dialog.timeInfo")}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ls,{label:l("dialog.fields.createdAt"),value:we(a?.created_at),valueClassName:"font-mono text-xs"}),e.jsx(ls,{label:l("dialog.fields.updatedAt"),value:we(a?.updated_at),valueClassName:"font-mono text-xs"})]})]})]})]})]})}const Qx={[os.NEW]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[os.RENEWAL]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[os.UPGRADE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[os.RESET_FLOW]:{color:"text-slate-700",bgColor:"bg-slate-100/80"}},Jx={[Pe.MONTH_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.QUARTER_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.HALF_YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.TWO_YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.THREE_YEAR_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.ONETIME_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"},[Pe.RESET_PRICE]:{color:"text-slate-700",bgColor:"bg-slate-100/80"}},Xx=s=>ae[s],Zx=s=>xe[s],eh=s=>os[s],sh=s=>{const{t:n}=V("order");return[{accessorKey:"trade_no",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.tradeNo")}),cell:({row:t})=>{const r=t.original.trade_no,a=r.length>6?`${r.slice(0,3)}...${r.slice(-3)}`:r;return e.jsx("div",{className:"flex items-center",children:e.jsx(Yx,{trigger:e.jsxs(J,{variant:"ghost",size:"sm",className:"flex h-8 items-center gap-1.5 px-2 font-medium text-primary transition-colors hover:bg-primary/10 hover:text-primary/80",children:[e.jsx("span",{className:"font-mono",children:a}),e.jsx(pr,{className:"h-3.5 w-3.5 opacity-70"})]}),id:t.original.id})})},enableSorting:!1,enableHiding:!1},{accessorKey:"type",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.type")}),cell:({row:t})=>{const r=t.getValue("type"),a=Qx[r];return e.jsx(q,{variant:"secondary",className:N("font-medium transition-colors text-nowrap",a.color,a.bgColor,"border border-border/50","hover:bg-slate-200/80"),children:n(`type.${eh(r)}`)})},enableSorting:!1,enableHiding:!1},{accessorKey:"plan.name",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.plan")}),cell:({row:t})=>e.jsx("div",{className:"flex space-x-2",children:e.jsx("span",{className:"max-w-32 truncate font-medium text-foreground/90 sm:max-w-72 md:max-w-[31rem]",children:t.original.plan?.name||"-"})}),enableSorting:!1,enableHiding:!1},{accessorKey:"period",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.period")}),cell:({row:t})=>{const r=t.getValue("period"),a=Jx[r];return e.jsx(q,{variant:"secondary",className:N("font-medium transition-colors text-nowrap",a.color,a.bgColor,"hover:bg-opacity-80"),children:n(`period.${r}`)})},enableSorting:!1,enableHiding:!1},{accessorKey:"total_amount",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.amount")}),cell:({row:t})=>{const r=t.getValue("total_amount"),a=typeof r=="number"?(r/100).toFixed(2):"N/A";return e.jsxs("div",{className:"flex items-center font-mono text-foreground/90",children:["¥",a]})},enableSorting:!0,enableHiding:!1},{accessorKey:"status",header:({column:t})=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(O,{column:t,title:n("table.columns.status")}),e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{children:e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground/70 transition-colors hover:text-muted-foreground"})}),e.jsx(ce,{side:"top",className:"max-w-[200px] text-sm",children:n("status.tooltip")})]})})]}),cell:({row:t})=>{const r=Js.find(a=>a.value===t.getValue("status"));return r?e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r.icon&&e.jsx(r.icon,{className:`h-4 w-4 text-${r.color}`}),e.jsx("span",{className:"text-sm font-medium",children:n(`status.${Xx(r.value)}`)})]}),r.value===ae.PENDING&&e.jsxs(Ss,{modal:!0,children:[e.jsx(ks,{asChild:!0,children:e.jsxs(J,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 hover:bg-muted/60",children:[e.jsx(Vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:n("actions.openMenu")})]})}),e.jsxs(fs,{align:"end",className:"w-[140px]",children:[e.jsx(je,{className:"cursor-pointer",onClick:async()=>{await ad({trade_no:t.original.trade_no}),s()},children:n("actions.markAsPaid")}),e.jsx(je,{className:"cursor-pointer text-destructive focus:text-destructive",onClick:async()=>{await nd({trade_no:t.original.trade_no}),s()},children:n("actions.cancel")})]})]})]}):null},enableSorting:!0,enableHiding:!1},{accessorKey:"commission_balance",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.commission")}),cell:({row:t})=>{const r=t.getValue("commission_balance"),a=r?(r/100).toFixed(2):"-";return e.jsx("div",{className:"flex items-center font-mono text-foreground/90",children:r?`¥${a}`:"-"})},enableSorting:!0,enableHiding:!1},{accessorKey:"commission_status",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.commissionStatus")}),cell:({row:t})=>{const r=t.original.status,a=t.original.commission_balance,i=ut.find(l=>l.value===t.getValue("commission_status"));return a==0||!i?e.jsx("span",{className:"text-muted-foreground",children:"-"}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.icon&&e.jsx(i.icon,{className:`h-4 w-4 text-${i.color}`}),e.jsx("span",{className:"text-sm font-medium",children:n(`commission.${Zx(i.value)}`)})]}),i.value===xe.PENDING&&r===ae.COMPLETED&&e.jsxs(Ss,{modal:!0,children:[e.jsx(ks,{asChild:!0,children:e.jsxs(J,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 hover:bg-muted/60",children:[e.jsx(Vt,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:n("actions.openMenu")})]})}),e.jsxs(fs,{align:"end",className:"w-[120px]",children:[e.jsx(je,{className:"cursor-pointer",onClick:async()=>{await an({trade_no:t.original.trade_no,commission_status:xe.PROCESSING}),s()},children:n("commission.PROCESSING")}),e.jsx(je,{className:"cursor-pointer text-destructive focus:text-destructive",onClick:async()=>{await an({trade_no:t.original.trade_no,commission_status:xe.INVALID}),s()},children:n("commission.INVALID")})]})]})]})},enableSorting:!0,enableHiding:!1},{accessorKey:"created_at",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.createdAt")}),cell:({row:t})=>e.jsx("div",{className:"text-nowrap font-mono text-sm text-muted-foreground",children:we(t.getValue("created_at"),"YYYY/MM/DD HH:mm:ss")}),enableSorting:!0,enableHiding:!1}]};function th(){const[s]=fr(),[n,t]=u.useState({}),[r,a]=u.useState({}),[i,l]=u.useState([]),[d,m]=u.useState([]),[o,c]=u.useState({pageIndex:0,pageSize:20});u.useEffect(()=>{const w=Object.entries({user_id:"string",order_id:"string",commission_status:"number",status:"number",commission_balance:"string"}).map(([b,k])=>{const p=s.get(b);return p?{id:b,value:k==="number"?parseInt(p):p}:null}).filter(Boolean);w.length>0&&l(w)},[s]);const{refetch:h,data:_,isLoading:E}=re({queryKey:["orderList",o,i,d],queryFn:()=>sd({pageSize:o.pageSize,current:o.pageIndex+1,filter:i,sort:d})}),C=ns({data:_?.data??[],columns:sh(h),state:{sorting:d,columnVisibility:r,rowSelection:n,columnFilters:i,pagination:o},rowCount:_?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:t,onSortingChange:m,onColumnFiltersChange:l,onColumnVisibilityChange:a,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),onPaginationChange:c,getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(hs,{table:C,toolbar:e.jsx(Gx,{table:C,refetch:h}),showPagination:!0})}function ah(){const{t:s}=V("order");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"text-muted-foreground mt-2",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(th,{})})]})]})}const nh=Object.freeze(Object.defineProperty({__proto__:null,default:ah},Symbol.toStringTag,{value:"Module"}));function rh({column:s,title:n,options:t}){const r=s?.getFacetedUniqueValues(),a=new Set(s?.getFilterValue());return e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),n,a?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:a.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:a.size>2?e.jsxs(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[a.size," selected"]}):t.filter(i=>a.has(i.value)).map(i=>e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:i.label},i.value))})]})]})}),e.jsx(xs,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Ms,{children:[e.jsx(Ks,{placeholder:n}),e.jsxs(Fs,{children:[e.jsx(Bs,{children:"No results found."}),e.jsx(Ye,{children:t.map(i=>{const l=a.has(i.value);return e.jsxs(Me,{onSelect:()=>{l?a.delete(i.value):a.add(i.value);const d=Array.from(a);s?.setFilterValue(d.length?d:void 0)},children:[e.jsx("div",{className:N("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",l?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx($s,{className:N("h-4 w-4")})}),i.icon&&e.jsx(i.icon,{className:`mr-2 h-4 w-4 text-muted-foreground text-${i.color}`}),e.jsx("span",{children:i.label}),r?.get(i.value)&&e.jsx("span",{className:"ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs",children:r.get(i.value)})]},i.value)})}),a.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx(Ye,{children:e.jsx(Me,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}const lh=x.object({id:x.coerce.number().nullable().optional(),name:x.string().min(1,"请输入优惠券名称"),code:x.string().nullable(),type:x.coerce.number(),value:x.coerce.number(),started_at:x.coerce.number(),ended_at:x.coerce.number(),limit_use:x.union([x.string(),x.number()]).nullable(),limit_use_with_user:x.union([x.string(),x.number()]).nullable(),generate_count:x.coerce.number().nullable().optional(),limit_plan_ids:x.array(x.coerce.number()).default([]).nullable(),limit_period:x.array(x.nativeEnum(xt)).default([]).nullable()}).refine(s=>s.ended_at>s.started_at,{message:"结束时间必须晚于开始时间",path:["ended_at"]}),xn={name:"",code:null,type:Be.AMOUNT,value:0,started_at:Math.floor(Date.now()/1e3),ended_at:Math.floor(Date.now()/1e3)+7*24*60*60,limit_use:null,limit_use_with_user:null,limit_plan_ids:[],limit_period:[],generate_count:null};function al({defaultValues:s,refetch:n,type:t="create",dialogTrigger:r=null,open:a,onOpenChange:i}){const{t:l}=V("coupon"),[d,m]=u.useState(!1),o=a??d,c=i??m,[h,_]=u.useState([]),E=ge({resolver:Ne(lh),defaultValues:s||xn});u.useEffect(()=>{s&&E.reset(s)},[s,E]),u.useEffect(()=>{qs().then(({data:b})=>_(b))},[]);const C=b=>{if(!b)return;const k=(p,v)=>{const M=new Date(v*1e3);return p.setHours(M.getHours(),M.getMinutes(),M.getSeconds()),Math.floor(p.getTime()/1e3)};b.from&&E.setValue("started_at",k(b.from,E.watch("started_at"))),b.to&&E.setValue("ended_at",k(b.to,E.watch("ended_at")))},S=async b=>{const k=await id(b);if(b.generate_count&&k){const p=new Blob([k],{type:"text/csv;charset=utf-8;"}),v=document.createElement("a");v.href=window.URL.createObjectURL(p),v.download=`coupons_${new Date().getTime()}.csv`,v.click(),window.URL.revokeObjectURL(v.href)}c(!1),t==="create"&&E.reset(xn),n()},w=(b,k)=>e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:k}),e.jsx(T,{type:"datetime-local",step:"1",value:we(E.watch(b),"YYYY-MM-DDTHH:mm:ss"),onChange:p=>{const v=new Date(p.target.value);E.setValue(b,Math.floor(v.getTime()/1e3))},className:"h-8 [&::-webkit-calendar-picker-indicator]:hidden"})]});return e.jsxs(be,{open:o,onOpenChange:c,children:[r&&e.jsx(Je,{asChild:!0,children:r}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsx(Ce,{children:e.jsx(ye,{children:l(t==="create"?"form.add":"form.edit")})}),e.jsx(_e,{...E,children:e.jsxs("form",{onSubmit:E.handleSubmit(S),className:"space-y-4",children:[e.jsx(g,{control:E.control,name:"name",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.name.label")}),e.jsx(T,{placeholder:l("form.name.placeholder"),...b}),e.jsx(D,{})]})}),t==="create"&&e.jsx(g,{control:E.control,name:"generate_count",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.generateCount.label")}),e.jsx(T,{type:"number",min:0,placeholder:l("form.generateCount.placeholder"),...b,value:b.value===void 0?"":b.value,onChange:k=>b.onChange(k.target.value===""?"":parseInt(k.target.value)),className:"h-9"}),e.jsx(F,{className:"text-xs",children:l("form.generateCount.description")}),e.jsx(D,{})]})}),(!E.watch("generate_count")||E.watch("generate_count")==null)&&e.jsx(g,{control:E.control,name:"code",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.code.label")}),e.jsx(T,{placeholder:l("form.code.placeholder"),...b,className:"h-9"}),e.jsx(F,{className:"text-xs",children:l("form.code.description")}),e.jsx(D,{})]})}),e.jsxs(f,{children:[e.jsx(j,{children:l("form.type.label")}),e.jsxs("div",{className:"flex",children:[e.jsx(g,{control:E.control,name:"type",render:({field:b})=>e.jsxs(G,{value:b.value.toString(),onValueChange:k=>{const p=b.value,v=parseInt(k);b.onChange(v);const M=E.getValues("value");M&&(p===Be.AMOUNT&&v===Be.PERCENTAGE?E.setValue("value",M/100):p===Be.PERCENTAGE&&v===Be.AMOUNT&&E.setValue("value",M*100))},children:[e.jsx(K,{className:"flex-[1.2] rounded-r-none border-r-0 focus:z-10",children:e.jsx(W,{placeholder:l("form.type.placeholder")})}),e.jsx(B,{children:Object.entries(gu).map(([k,p])=>e.jsx(z,{value:k,children:l(`table.toolbar.types.${k}`)},k))})]})}),e.jsx(g,{control:E.control,name:"value",render:({field:b})=>{const k=b.value==null?"":E.watch("type")===Be.AMOUNT&&typeof b.value=="number"?(b.value/100).toString():b.value.toString();return e.jsx(T,{type:"number",placeholder:l("form.value.placeholder"),...b,value:k,onChange:p=>{const v=p.target.value;if(v===""){b.onChange("");return}const M=parseFloat(v);isNaN(M)||b.onChange(E.watch("type")===Be.AMOUNT?Math.round(M*100):M)},step:"any",min:0,className:"flex-[2] rounded-none border-x-0 text-left"})}}),e.jsx("div",{className:"flex min-w-[40px] items-center justify-center rounded-md rounded-l-none border border-l-0 border-input bg-muted/50 px-3 font-medium text-muted-foreground",children:e.jsx("span",{children:E.watch("type")==Be.AMOUNT?"¥":"%"})})]})]}),e.jsxs(f,{children:[e.jsx(j,{children:l("form.validity.label")}),e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(P,{variant:"outline",className:N("w-full justify-start text-left font-normal",!E.watch("started_at")&&"text-muted-foreground"),children:[e.jsx(jt,{className:"mr-2 h-4 w-4"}),we(E.watch("started_at"),"YYYY-MM-DD HH:mm:ss")," ",l("form.validity.to")," ",we(E.watch("ended_at"),"YYYY-MM-DD HH:mm:ss")]})}),e.jsxs(xs,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"border-b border-border",children:e.jsx(Gs,{mode:"range",selected:{from:new Date(E.watch("started_at")*1e3),to:new Date(E.watch("ended_at")*1e3)},onSelect:C,numberOfMonths:2})}),e.jsx("div",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-4",children:[w("started_at",l("table.validity.startTime")),e.jsx("div",{className:"mt-6 text-sm text-muted-foreground",children:l("form.validity.to")}),w("ended_at",l("table.validity.endTime"))]})})]})]}),e.jsx(D,{})]}),e.jsx(g,{control:E.control,name:"limit_use",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.limitUse.label")}),e.jsx(T,{type:"number",min:0,placeholder:l("form.limitUse.placeholder"),...b,value:b.value===null?"":b.value,onChange:k=>b.onChange(k.target.value===""?null:parseInt(k.target.value)),className:"h-9"}),e.jsx(F,{className:"text-xs",children:l("form.limitUse.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:E.control,name:"limit_use_with_user",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.limitUseWithUser.label")}),e.jsx(T,{type:"number",min:0,placeholder:l("form.limitUseWithUser.placeholder"),...b,value:b.value===null?"":b.value,onChange:k=>b.onChange(k.target.value===""?null:parseInt(k.target.value)),className:"h-9"}),e.jsx(F,{className:"text-xs",children:l("form.limitUseWithUser.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:E.control,name:"limit_period",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.limitPeriod.label")}),e.jsx(at,{options:Object.entries(xt).filter(([k])=>isNaN(Number(k))).map(([k,p])=>({label:l(`coupon:period.${p}`),value:k})),onChange:k=>{if(k.length===0){b.onChange([]);return}const p=k.map(v=>xt[v.value]);b.onChange(p)},value:(b.value||[]).map(k=>({label:l(`coupon:period.${k}`),value:Object.entries(xt).find(([p,v])=>v===k)?.[0]||""})),placeholder:l("form.limitPeriod.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:l("form.limitPeriod.empty")})}),e.jsx(F,{className:"text-xs",children:l("form.limitPeriod.description")}),e.jsx(D,{})]})}),e.jsx(g,{control:E.control,name:"limit_plan_ids",render:({field:b})=>e.jsxs(f,{children:[e.jsx(j,{children:l("form.limitPlan.label")}),e.jsx(at,{options:h?.map(k=>({label:k.name,value:k.id.toString()}))||[],onChange:k=>b.onChange(k.map(p=>Number(p.value))),value:(h||[]).filter(k=>(b.value||[]).includes(k.id)).map(k=>({label:k.name,value:k.id.toString()})),placeholder:l("form.limitPlan.placeholder"),emptyIndicator:e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:l("form.limitPlan.empty")})}),e.jsx(D,{})]})}),e.jsx(ze,{children:e.jsx(P,{type:"submit",disabled:E.formState.isSubmitting,children:E.formState.isSubmitting?l("form.submit.saving"):l("form.submit.save")})})]})})]})]})}function ih({table:s,refetch:n}){const t=s.getState().columnFilters.length>0,{t:r}=V("coupon");return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(al,{refetch:n,dialogTrigger:e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 space-x-2",children:[e.jsx(Ve,{icon:"ion:add"}),e.jsx("div",{children:r("form.add")})]})}),e.jsx(T,{placeholder:r("table.toolbar.search"),value:s.getColumn("name")?.getFilterValue()??"",onChange:a=>s.getColumn("name")?.setFilterValue(a.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),s.getColumn("type")&&e.jsx(rh,{column:s.getColumn("type"),title:r("table.toolbar.type"),options:[{value:Be.AMOUNT,label:r(`table.toolbar.types.${Be.AMOUNT}`)},{value:Be.PERCENTAGE,label:r(`table.toolbar.types.${Be.PERCENTAGE}`)}]}),t&&e.jsxs(P,{variant:"ghost",onClick:()=>s.resetColumnFilters(),className:"h-8 px-2 lg:px-3",children:[r("table.toolbar.reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]})]})}const nl=u.createContext(void 0);function oh({children:s,refetch:n}){const[t,r]=u.useState(!1),[a,i]=u.useState(null),l=m=>{i(m),r(!0)},d=()=>{r(!1),i(null)};return e.jsxs(nl.Provider,{value:{isOpen:t,currentCoupon:a,openEdit:l,closeEdit:d},children:[s,a&&e.jsx(al,{defaultValues:a,refetch:n,type:"edit",open:t,onOpenChange:r})]})}function ch(){const s=u.useContext(nl);if(s===void 0)throw new Error("useCouponEdit must be used within a CouponEditProvider");return s}const dh=s=>{const{t:n}=V("coupon");return[{accessorKey:"id",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.id")}),cell:({row:t})=>e.jsx(q,{children:t.original.id}),enableSorting:!0},{accessorKey:"show",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.show")}),cell:({row:t})=>e.jsx(Y,{defaultChecked:t.original.show,onCheckedChange:r=>{cd({id:t.original.id,show:r}).then(({data:a})=>!a&&s())}}),enableSorting:!1},{accessorKey:"name",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.name")}),cell:({row:t})=>e.jsx("div",{className:"flex items-center",children:e.jsx("span",{children:t.original.name})}),enableSorting:!1,size:800},{accessorKey:"type",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.type")}),cell:({row:t})=>e.jsx(q,{variant:"outline",children:n(`table.toolbar.types.${t.original.type}`)}),enableSorting:!0},{accessorKey:"code",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.code")}),cell:({row:t})=>e.jsx(q,{variant:"secondary",children:t.original.code}),enableSorting:!0},{accessorKey:"limit_use",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.limitUse")}),cell:({row:t})=>e.jsx(q,{variant:"outline",children:t.original.limit_use===null?n("table.validity.unlimited"):t.original.limit_use}),enableSorting:!0},{accessorKey:"limit_use_with_user",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.limitUseWithUser")}),cell:({row:t})=>e.jsx(q,{variant:"outline",children:t.original.limit_use_with_user===null?n("table.validity.noLimit"):t.original.limit_use_with_user}),enableSorting:!0},{accessorKey:"#",header:({column:t})=>e.jsx(O,{column:t,title:n("table.columns.validity")}),cell:({row:t})=>{const[r,a]=u.useState(!1),i=Date.now(),l=t.original.started_at*1e3,d=t.original.ended_at*1e3,m=i>d,o=ie.jsx(O,{className:"justify-end",column:t,title:n("table.columns.actions")}),cell:({row:t})=>{const{openEdit:r}=ch();return e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-muted",onClick:()=>r(t.original),children:[e.jsx(Hs,{className:"h-4 w-4 text-muted-foreground hover:text-foreground"}),e.jsx("span",{className:"sr-only",children:n("table.actions.edit")})]}),e.jsx(Qe,{title:n("table.actions.deleteConfirm.title"),description:n("table.actions.deleteConfirm.description"),confirmText:n("table.actions.deleteConfirm.confirmText"),variant:"destructive",onConfirm:async()=>{od({id:t.original.id}).then(({data:a})=>{a&&(A.success("删除成功"),s())})},children:e.jsxs(P,{variant:"ghost",size:"icon",className:"h-8 w-8 hover:bg-red-100 dark:hover:bg-red-900",children:[e.jsx(cs,{className:"h-4 w-4 text-muted-foreground hover:text-red-600 dark:hover:text-red-400"}),e.jsx("span",{className:"sr-only",children:n("table.actions.delete")})]})})]})}}]};function uh(){const[s,n]=u.useState({}),[t,r]=u.useState({}),[a,i]=u.useState([]),[l,d]=u.useState([]),[m,o]=u.useState({pageIndex:0,pageSize:20}),{refetch:c,data:h}=re({queryKey:["couponList",m,a,l],queryFn:()=>ld({pageSize:m.pageSize,current:m.pageIndex+1,filter:a,sort:l})}),_=ns({data:h?.data??[],columns:dh(c),state:{sorting:l,columnVisibility:t,rowSelection:s,columnFilters:a,pagination:m},pageCount:Math.ceil((h?.total??0)/m.pageSize),rowCount:h?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:d,onColumnFiltersChange:i,onColumnVisibilityChange:r,onPaginationChange:o,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsx(oh,{refetch:c,children:e.jsx("div",{className:"space-y-4",children:e.jsx(hs,{table:_,toolbar:e.jsx(ih,{table:_,refetch:c})})})})}function mh(){const{t:s}=V("coupon");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"text-muted-foreground mt-2",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(uh,{})})]})]})}const xh=Object.freeze(Object.defineProperty({__proto__:null,default:mh},Symbol.toStringTag,{value:"Module"})),hh=1,ph=1e6;let ua=0;function fh(){return ua=(ua+1)%Number.MAX_SAFE_INTEGER,ua.toString()}const ma=new Map,hn=s=>{if(ma.has(s))return;const n=setTimeout(()=>{ma.delete(s),ht({type:"REMOVE_TOAST",toastId:s})},ph);ma.set(s,n)},gh=(s,n)=>{switch(n.type){case"ADD_TOAST":return{...s,toasts:[n.toast,...s.toasts].slice(0,hh)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(t=>t.id===n.toast.id?{...t,...n.toast}:t)};case"DISMISS_TOAST":{const{toastId:t}=n;return t?hn(t):s.toasts.forEach(r=>{hn(r.id)}),{...s,toasts:s.toasts.map(r=>r.id===t||t===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return n.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(t=>t.id!==n.toastId)}}},Pt=[];let Et={toasts:[]};function ht(s){Et=gh(Et,s),Pt.forEach(n=>{n(Et)})}function jh({...s}){const n=fh(),t=a=>ht({type:"UPDATE_TOAST",toast:{...a,id:n}}),r=()=>ht({type:"DISMISS_TOAST",toastId:n});return ht({type:"ADD_TOAST",toast:{...s,id:n,open:!0,onOpenChange:a=>{a||r()}}}),{id:n,dismiss:r,update:t}}function rl(){const[s,n]=u.useState(Et);return u.useEffect(()=>(Pt.push(n),()=>{const t=Pt.indexOf(n);t>-1&&Pt.splice(t,1)}),[s]),{...s,toast:jh,dismiss:t=>ht({type:"DISMISS_TOAST",toastId:t})}}function vh({open:s,onOpenChange:n,table:t}){const{t:r}=V("user"),{toast:a}=rl(),[i,l]=u.useState(!1),[d,m]=u.useState(""),[o,c]=u.useState(""),h=async()=>{if(!d||!o){a({title:r("messages.error"),description:r("messages.send_mail.required_fields"),variant:"destructive"});return}try{l(!0),await Ot.sendMail({subject:d,content:o,filter:t.getState().columnFilters,sort:t.getState().sorting[0]?.id,sort_type:t.getState().sorting[0]?.desc?"DESC":"ASC"}),a({title:r("messages.success"),description:r("messages.send_mail.success")}),n(!1),m(""),c("")}catch{a({title:r("messages.error"),description:r("messages.send_mail.failed"),variant:"destructive"})}finally{l(!1)}};return e.jsx(be,{open:s,onOpenChange:n,children:e.jsxs(fe,{className:"sm:max-w-[500px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:r("send_mail.title")}),e.jsx(Te,{children:r("send_mail.description")})]}),e.jsxs("div",{className:"grid gap-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[e.jsx("label",{htmlFor:"subject",className:"text-right",children:r("send_mail.subject")}),e.jsx(T,{id:"subject",value:d,onChange:_=>m(_.target.value),className:"col-span-3"})]}),e.jsxs("div",{className:"grid grid-cols-4 items-center gap-4",children:[e.jsx("label",{htmlFor:"content",className:"text-right",children:r("send_mail.content")}),e.jsx(ys,{id:"content",value:o,onChange:_=>c(_.target.value),className:"col-span-3",rows:6})]})]}),e.jsx(ze,{children:e.jsx(J,{type:"submit",onClick:h,disabled:i,children:r(i?"send_mail.sending":"send_mail.send")})})]})})}const bh=x.object({email_prefix:x.string().optional(),email_suffix:x.string().min(1),password:x.string().optional(),expired_at:x.number().optional().nullable(),plan_id:x.number().nullable(),generate_count:x.number().optional().nullable()}).refine(s=>s.generate_count===null?s.email_prefix!==void 0&&s.email_prefix!=="":!0,{message:"Email prefix is required when generate_count is null",path:["email_prefix"]}),yh={email_prefix:"",email_suffix:"",password:"",expired_at:null,plan_id:null,generate_count:void 0};function Nh({refetch:s}){const{t:n}=V("user"),[t,r]=u.useState(!1),a=ge({resolver:Ne(bh),defaultValues:yh,mode:"onChange"}),[i,l]=u.useState([]);return u.useEffect(()=>{t&&qs().then(({data:d})=>{d&&l(d)})},[t]),e.jsxs(be,{open:t,onOpenChange:r,children:[e.jsx(Je,{asChild:!0,children:e.jsxs(J,{size:"sm",variant:"outline",className:"space-x-2 gap-0",children:[e.jsx(Ve,{icon:"ion:add"}),e.jsx("div",{children:n("generate.button")})]})}),e.jsxs(fe,{className:"sm:max-w-[425px]",children:[e.jsxs(Ce,{children:[e.jsx(ye,{children:n("generate.title")}),e.jsx(Te,{})]}),e.jsxs(_e,{...a,children:[e.jsxs(f,{children:[e.jsx(j,{children:n("generate.form.email")}),e.jsxs("div",{className:"flex",children:[!a.watch("generate_count")&&e.jsx(g,{control:a.control,name:"email_prefix",render:({field:d})=>e.jsx(T,{className:"flex-[5] rounded-r-none",placeholder:n("generate.form.email_prefix"),...d})}),e.jsx("div",{className:`z-[-1] border border-r-0 border-input px-3 py-1 shadow-sm ${a.watch("generate_count")?"rounded-l-md":"border-l-0"}`,children:"@"}),e.jsx(g,{control:a.control,name:"email_suffix",render:({field:d})=>e.jsx(T,{className:"flex-[4] rounded-l-none",placeholder:n("generate.form.email_domain"),...d})})]})]}),e.jsx(g,{control:a.control,name:"password",render:({field:d})=>e.jsxs(f,{children:[e.jsx(j,{children:n("generate.form.password")}),e.jsx(T,{placeholder:n("generate.form.password_placeholder"),...d}),e.jsx(D,{})]})}),e.jsx(g,{control:a.control,name:"expired_at",render:({field:d})=>e.jsxs(f,{className:"flex flex-col",children:[e.jsx(j,{children:n("generate.form.expire_time")}),e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsx(y,{children:e.jsxs(J,{variant:"outline",className:N("w-full pl-3 text-left font-normal",!d.value&&"text-muted-foreground"),children:[d.value?we(d.value):e.jsx("span",{children:n("generate.form.expire_time_placeholder")}),e.jsx(jt,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),e.jsxs(xs,{className:"flex w-auto flex-col space-y-2 p-2",children:[e.jsx(Go,{asChild:!0,children:e.jsx(J,{variant:"outline",className:"w-full",onClick:()=>{d.onChange(null)},children:n("generate.form.permanent")})}),e.jsx("div",{className:"rounded-md border",children:e.jsx(Gs,{mode:"single",selected:d.value?new Date(d.value*1e3):void 0,onSelect:m=>{m&&d.onChange(m?.getTime()/1e3)}})})]})]})]})}),e.jsx(g,{control:a.control,name:"plan_id",render:({field:d})=>e.jsxs(f,{children:[e.jsx(j,{children:n("generate.form.subscription")}),e.jsx(y,{children:e.jsxs(G,{value:d.value?d.value.toString():"null",onValueChange:m=>d.onChange(m==="null"?null:parseInt(m)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:n("generate.form.subscription_none")})}),e.jsxs(B,{children:[e.jsx(z,{value:"null",children:n("generate.form.subscription_none")}),i.map(m=>e.jsx(z,{value:m.id.toString(),children:m.name},m.id))]})]})})]})}),!a.watch("email_prefix")&&e.jsx(g,{control:a.control,name:"generate_count",render:({field:d})=>e.jsxs(f,{children:[e.jsx(j,{children:n("generate.form.generate_count")}),e.jsx(T,{type:"number",placeholder:n("generate.form.generate_count_placeholder"),value:d.value||"",onChange:m=>d.onChange(m.target.value?parseInt(m.target.value):null)})]})})]}),e.jsxs(ze,{children:[e.jsx(J,{variant:"outline",onClick:()=>r(!1),children:n("generate.form.cancel")}),e.jsx(J,{onClick:()=>a.handleSubmit(d=>{xd(d).then(({data:m})=>{m&&(A.success(n("generate.form.success")),a.reset(),s(),r(!1))})})(),children:n("generate.form.submit")})]})]})]})}const ll=Nn,_h=_n,wh=wn,il=u.forwardRef(({className:s,...n},t)=>e.jsx(zt,{className:N("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...n,ref:t}));il.displayName=zt.displayName;const Ch=As("fixed overflow-y-scroll z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-md",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-md"}},defaultVariants:{side:"right"}}),Aa=u.forwardRef(({side:s="right",className:n,children:t,...r},a)=>e.jsxs(wh,{children:[e.jsx(il,{}),e.jsxs(At,{ref:a,className:N(Ch({side:s}),n),...r,children:[e.jsxs(Ca,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e.jsx(ss,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]}),t]})]}));Aa.displayName=At.displayName;const $a=({className:s,...n})=>e.jsx("div",{className:N("flex flex-col space-y-2 text-center sm:text-left",s),...n});$a.displayName="SheetHeader";const ol=({className:s,...n})=>e.jsx("div",{className:N("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...n});ol.displayName="SheetFooter";const Ua=u.forwardRef(({className:s,...n},t)=>e.jsx($t,{ref:t,className:N("text-lg font-semibold text-foreground",s),...n}));Ua.displayName=$t.displayName;const Ha=u.forwardRef(({className:s,...n},t)=>e.jsx(Ut,{ref:t,className:N("text-sm text-muted-foreground",s),...n}));Ha.displayName=Ut.displayName;function Sh({table:s,refetch:n,permissionGroups:t=[],subscriptionPlans:r=[]}){const{t:a}=V("user"),{toast:i}=rl(),l=s.getState().columnFilters.length>0,[d,m]=u.useState([]),[o,c]=u.useState(!1),[h,_]=u.useState(!1),[E,C]=u.useState(!1),[S,w]=u.useState(!1),b=async()=>{try{const Q=await Ot.dumpCSV({filter:s.getState().columnFilters,sort:s.getState().sorting[0]?.id,sort_type:s.getState().sorting[0]?.desc?"DESC":"ASC"}),te=Q;console.log(Q);const $=new Blob([te],{type:"text/csv;charset=utf-8;"}),R=window.URL.createObjectURL($),X=document.createElement("a");X.href=R,X.setAttribute("download",`users_${new Date().toISOString()}.csv`),document.body.appendChild(X),X.click(),X.remove(),window.URL.revokeObjectURL(R),i({title:a("messages.success"),description:a("messages.export.success")})}catch{i({title:a("messages.error"),description:a("messages.export.failed"),variant:"destructive"})}},k=async()=>{try{w(!0),await Ot.batchBan({filter:s.getState().columnFilters,sort:s.getState().sorting[0]?.id,sort_type:s.getState().sorting[0]?.desc?"DESC":"ASC"}),i({title:a("messages.success"),description:a("messages.batch_ban.success")}),n()}catch{i({title:a("messages.error"),description:a("messages.batch_ban.failed"),variant:"destructive"})}finally{w(!1),C(!1)}},p=[{label:a("filter.fields.email"),value:"email",type:"text",operators:[{label:a("filter.operators.contains"),value:"contains"},{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.id"),value:"id",type:"number",operators:[{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.plan_id"),value:"plan_id",type:"select",operators:[{label:a("filter.operators.eq"),value:"eq"}],useOptions:!0},{label:a("filter.fields.transfer_enable"),value:"transfer_enable",type:"number",unit:"GB",operators:[{label:a("filter.operators.gt"),value:"gt"},{label:a("filter.operators.lt"),value:"lt"},{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.total_used"),value:"total_used",type:"number",unit:"GB",operators:[{label:a("filter.operators.gt"),value:"gt"},{label:a("filter.operators.lt"),value:"lt"},{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.online_count"),value:"online_count",type:"number",operators:[{label:a("filter.operators.eq"),value:"eq"},{label:a("filter.operators.gt"),value:"gt"},{label:a("filter.operators.lt"),value:"lt"}]},{label:a("filter.fields.expired_at"),value:"expired_at",type:"date",operators:[{label:a("filter.operators.lt"),value:"lt"},{label:a("filter.operators.gt"),value:"gt"},{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.uuid"),value:"uuid",type:"text",operators:[{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.token"),value:"token",type:"text",operators:[{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.banned"),value:"banned",type:"select",operators:[{label:a("filter.operators.eq"),value:"eq"}],options:[{label:a("filter.status.normal"),value:"0"},{label:a("filter.status.banned"),value:"1"}]},{label:a("filter.fields.remark"),value:"remarks",type:"text",operators:[{label:a("filter.operators.contains"),value:"contains"},{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.inviter_email"),value:"invite_user.email",type:"text",operators:[{label:a("filter.operators.contains"),value:"contains"},{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.invite_user_id"),value:"invite_user_id",type:"number",operators:[{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.is_admin"),value:"is_admin",type:"boolean",operators:[{label:a("filter.operators.eq"),value:"eq"}]},{label:a("filter.fields.is_staff"),value:"is_staff",type:"boolean",operators:[{label:a("filter.operators.eq"),value:"eq"}]}],v=Q=>Q*1024*1024*1024,M=Q=>Q/(1024*1024*1024),H=()=>{m([...d,{field:"",operator:"",value:""}])},se=Q=>{m(d.filter((te,$)=>$!==Q))},L=(Q,te,$)=>{const R=[...d];if(R[Q]={...R[Q],[te]:$},te==="field"){const X=p.find(Ns=>Ns.value===$);X&&(R[Q].operator=X.operators[0].value,R[Q].value=X.type==="boolean"?!1:"")}m(R)},Z=(Q,te)=>{const $=p.find(R=>R.value===Q.field);if(!$)return null;switch($.type){case"text":return e.jsx(T,{placeholder:a("filter.sheet.value"),value:Q.value,onChange:R=>L(te,"value",R.target.value)});case"number":return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(T,{type:"number",placeholder:a("filter.sheet.value_number",{unit:$.unit}),value:$.unit==="GB"?M(Q.value||0):Q.value,onChange:R=>{const X=Number(R.target.value);L(te,"value",$.unit==="GB"?v(X):X)}}),$.unit&&e.jsx("span",{className:"text-sm text-muted-foreground",children:$.unit})]});case"date":return e.jsx(Gs,{mode:"single",selected:Q.value,onSelect:R=>L(te,"value",R),className:"flex flex-1 justify-center rounded-md border"});case"select":return e.jsxs(G,{value:Q.value,onValueChange:R=>L(te,"value",R),children:[e.jsx(K,{children:e.jsx(W,{placeholder:a("filter.sheet.value")})}),e.jsx(B,{children:$.useOptions?r.map(R=>e.jsx(z,{value:R.value.toString(),children:R.label},R.value)):$.options?.map(R=>e.jsx(z,{value:R.value.toString(),children:R.label},R.value))})]});case"boolean":return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Y,{checked:Q.value,onCheckedChange:R=>L(te,"value",R)}),e.jsx(Mt,{children:Q.value?a("filter.boolean.true"):a("filter.boolean.false")})]});default:return null}},de=()=>{const Q=d.filter(te=>te.field&&te.operator&&te.value!=="").map(te=>{const $=p.find(X=>X.value===te.field);let R=te.value;return te.operator==="contains"?{id:te.field,value:R}:($?.type==="date"&&R instanceof Date&&(R=Math.floor(R.getTime()/1e3)),$?.type==="boolean"&&(R=R?1:0),{id:te.field,value:`${te.operator}:${R}`})});s.setColumnFilters(Q),c(!1)};return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-1 flex-wrap items-center gap-2",children:[e.jsx(Nh,{refetch:n}),e.jsx(T,{placeholder:a("filter.email_search"),value:s.getColumn("email")?.getFilterValue()??"",onChange:Q=>s.getColumn("email")?.setFilterValue(Q.target.value),className:"h-8 w-[150px] lg:w-[250px]"}),e.jsxs(ll,{open:o,onOpenChange:c,children:[e.jsx(_h,{asChild:!0,children:e.jsxs(P,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(Wo,{className:"mr-2 h-4 w-4"}),a("filter.advanced"),d.length>0&&e.jsx(q,{variant:"secondary",className:"ml-2 rounded-sm px-1",children:d.length})]})}),e.jsxs(Aa,{className:"w-[400px] sm:w-[540px]",children:[e.jsxs($a,{children:[e.jsx(Ua,{children:a("filter.sheet.title")}),e.jsx(Ha,{children:a("filter.sheet.description")})]}),e.jsxs("div",{className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-medium",children:a("filter.sheet.conditions")}),e.jsx(P,{variant:"outline",size:"sm",onClick:H,children:a("filter.sheet.add")})]}),e.jsx(zs,{className:"h-[calc(100vh-280px)] ",children:e.jsx("div",{className:"space-y-4",children:d.map((Q,te)=>e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Mt,{children:a("filter.sheet.condition",{number:te+1})}),e.jsx(P,{variant:"ghost",size:"sm",onClick:()=>se(te),children:e.jsx(ss,{className:"h-4 w-4"})})]}),e.jsxs(G,{value:Q.field,onValueChange:$=>L(te,"field",$),children:[e.jsx(K,{children:e.jsx(W,{placeholder:a("filter.sheet.field")})}),e.jsx(B,{children:e.jsx(He,{children:p.map($=>e.jsx(z,{value:$.value,className:"cursor-pointer",children:$.label},$.value))})})]}),Q.field&&e.jsxs(G,{value:Q.operator,onValueChange:$=>L(te,"operator",$),children:[e.jsx(K,{children:e.jsx(W,{placeholder:a("filter.sheet.operator")})}),e.jsx(B,{children:p.find($=>$.value===Q.field)?.operators.map($=>e.jsx(z,{value:$.value,children:$.label},$.value))})]}),Q.field&&Q.operator&&Z(Q,te)]},te))})}),e.jsxs("div",{className:"flex justify-end space-x-2",children:[e.jsx(P,{variant:"outline",onClick:()=>{m([]),c(!1)},children:a("filter.sheet.reset")}),e.jsx(P,{onClick:de,children:a("filter.sheet.apply")})]})]})]})]}),l&&e.jsxs(P,{variant:"ghost",onClick:()=>{s.resetColumnFilters(),m([])},className:"h-8 px-2 lg:px-3",children:[a("reset"),e.jsx(ss,{className:"ml-2 h-4 w-4"})]}),e.jsxs(Ss,{modal:!1,children:[e.jsx(ks,{asChild:!0,children:e.jsx(P,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:a("actions.title")})}),e.jsxs(fs,{children:[e.jsx(je,{onClick:()=>_(!0),children:a("actions.send_email")}),e.jsx(je,{onClick:b,children:a("actions.export_csv")}),e.jsx(tt,{}),e.jsx(je,{onClick:()=>C(!0),className:"text-red-600 focus:text-red-600",children:a("actions.batch_ban")})]})]})]}),e.jsx(vh,{open:h,onOpenChange:_,table:s}),e.jsx(Oa,{open:E,onOpenChange:C,children:e.jsxs(Yt,{children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:a("actions.confirm_ban.title")}),e.jsx(Zt,{children:a(l?"actions.confirm_ban.filtered_description":"actions.confirm_ban.all_description")})]}),e.jsxs(Jt,{children:[e.jsx(sa,{disabled:S,children:a("actions.confirm_ban.cancel")}),e.jsx(ea,{onClick:k,disabled:S,className:"bg-red-600 hover:bg-red-700 focus:ring-red-600",children:a(S?"actions.confirm_ban.banning":"actions.confirm_ban.confirm")})]})]})})]})}const cl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"m17.71 11.29l-5-5a1 1 0 0 0-.33-.21a1 1 0 0 0-.76 0a1 1 0 0 0-.33.21l-5 5a1 1 0 0 0 1.42 1.42L11 9.41V17a1 1 0 0 0 2 0V9.41l3.29 3.3a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42"})}),dl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M17.71 11.29a1 1 0 0 0-1.42 0L13 14.59V7a1 1 0 0 0-2 0v7.59l-3.29-3.3a1 1 0 0 0-1.42 1.42l5 5a1 1 0 0 0 .33.21a.94.94 0 0 0 .76 0a1 1 0 0 0 .33-.21l5-5a1 1 0 0 0 0-1.42"})}),kh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M17 11H9.41l3.3-3.29a1 1 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33a1 1 0 0 0 0 .76a1 1 0 0 0 .21.33l5 5a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42L9.41 13H17a1 1 0 0 0 0-2"})}),Th=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M17.92 11.62a1 1 0 0 0-.21-.33l-5-5a1 1 0 0 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1 1 0 0 0 0 1.42a1 1 0 0 0 1.42 0l5-5a1 1 0 0 0 .21-.33a1 1 0 0 0 0-.76"})}),xa=[{accessorKey:"record_at",header:"时间",cell:({row:s})=>e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx("time",{className:"text-sm text-muted-foreground",children:mc(s.original.record_at)})})},{accessorKey:"u",header:"上行流量",cell:({row:s})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(cl,{className:"h-4 w-4 text-emerald-500"}),e.jsx("span",{className:"font-mono text-sm",children:ps(s.original.u)})]})},{accessorKey:"d",header:"下行流量",cell:({row:s})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(dl,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"font-mono text-sm",children:ps(s.original.d)})]})},{accessorKey:"server_rate",header:"倍率",cell:({row:s})=>{const n=s.original.server_rate;return e.jsx("div",{className:"flex items-center space-x-2",children:e.jsxs(q,{variant:"outline",className:"font-mono",children:[n,"x"]})})}},{id:"total",header:"总计",cell:({row:s})=>{const n=s.original.u+s.original.d;return e.jsx("div",{className:"flex items-center justify-end font-mono text-sm",children:ps(n)})}}];function ul({user_id:s,dialogTrigger:n}){const{t}=V(["traffic"]),[r,a]=u.useState(!1),[i,l]=u.useState({pageIndex:0,pageSize:20}),{data:d,isLoading:m}=re({queryKey:["userStats",s,i,r],queryFn:()=>r?hd({user_id:s,pageSize:i.pageSize,page:i.pageIndex+1}):null}),o=ns({data:d?.data??[],columns:xa,pageCount:Math.ceil((d?.total??0)/i.pageSize),state:{pagination:i},manualPagination:!0,getCoreRowModel:rs(),onPaginationChange:l});return e.jsxs(be,{open:r,onOpenChange:a,children:[e.jsx(Je,{asChild:!0,children:n}),e.jsxs(fe,{className:"sm:max-w-[700px]",children:[e.jsx(Ce,{children:e.jsx(ye,{children:t("trafficRecord.title")})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ia,{children:[e.jsx(Va,{children:o.getHeaderGroups().map(c=>e.jsx(Is,{children:c.headers.map(h=>e.jsx(Fa,{className:N("h-10 px-2 text-xs",h.id==="total"&&"text-right"),children:h.isPlaceholder?null:Rt(h.column.columnDef.header,h.getContext())},h.id))},c.id))}),e.jsx(Ma,{children:m?Array.from({length:i.pageSize}).map((c,h)=>e.jsx(Is,{children:Array.from({length:xa.length}).map((_,E)=>e.jsx(Zs,{className:"p-2",children:e.jsx(oe,{className:"h-6 w-full"})},E))},h)):o.getRowModel().rows?.length?o.getRowModel().rows.map(c=>e.jsx(Is,{"data-state":c.getIsSelected()&&"selected",className:"h-10",children:c.getVisibleCells().map(h=>e.jsx(Zs,{className:"px-2",children:Rt(h.column.columnDef.cell,h.getContext())},h.id))},c.id)):e.jsx(Is,{children:e.jsx(Zs,{colSpan:xa.length,className:"h-24 text-center",children:t("trafficRecord.noRecords")})})})]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("p",{className:"text-sm font-medium",children:t("trafficRecord.perPage")}),e.jsxs(G,{value:`${o.getState().pagination.pageSize}`,onValueChange:c=>{o.setPageSize(Number(c))},children:[e.jsx(K,{className:"h-8 w-[70px]",children:e.jsx(W,{placeholder:o.getState().pagination.pageSize})}),e.jsx(B,{side:"top",children:[10,20,30,40,50].map(c=>e.jsx(z,{value:`${c}`,children:c},c))})]}),e.jsx("p",{className:"text-sm font-medium",children:t("trafficRecord.records")})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("div",{className:"flex w-[100px] items-center justify-center text-sm",children:t("trafficRecord.page",{current:o.getState().pagination.pageIndex+1,total:o.getPageCount()})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(J,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>o.previousPage(),disabled:!o.getCanPreviousPage()||m,children:e.jsx(kh,{className:"h-4 w-4"})}),e.jsx(J,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>o.nextPage(),disabled:!o.getCanNextPage()||m,children:e.jsx(Th,{className:"h-4 w-4"})})]})]})]})]})]})]})}function Dh({onConfirm:s,children:n,title:t="确认操作",description:r="确定要执行此操作吗?",cancelText:a="取消",confirmText:i="确认",variant:l="default",className:d}){return e.jsxs(Oa,{children:[e.jsx(Kr,{asChild:!0,children:n}),e.jsxs(Yt,{className:N("sm:max-w-[425px]",d),children:[e.jsxs(Qt,{children:[e.jsx(Xt,{children:t}),e.jsx(Zt,{children:r})]}),e.jsxs(Jt,{children:[e.jsx(sa,{asChild:!0,children:e.jsx(P,{variant:"outline",children:a})}),e.jsx(ea,{asChild:!0,children:e.jsx(P,{variant:l,onClick:s,children:i})})]})]})]})}const Ph=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M5 18h4.24a1 1 0 0 0 .71-.29l6.92-6.93L19.71 8a1 1 0 0 0 0-1.42l-4.24-4.29a1 1 0 0 0-1.42 0l-2.82 2.83l-6.94 6.93a1 1 0 0 0-.29.71V17a1 1 0 0 0 1 1m9.76-13.59l2.83 2.83l-1.42 1.42l-2.83-2.83ZM6 13.17l5.93-5.93l2.83 2.83L8.83 16H6ZM21 20H3a1 1 0 0 0 0 2h18a1 1 0 0 0 0-2"})}),Eh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M19 11h-6V5a1 1 0 0 0-2 0v6H5a1 1 0 0 0 0 2h6v6a1 1 0 0 0 2 0v-6h6a1 1 0 0 0 0-2"})}),Rh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21 8.94a1.3 1.3 0 0 0-.06-.27v-.09a1 1 0 0 0-.19-.28l-6-6a1 1 0 0 0-.28-.19a.3.3 0 0 0-.09 0a.9.9 0 0 0-.33-.11H10a3 3 0 0 0-3 3v1H6a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3v-1h1a3 3 0 0 0 3-3zm-6-3.53L17.59 8H16a1 1 0 0 1-1-1ZM15 19a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h1v7a3 3 0 0 0 3 3h5Zm4-4a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3v3a3 3 0 0 0 3 3h3Z"})}),Ih=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21 11a1 1 0 0 0-1 1a8.05 8.05 0 1 1-2.22-5.5h-2.4a1 1 0 0 0 0 2h4.53a1 1 0 0 0 1-1V3a1 1 0 0 0-2 0v1.77A10 10 0 1 0 22 12a1 1 0 0 0-1-1"})}),Vh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M9.5 10.5H12a1 1 0 0 0 0-2h-1V8a1 1 0 0 0-2 0v.55a2.5 2.5 0 0 0 .5 4.95h1a.5.5 0 0 1 0 1H8a1 1 0 0 0 0 2h1v.5a1 1 0 0 0 2 0v-.55a2.5 2.5 0 0 0-.5-4.95h-1a.5.5 0 0 1 0-1M21 12h-3V3a1 1 0 0 0-.5-.87a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0A1 1 0 0 0 2 3v16a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-6a1 1 0 0 0-1-1M5 20a1 1 0 0 1-1-1V4.73l2 1.14a1.08 1.08 0 0 0 1 0l3-1.72l3 1.72a1.08 1.08 0 0 0 1 0l2-1.14V19a3 3 0 0 0 .18 1Zm15-1a1 1 0 0 1-2 0v-5h2Z"})}),Mh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M12.3 12.22A4.92 4.92 0 0 0 14 8.5a5 5 0 0 0-10 0a4.92 4.92 0 0 0 1.7 3.72A8 8 0 0 0 1 19.5a1 1 0 0 0 2 0a6 6 0 0 1 12 0a1 1 0 0 0 2 0a8 8 0 0 0-4.7-7.28M9 11.5a3 3 0 1 1 3-3a3 3 0 0 1-3 3m9.74.32A5 5 0 0 0 15 3.5a1 1 0 0 0 0 2a3 3 0 0 1 3 3a3 3 0 0 1-1.5 2.59a1 1 0 0 0-.5.84a1 1 0 0 0 .45.86l.39.26l.13.07a7 7 0 0 1 4 6.38a1 1 0 0 0 2 0a9 9 0 0 0-4.23-7.68"})}),Fh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M12 2a10 10 0 0 0-6.88 2.77V3a1 1 0 0 0-2 0v4.5a1 1 0 0 0 1 1h4.5a1 1 0 0 0 0-2h-2.4A8 8 0 1 1 4 12a1 1 0 0 0-2 0A10 10 0 1 0 12 2m0 6a1 1 0 0 0-1 1v3a1 1 0 0 0 1 1h2a1 1 0 0 0 0-2h-1V9a1 1 0 0 0-1-1"})}),Oh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M20 6h-4V5a3 3 0 0 0-3-3h-2a3 3 0 0 0-3 3v1H4a1 1 0 0 0 0 2h1v11a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3V8h1a1 1 0 0 0 0-2M10 5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v1h-4Zm7 14a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8h10Z"})}),Lh=(s,n,t,r)=>{const{t:a}=V("user");return[{accessorKey:"is_admin",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.is_admin")}),enableSorting:!1,enableHiding:!0,filterFn:(i,l,d)=>d.includes(i.getValue(l)),size:0},{accessorKey:"is_staff",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.is_staff")}),enableSorting:!1,enableHiding:!0,filterFn:(i,l,d)=>d.includes(i.getValue(l)),size:0},{accessorKey:"id",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.id")}),cell:({row:i})=>e.jsx(q,{variant:"outline",children:i.original.id}),enableSorting:!0,enableHiding:!1},{accessorKey:"email",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.email")}),cell:({row:i})=>{const l=i.original.t||0,d=Date.now()/1e3-l<120,m=Math.floor(Date.now()/1e3-l);let o=d?a("columns.online_status.online"):l===0?a("columns.online_status.never"):a("columns.online_status.last_online",{time:we(l)});if(!d&&l!==0){const c=Math.floor(m/60),h=Math.floor(c/60),_=Math.floor(h/24);_>0?o+=` +`+a("columns.online_status.offline_duration.days",{count:_}):h>0?o+=` +`+a("columns.online_status.offline_duration.hours",{count:h}):c>0?o+=` +`+a("columns.online_status.offline_duration.minutes",{count:c}):o+=` +`+a("columns.online_status.offline_duration.seconds",{count:m})}return e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:N("size-2.5 rounded-full ring-2 ring-offset-2",d?"bg-green-500 ring-green-500/20":"bg-gray-300 ring-gray-300/20","transition-all duration-300")}),e.jsx("span",{className:"font-medium text-foreground/90",children:i.original.email})]})}),e.jsx(ce,{side:"bottom",className:"max-w-[280px]",children:e.jsx("p",{className:"whitespace-pre-line text-sm",children:o})})]})})},enableSorting:!1,enableHiding:!1},{accessorKey:"online_count",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.online_count")}),cell:({row:i})=>{const l=i.original.device_limit,d=i.original.online_count||0;return e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsxs(q,{variant:"outline",className:N("min-w-[4rem] justify-center",l!==null&&d>=l?"border-destructive/50 bg-destructive/10 text-destructive":"border-primary/40 bg-primary/5 text-primary/90"),children:[d," / ",l===null?"∞":l]})})}),e.jsx(ce,{side:"bottom",children:e.jsx("p",{className:"text-sm",children:l===null?a("columns.device_limit.unlimited"):a("columns.device_limit.limited",{count:l})})})]})})},enableSorting:!0,enableHiding:!1},{accessorKey:"banned",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.status")}),cell:({row:i})=>{const l=i.original.banned;return e.jsx("div",{className:"flex justify-center",children:e.jsx(q,{className:N("min-w-20 justify-center transition-colors",l?"bg-destructive/15 text-destructive hover:bg-destructive/25":"bg-success/15 text-success hover:bg-success/25"),children:a(l?"columns.status_text.banned":"columns.status_text.normal")})})},enableSorting:!0,filterFn:(i,l,d)=>d.includes(i.getValue(l))},{accessorKey:"plan_id",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.subscription")}),cell:({row:i})=>e.jsx("div",{className:"min-w-[10em] break-all",children:i.original?.plan?.name||"-"}),enableSorting:!1,enableHiding:!1},{accessorKey:"group_id",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.group")}),cell:({row:i})=>e.jsx("div",{className:"flex flex-wrap gap-1",children:e.jsx(q,{variant:"outline",className:N("px-2 py-0.5 font-medium","bg-secondary/50 hover:bg-secondary/70","border border-border/50","transition-all duration-200","cursor-default select-none","flex items-center gap-1.5 whitespace-nowrap"),children:i.original?.group?.name||"-"})}),enableSorting:!1},{accessorKey:"total_used",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.used_traffic")}),cell:({row:i})=>{const l=ps(i.original?.total_used),d=ps(i.original?.transfer_enable),m=i.original?.total_used/i.original?.transfer_enable*100||0;return e.jsx(ve,{delayDuration:100,children:e.jsxs(he,{children:[e.jsx(pe,{className:"w-full",children:e.jsxs("div",{className:"w-full space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:l}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[m.toFixed(1),"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-secondary",children:e.jsx("div",{className:N("h-full rounded-full transition-all",m>90?"bg-destructive":"bg-primary"),style:{width:`${Math.min(m,100)}%`}})})]})}),e.jsx(ce,{side:"bottom",children:e.jsxs("p",{className:"text-sm",children:[a("columns.total_traffic"),": ",d]})})]})})}},{accessorKey:"transfer_enable",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.total_traffic")}),cell:({row:i})=>e.jsx("div",{className:"font-medium text-muted-foreground",children:ps(i.original?.transfer_enable)})},{accessorKey:"expired_at",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.expire_time")}),cell:({row:i})=>{const l=i.original.expired_at,d=Date.now()/1e3,m=l!=null&&le.jsx(O,{column:i,title:a("columns.balance")}),cell:({row:i})=>{const l=Xs(i.original?.balance);return e.jsxs("div",{className:"flex items-center gap-1 font-medium",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"¥"}),e.jsx("span",{className:"tabular-nums text-foreground",children:l})]})}},{accessorKey:"commission_balance",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.commission")}),cell:({row:i})=>{const l=Xs(i.original?.commission_balance);return e.jsxs("div",{className:"flex items-center gap-1 font-medium",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"¥"}),e.jsx("span",{className:"tabular-nums text-foreground",children:l})]})}},{accessorKey:"created_at",header:({column:i})=>e.jsx(O,{column:i,title:a("columns.register_time")}),cell:({row:i})=>e.jsx("div",{className:"truncate",children:we(i.original?.created_at)}),size:1e3},{id:"actions",header:({column:i})=>e.jsx(O,{column:i,className:"justify-end",title:a("columns.actions")}),cell:({row:i,table:l})=>e.jsxs(Ss,{modal:!0,children:[e.jsx(ks,{asChild:!0,children:e.jsx("div",{className:"text-center",children:e.jsx(J,{variant:"ghost",className:"h-8 w-8 p-0 hover:bg-muted","aria-label":a("columns.actions"),children:e.jsx(Vt,{className:"size-4"})})})}),e.jsxs(fs,{align:"end",className:"min-w-[40px]",children:[e.jsx(je,{onSelect:d=>{d.preventDefault(),t(i.original),r(!0)},className:"p-0",children:e.jsxs(J,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Ph,{className:"mr-2"}),a("columns.actions_menu.edit")]})}),e.jsx(je,{onSelect:d=>d.preventDefault(),className:"p-0",children:e.jsx(tl,{defaultValues:{email:i.original.email},trigger:e.jsxs(J,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Eh,{className:"mr-2 "}),a("columns.actions_menu.assign_order")]})})}),e.jsx(je,{onSelect:()=>{Ft(i.original.subscribe_url).then(()=>{A.success(a("common:copy.success"))})},className:"p-0",children:e.jsxs(J,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Rh,{className:"mr-2"}),a("columns.actions_menu.copy_url")]})}),e.jsx(je,{onSelect:()=>{md({id:i.original.id}).then(({data:d})=>{d&&A.success("重置成功")})},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Ih,{className:"mr-2 "}),a("columns.actions_menu.reset_secret")]})}),e.jsx(je,{onSelect:()=>{},className:"p-0",children:e.jsxs(Us,{className:"flex items-center px-2 py-1.5",to:`/finance/order?user_id=${i.original?.id}`,children:[e.jsx(Vh,{className:"mr-2"}),a("columns.actions_menu.orders")]})}),e.jsx(je,{onSelect:()=>{l.setColumnFilters([{id:"invite_user_id",value:"eq:"+i.original?.id}])},children:e.jsxs("div",{className:"flex items-center",children:[e.jsx(Mh,{className:"mr-2 "}),a("columns.actions_menu.invites")]})}),e.jsx(je,{onSelect:d=>d.preventDefault(),className:"p-0",children:e.jsx(ul,{user_id:i.original?.id,dialogTrigger:e.jsxs(J,{variant:"ghost",className:"w-full justify-start px-2 py-1.5",children:[e.jsx(Fh,{className:"mr-2 "}),a("columns.actions_menu.traffic_records")]})})}),e.jsx(je,{onSelect:d=>d.preventDefault(),className:"p-0",children:e.jsx(Dh,{title:a("columns.actions_menu.delete_confirm_title"),description:a("columns.actions_menu.delete_confirm_description",{email:i.original.email}),cancelText:a("common:cancel"),confirmText:a("common:confirm"),variant:"destructive",onConfirm:async()=>{try{const{data:d}=await Ot.destroy(i.original.id);d&&(A.success(a("common:delete.success")),s())}catch{A.error(a("common:delete.failed"))}},children:e.jsxs(J,{variant:"ghost",className:"w-full justify-start px-2 py-1.5 text-destructive hover:text-destructive",children:[e.jsx(Oh,{className:"mr-2"}),a("columns.actions_menu.delete")]})})})]})]})}]},ml=u.createContext(void 0),qa=()=>{const s=u.useContext(ml);if(!s)throw new Error("useUserEdit must be used within an UserEditProvider");return s},xl=({children:s,refreshData:n})=>{const[t,r]=u.useState(!1),[a,i]=u.useState(null),l={isOpen:t,setIsOpen:r,editingUser:a,setEditingUser:i,refreshData:n};return e.jsx(ml.Provider,{value:l,children:s})},zh=x.object({id:x.number(),email:x.string().email(),invite_user_email:x.string().email().nullable().optional(),password:x.string().optional().nullable(),balance:x.coerce.number(),commission_balance:x.coerce.number(),u:x.number(),d:x.number(),transfer_enable:x.number(),expired_at:x.number().nullable(),plan_id:x.number().nullable(),banned:x.number(),commission_type:x.number(),commission_rate:x.number().nullable(),discount:x.number().nullable(),speed_limit:x.number().nullable(),device_limit:x.number().nullable(),is_admin:x.number(),is_staff:x.number(),remarks:x.string().nullable()});function hl(){const{t:s}=V("user"),{isOpen:n,setIsOpen:t,editingUser:r,refreshData:a}=qa(),[i,l]=u.useState(!1),[d,m]=u.useState([]),o=ge({resolver:Ne(zh),defaultValues:{id:0,email:"",invite_user_email:null,password:null,balance:0,commission_balance:0,u:0,d:0,transfer_enable:0,expired_at:null,plan_id:null,banned:0,commission_type:0,commission_rate:null,discount:null,speed_limit:null,device_limit:null,is_admin:0,is_staff:0,remarks:null}});return u.useEffect(()=>{n&&qs().then(({data:c})=>{m(c)})},[n]),u.useEffect(()=>{if(r){const c=r.invite_user?.email,{invite_user:h,..._}=r;o.reset({..._,invite_user_email:c||null,password:null})}},[r,o]),e.jsx(ll,{open:n,onOpenChange:t,children:e.jsxs(Aa,{className:"max-w-[90%] space-y-4",children:[e.jsxs($a,{children:[e.jsx(Ua,{children:s("edit.title")}),e.jsx(Ha,{})]}),e.jsxs(_e,{...o,children:[e.jsx(g,{control:o.control,name:"email",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.email")}),e.jsx(y,{children:e.jsx(T,{...c,placeholder:s("edit.form.email_placeholder")})}),e.jsx(D,{...c})]})}),e.jsx(g,{control:o.control,name:"invite_user_email",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.inviter_email")}),e.jsx(y,{children:e.jsx(T,{value:c.value||"",onChange:h=>c.onChange(h.target.value?h.target.value:null),placeholder:s("edit.form.inviter_email_placeholder")})}),e.jsx(D,{...c})]})}),e.jsx(g,{control:o.control,name:"password",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.password")}),e.jsx(y,{children:e.jsx(T,{type:"password",value:c.value||"",onChange:c.onChange,placeholder:s("edit.form.password_placeholder")})}),e.jsx(D,{...c})]})}),e.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[e.jsx(g,{control:o.control,name:"balance",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.balance")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value||"",onChange:c.onChange,placeholder:s("edit.form.balance_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"¥"})]})}),e.jsx(D,{...c})]})}),e.jsx(g,{control:o.control,name:"commission_balance",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.commission_balance")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value||"",onChange:c.onChange,placeholder:s("edit.form.commission_balance_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"¥"})]})}),e.jsx(D,{...c})]})}),e.jsx(g,{control:o.control,name:"u",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.upload")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{value:c.value/1024/1024/1024||"",onChange:h=>c.onChange(parseInt(h.target.value)*1024*1024*1024),placeholder:s("edit.form.upload_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"GB"})]})}),e.jsx(D,{...c})]})}),e.jsx(g,{control:o.control,name:"d",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.download")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value/1024/1024/1024||"",onChange:h=>c.onChange(parseInt(h.target.value)*1024*1024*1024),placeholder:s("edit.form.download_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"GB"})]})}),e.jsx(D,{...c})]})})]}),e.jsx(g,{control:o.control,name:"transfer_enable",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.total_traffic")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value/1024/1024/1024||"",onChange:h=>c.onChange(parseInt(h.target.value)*1024*1024*1024),placeholder:s("edit.form.total_traffic_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"GB"})]})}),e.jsx(D,{})]})}),e.jsx(g,{control:o.control,name:"expired_at",render:({field:c})=>e.jsxs(f,{className:"flex flex-col",children:[e.jsx(j,{children:s("edit.form.expire_time")}),e.jsxs(vs,{open:i,onOpenChange:l,children:[e.jsx(bs,{asChild:!0,children:e.jsx(y,{children:e.jsxs(P,{type:"button",variant:"outline",className:N("w-full pl-3 text-left font-normal",!c.value&&"text-muted-foreground"),onClick:()=>l(!0),children:[c.value?we(c.value):e.jsx("span",{children:s("edit.form.expire_time_placeholder")}),e.jsx(jt,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),e.jsx(xs,{className:"w-auto p-0",align:"start",side:"top",sideOffset:4,onInteractOutside:h=>{h.preventDefault()},onEscapeKeyDown:h=>{h.preventDefault()},children:e.jsxs("div",{className:"flex flex-col space-y-3 p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(P,{type:"button",variant:"outline",className:"flex-1",onClick:()=>{c.onChange(null),l(!1)},children:s("edit.form.expire_time_permanent")}),e.jsx(P,{type:"button",variant:"outline",className:"flex-1",onClick:()=>{const h=new Date;h.setMonth(h.getMonth()+1),h.setHours(23,59,59,999),c.onChange(Math.floor(h.getTime()/1e3)),l(!1)},children:s("edit.form.expire_time_1month")}),e.jsx(P,{type:"button",variant:"outline",className:"flex-1",onClick:()=>{const h=new Date;h.setMonth(h.getMonth()+3),h.setHours(23,59,59,999),c.onChange(Math.floor(h.getTime()/1e3)),l(!1)},children:s("edit.form.expire_time_3months")})]}),e.jsx("div",{className:"rounded-md border",children:e.jsx(Gs,{mode:"single",selected:c.value?new Date(c.value*1e3):void 0,onSelect:h=>{if(h){const _=new Date(c.value?c.value*1e3:Date.now());h.setHours(_.getHours(),_.getMinutes(),_.getSeconds()),c.onChange(Math.floor(h.getTime()/1e3))}},disabled:h=>h{const h=new Date;h.setHours(23,59,59,999),c.onChange(Math.floor(h.getTime()/1e3))},className:"h-6 px-2 text-xs",children:s("edit.form.expire_time_today")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(T,{type:"datetime-local",step:"1",value:we(c.value,"YYYY-MM-DDTHH:mm:ss"),onChange:h=>{const _=new Date(h.target.value);isNaN(_.getTime())||c.onChange(Math.floor(_.getTime()/1e3))},className:"flex-1"}),e.jsx(P,{type:"button",variant:"outline",onClick:()=>l(!1),children:s("edit.form.expire_time_confirm")})]})]})]})})]}),e.jsx(D,{})]})}),e.jsx(g,{control:o.control,name:"plan_id",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.subscription")}),e.jsx(y,{children:e.jsxs(G,{value:c.value!==null?String(c.value):"null",onValueChange:h=>c.onChange(h==="null"?null:parseInt(h)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:s("edit.form.subscription_none")})}),e.jsxs(B,{children:[e.jsx(z,{value:"null",children:s("edit.form.subscription_none")}),d.map(h=>e.jsx(z,{value:String(h.id),children:h.name},h.id))]})]})})]})}),e.jsx(g,{control:o.control,name:"banned",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.account_status")}),e.jsx(y,{children:e.jsxs(G,{value:c.value.toString(),onValueChange:h=>c.onChange(parseInt(h)),children:[e.jsx(K,{children:e.jsx(W,{})}),e.jsxs(B,{children:[e.jsx(z,{value:"1",children:s("columns.status_text.banned")}),e.jsx(z,{value:"0",children:s("columns.status_text.normal")})]})]})})]})}),e.jsx(g,{control:o.control,name:"commission_type",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.commission_type")}),e.jsx(y,{children:e.jsxs(G,{value:c.value.toString(),onValueChange:h=>c.onChange(parseInt(h)),children:[e.jsx(K,{children:e.jsx(W,{placeholder:s("edit.form.subscription_none")})}),e.jsxs(B,{children:[e.jsx(z,{value:"0",children:s("edit.form.commission_type_system")}),e.jsx(z,{value:"1",children:s("edit.form.commission_type_cycle")}),e.jsx(z,{value:"2",children:s("edit.form.commission_type_onetime")})]})]})})]})}),e.jsx(g,{control:o.control,name:"commission_rate",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.commission_rate")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value||"",onChange:h=>c.onChange(parseInt(h.currentTarget.value)||null),placeholder:s("edit.form.commission_rate_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"%"})]})})]})}),e.jsx(g,{control:o.control,name:"discount",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.discount")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value||"",onChange:h=>c.onChange(parseInt(h.currentTarget.value)||null),placeholder:s("edit.form.discount_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"%"})]})}),e.jsx(D,{})]})}),e.jsx(g,{control:o.control,name:"speed_limit",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.speed_limit")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value||"",onChange:h=>c.onChange(parseInt(h.currentTarget.value)||null),placeholder:s("edit.form.speed_limit_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"Mbps"})]})}),e.jsx(D,{})]})}),e.jsx(g,{control:o.control,name:"device_limit",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.device_limit")}),e.jsx(y,{children:e.jsxs("div",{className:"flex",children:[e.jsx(T,{type:"number",value:c.value||"",onChange:h=>c.onChange(parseInt(h.currentTarget.value)||null),placeholder:s("edit.form.device_limit_placeholder"),className:"rounded-r-none"}),e.jsx("div",{className:"z-[-1] rounded-md rounded-l-none border border-l-0 border-input px-3 py-1 shadow-sm",children:"台"})]})}),e.jsx(D,{})]})}),e.jsx(g,{control:o.control,name:"is_admin",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.is_admin")}),e.jsx("div",{className:"py-2",children:e.jsx(y,{children:e.jsx(Y,{checked:c.value===1,onCheckedChange:h=>c.onChange(h?1:0)})})})]})}),e.jsx(g,{control:o.control,name:"is_staff",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.is_staff")}),e.jsx("div",{className:"py-2",children:e.jsx(y,{children:e.jsx(Y,{checked:c.value===1,onCheckedChange:h=>c.onChange(h?1:0)})})})]})}),e.jsx(g,{control:o.control,name:"remarks",render:({field:c})=>e.jsxs(f,{children:[e.jsx(j,{children:s("edit.form.remarks")}),e.jsx(y,{children:e.jsx(ys,{className:"h-24",value:c.value||"",onChange:h=>c.onChange(h.currentTarget.value??null),placeholder:s("edit.form.remarks_placeholder")})}),e.jsx(D,{})]})}),e.jsxs(ol,{children:[e.jsx(P,{variant:"outline",onClick:()=>t(!1),children:s("edit.form.cancel")}),e.jsx(P,{type:"submit",onClick:()=>{o.handleSubmit(c=>{ud(c).then(({data:h})=>{h&&(A.success(s("edit.form.success")),t(!1),a())})})()},children:s("edit.form.submit")})]})]})]})})}function Ah(){const[s]=fr(),[n,t]=u.useState({}),[r,a]=u.useState({is_admin:!1,is_staff:!1}),[i,l]=u.useState([]),[d,m]=u.useState([]),[o,c]=u.useState({pageIndex:0,pageSize:20});u.useEffect(()=>{const v=s.get("email");v&&l(M=>M.some(se=>se.id==="email")?M:[...M,{id:"email",value:v}])},[s]);const{refetch:h,data:_,isLoading:E}=re({queryKey:["userList",o,i,d],queryFn:()=>dd({pageSize:o.pageSize,current:o.pageIndex+1,filter:i,sort:d})}),[C,S]=u.useState([]),[w,b]=u.useState([]);u.useEffect(()=>{bt().then(({data:v})=>{S(v)}),qs().then(({data:v})=>{b(v)})},[]);const k=C.map(v=>({label:v.name,value:v.id})),p=w.map(v=>({label:v.name,value:v.id}));return e.jsxs(xl,{refreshData:h,children:[e.jsx($h,{data:_?.data??[],rowCount:_?.total??0,sorting:d,setSorting:m,columnVisibility:r,setColumnVisibility:a,rowSelection:n,setRowSelection:t,columnFilters:i,setColumnFilters:l,pagination:o,setPagination:c,refetch:h,serverGroupList:C,permissionGroups:k,subscriptionPlans:p}),e.jsx(hl,{})]})}function $h({data:s,rowCount:n,sorting:t,setSorting:r,columnVisibility:a,setColumnVisibility:i,rowSelection:l,setRowSelection:d,columnFilters:m,setColumnFilters:o,pagination:c,setPagination:h,refetch:_,serverGroupList:E,permissionGroups:C,subscriptionPlans:S}){const{setIsOpen:w,setEditingUser:b}=qa(),k=ns({data:s,columns:Lh(_,E,b,w),state:{sorting:t,columnVisibility:a,rowSelection:l,columnFilters:m,pagination:c},rowCount:n,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:d,onSortingChange:r,onColumnFiltersChange:o,onColumnVisibilityChange:i,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),onPaginationChange:h,getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnVisibility:{commission_balance:!1,created_at:!1,is_admin:!1,is_staff:!1,permission_group:!1,plan_id:!1},columnPinning:{right:["actions"]}}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Sh,{table:k,refetch:_,serverGroupList:E,permissionGroups:C,subscriptionPlans:S}),e.jsx(hs,{table:k})]})}function Uh(){const{t:s}=V("user");return e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("manage.title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("manage.description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx("div",{className:"w-full",children:e.jsx(Ah,{})})})]})]})}const Hh=Object.freeze(Object.defineProperty({__proto__:null,default:Uh},Symbol.toStringTag,{value:"Module"}));function qh({column:s,title:n,options:t}){const r=new Set(s?.getFilterValue());return e.jsxs(vs,{children:[e.jsx(bs,{asChild:!0,children:e.jsxs(J,{variant:"outline",size:"sm",className:"h-8 border-dashed",children:[e.jsx(Yo,{className:"mr-2 h-4 w-4"}),n,r?.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{orientation:"vertical",className:"mx-2 h-4"}),e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal lg:hidden",children:r.size}),e.jsx("div",{className:"hidden space-x-1 lg:flex",children:r.size>2?e.jsxs(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:[r.size," selected"]}):t.filter(a=>r.has(a.value)).map(a=>e.jsx(q,{variant:"secondary",className:"rounded-sm px-1 font-normal",children:a.label},`selected-${a.value}`))})]})]})}),e.jsx(xs,{className:"w-[200px] p-0",align:"start",children:e.jsxs(Ms,{children:[e.jsx(Ks,{placeholder:n}),e.jsxs(Fs,{children:[e.jsx(Bs,{children:"No results found."}),e.jsx(Ye,{children:t.map(a=>{const i=r.has(a.value);return e.jsxs(Me,{onSelect:()=>{i?r.delete(a.value):r.add(a.value);const l=Array.from(r);s?.setFilterValue(l.length?l:void 0)},children:[e.jsx("div",{className:N("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",i?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(Qo,{className:N("h-4 w-4")})}),a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:a.label})]},`option-${a.value}`)})}),r.size>0&&e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx(Ye,{children:e.jsx(Me,{onSelect:()=>s?.setFilterValue(void 0),className:"justify-center text-center",children:"Clear filters"})})]})]})]})})]})}const Kh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M19 11H5a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2"})});function Bh({table:s}){const{t:n}=V("ticket");return e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex flex-1 flex-col-reverse items-start gap-y-2 sm:flex-row sm:items-center sm:space-x-4",children:[e.jsx(Gt,{defaultValue:s.getColumn("status")?.getFilterValue(),onValueChange:t=>s.getColumn("status")?.setFilterValue(t),children:e.jsxs(vt,{className:"grid w-full grid-cols-2",children:[e.jsx(Ge,{value:"0",children:n("status.pending")}),e.jsx(Ge,{value:"1",children:n("status.closed")})]})}),s.getColumn("level")&&e.jsx(qh,{column:s.getColumn("level"),title:n("columns.level"),options:[{label:n("level.low"),value:Oe.LOW,icon:Kh,color:"gray"},{label:n("level.medium"),value:Oe.MIDDLE,icon:cl,color:"yellow"},{label:n("level.high"),value:Oe.HIGH,icon:dl,color:"red"}]})]})})}function Gh(){return e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",className:"text-foreground",children:[e.jsx("circle",{cx:"4",cy:"12",r:"2",fill:"currentColor",children:e.jsx("animate",{id:"spinner_qFRN",begin:"0;spinner_OcgL.end+0.25s",attributeName:"cy",calcMode:"spline",dur:"0.6s",values:"12;6;12",keySplines:".33,.66,.66,1;.33,0,.66,.33"})}),e.jsx("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor",children:e.jsx("animate",{begin:"spinner_qFRN.begin+0.1s",attributeName:"cy",calcMode:"spline",dur:"0.6s",values:"12;6;12",keySplines:".33,.66,.66,1;.33,0,.66,.33"})}),e.jsx("circle",{cx:"20",cy:"12",r:"2",fill:"currentColor",children:e.jsx("animate",{id:"spinner_OcgL",begin:"spinner_qFRN.begin+0.2s",attributeName:"cy",calcMode:"spline",dur:"0.6s",values:"12;6;12",keySplines:".33,.66,.66,1;.33,0,.66,.33"})})]})}const Wh=As("flex gap-2 max-w-[60%] items-end relative group",{variants:{variant:{received:"self-start",sent:"self-end flex-row-reverse"},layout:{default:"",ai:"max-w-full w-full items-center"}},defaultVariants:{variant:"received",layout:"default"}}),pl=u.forwardRef(({className:s,variant:n,layout:t,children:r,...a},i)=>e.jsx("div",{className:N(Wh({variant:n,layout:t,className:s}),"relative group"),ref:i,...a,children:u.Children.map(r,l=>u.isValidElement(l)&&typeof l.type!="string"?u.cloneElement(l,{variant:n,layout:t}):l)}));pl.displayName="ChatBubble";const Yh=As("p-4",{variants:{variant:{received:"bg-secondary text-secondary-foreground rounded-r-lg rounded-tl-lg",sent:"bg-primary text-primary-foreground rounded-l-lg rounded-tr-lg"},layout:{default:"",ai:"border-t w-full rounded-none bg-transparent"}},defaultVariants:{variant:"received",layout:"default"}}),fl=u.forwardRef(({className:s,variant:n,layout:t,isLoading:r=!1,children:a,...i},l)=>e.jsx("div",{className:N(Yh({variant:n,layout:t,className:s}),"break-words max-w-full whitespace-pre-wrap"),ref:l,...i,children:r?e.jsx("div",{className:"flex items-center space-x-2",children:e.jsx(Gh,{})}):a}));fl.displayName="ChatBubbleMessage";const Qh=u.forwardRef(({variant:s,className:n,children:t,...r},a)=>e.jsx("div",{ref:a,className:N("absolute top-1/2 -translate-y-1/2 flex opacity-0 group-hover:opacity-100 transition-opacity duration-200",s==="sent"?"-left-1 -translate-x-full flex-row-reverse":"-right-1 translate-x-full",n),...r,children:t}));Qh.displayName="ChatBubbleActionWrapper";const gl=u.forwardRef(({className:s,...n},t)=>e.jsx(ys,{autoComplete:"off",ref:t,name:"message",className:N("max-h-12 px-4 py-3 bg-background text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 w-full rounded-md flex items-center h-16 resize-none",s),...n}));gl.displayName="ChatInput";const jl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"m13.41 12l4.3-4.29a1 1 0 1 0-1.42-1.42L12 10.59l-4.29-4.3a1 1 0 0 0-1.42 1.42l4.3 4.29l-4.3 4.29a1 1 0 0 0 0 1.42a1 1 0 0 0 1.42 0l4.29-4.3l4.29 4.3a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42Z"})}),vl=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M15.098 12.634L13 11.423V7a1 1 0 0 0-2 0v5a1 1 0 0 0 .5.866l2.598 1.5a1 1 0 1 0 1-1.732M12 2a10 10 0 1 0 10 10A10.01 10.01 0 0 0 12 2m0 18a8 8 0 1 1 8-8a8.01 8.01 0 0 1-8 8"})}),pn=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"m11.29 12l3.54-3.54a1 1 0 0 0 0-1.41a1 1 0 0 0-1.42 0l-4.24 4.24a1 1 0 0 0 0 1.42L13.41 17a1 1 0 0 0 .71.29a1 1 0 0 0 .71-.29a1 1 0 0 0 0-1.41Z"})}),Jh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21.71 20.29L18 16.61A9 9 0 1 0 16.61 18l3.68 3.68a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.39M11 18a7 7 0 1 1 7-7a7 7 0 0 1-7 7"})}),Xh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M3.71 16.29a1 1 0 0 0-.33-.21a1 1 0 0 0-.76 0a1 1 0 0 0-.33.21a1 1 0 0 0-.21.33a1 1 0 0 0 .21 1.09a1.2 1.2 0 0 0 .33.21a.94.94 0 0 0 .76 0a1.2 1.2 0 0 0 .33-.21a1 1 0 0 0 .21-1.09a1 1 0 0 0-.21-.33M7 8h14a1 1 0 0 0 0-2H7a1 1 0 0 0 0 2m-3.29 3.29a1 1 0 0 0-1.09-.21a1.2 1.2 0 0 0-.33.21a1 1 0 0 0-.21.33a.94.94 0 0 0 0 .76a1.2 1.2 0 0 0 .21.33a1.2 1.2 0 0 0 .33.21a.94.94 0 0 0 .76 0a1.2 1.2 0 0 0 .33-.21a1.2 1.2 0 0 0 .21-.33a.94.94 0 0 0 0-.76a1 1 0 0 0-.21-.33M21 11H7a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2M3.71 6.29a1 1 0 0 0-.33-.21a1 1 0 0 0-1.09.21a1.2 1.2 0 0 0-.21.33a.94.94 0 0 0 0 .76a1.2 1.2 0 0 0 .21.33a1.2 1.2 0 0 0 .33.21a1 1 0 0 0 1.09-.21a1.2 1.2 0 0 0 .21-.33a.94.94 0 0 0 0-.76a1.2 1.2 0 0 0-.21-.33M21 16H7a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2"})}),Zh=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M9 12H7a1 1 0 0 0 0 2h2a1 1 0 0 0 0-2m-1-2h4a1 1 0 0 0 0-2H8a1 1 0 0 0 0 2m1 6H7a1 1 0 0 0 0 2h2a1 1 0 0 0 0-2m12-4h-3V3a1 1 0 0 0-.5-.87a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0l-3 1.72l-3-1.72a1 1 0 0 0-1 0A1 1 0 0 0 2 3v16a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-6a1 1 0 0 0-1-1M5 20a1 1 0 0 1-1-1V4.73l2 1.14a1.08 1.08 0 0 0 1 0l3-1.72l3 1.72a1.08 1.08 0 0 0 1 0l2-1.14V19a3 3 0 0 0 .18 1Zm15-1a1 1 0 0 1-2 0v-5h2Zm-6.44-2.83a.8.8 0 0 0-.18-.09a.6.6 0 0 0-.19-.06a1 1 0 0 0-.9.27A1.05 1.05 0 0 0 12 17a1 1 0 0 0 .07.38a1.2 1.2 0 0 0 .22.33a1.2 1.2 0 0 0 .33.21a.94.94 0 0 0 .76 0a1.2 1.2 0 0 0 .33-.21A1 1 0 0 0 14 17a1.05 1.05 0 0 0-.29-.71a2 2 0 0 0-.15-.12m.14-3.88a1 1 0 0 0-1.62.33A1 1 0 0 0 13 14a1 1 0 0 0 1-1a1 1 0 0 0-.08-.38a.9.9 0 0 0-.22-.33"})});function ep(){return e.jsxs("div",{className:"flex h-full flex-col space-y-4 p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"h-8 w-3/4"}),e.jsx(oe,{className:"h-4 w-1/2"})]}),e.jsx("div",{className:"flex-1 space-y-4",children:[1,2,3].map(s=>e.jsx(oe,{className:"h-20 w-2/3"},s))})]})}function sp(){return e.jsx("div",{className:"space-y-4 p-4",children:[1,2,3,4].map(s=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"h-5 w-4/5"}),e.jsx(oe,{className:"h-4 w-2/3"}),e.jsx(oe,{className:"h-3 w-1/2"})]},s))})}function tp({ticket:s,isActive:n,onClick:t}){const{t:r}=V("ticket"),a=i=>{switch(i){case Oe.HIGH:return"bg-red-50 text-red-600 border-red-200";case Oe.MIDDLE:return"bg-yellow-50 text-yellow-600 border-yellow-200";case Oe.LOW:return"bg-green-50 text-green-600 border-green-200";default:return"bg-gray-50 text-gray-600 border-gray-200"}};return e.jsxs("div",{className:N("flex cursor-pointer flex-col border-b p-4 hover:bg-accent/50",n&&"bg-accent"),onClick:t,children:[e.jsxs("div",{className:"flex max-w-[280px] items-center justify-between gap-2",children:[e.jsx("h4",{className:"flex-1 truncate font-medium",children:s.subject}),e.jsx(q,{variant:s.status===Vs.CLOSED?"secondary":"default",className:"shrink-0",children:s.status===Vs.CLOSED?r("status.closed"):r("status.processing")})]}),e.jsx("div",{className:"mt-1 max-w-[280px] truncate text-sm text-muted-foreground",children:s.user?.email}),e.jsxs("div",{className:"mt-2 flex items-center justify-between text-xs",children:[e.jsx("time",{className:"text-muted-foreground",children:we(s.updated_at)}),e.jsx("div",{className:N("rounded-full border px-2 py-0.5 text-xs font-medium",a(s.level)),children:r(`level.${s.level===Oe.LOW?"low":s.level===Oe.MIDDLE?"medium":"high"}`)})]})]})}function ap({ticketId:s,dialogTrigger:n}){const{t}=V("ticket"),r=Ts(),a=u.useRef(null),i=u.useRef(null),[l,d]=u.useState(!1),[m,o]=u.useState(""),[c,h]=u.useState(!1),[_,E]=u.useState(s),[C,S]=u.useState(""),[w,b]=u.useState(!1),{setIsOpen:k,setEditingUser:p}=qa(),{data:v,isLoading:M,refetch:H}=re({queryKey:["tickets",l],queryFn:()=>l?la.getList({filter:[{id:"status",value:[Vs.OPENING]}]}):Promise.resolve(null),enabled:l}),{data:se,refetch:L,isLoading:Z}=re({queryKey:["ticket",_,l],queryFn:()=>l?fd(_):Promise.resolve(null),refetchInterval:l?5e3:!1,retry:3}),de=se?.data,te=(v?.data||[]).filter(le=>le.subject.toLowerCase().includes(C.toLowerCase())||le.user?.email.toLowerCase().includes(C.toLowerCase())),$=(le="smooth")=>{if(a.current){const{scrollHeight:Os,clientHeight:Ws}=a.current;a.current.scrollTo({top:Os-Ws,behavior:le})}};u.useEffect(()=>{if(!l)return;const le=requestAnimationFrame(()=>{$("instant"),setTimeout(()=>$(),1e3)});return()=>{cancelAnimationFrame(le)}},[l,de?.messages]);const R=async()=>{const le=m.trim();!le||c||(h(!0),la.reply({id:_,message:le}).then(()=>{o(""),L(),$(),setTimeout(()=>{i.current?.focus()},0)}).finally(()=>{h(!1)}))},X=async()=>{la.close(_).then(()=>{A.success(t("actions.close_success")),L(),H()})},Ns=()=>{de?.user&&r("/finance/order?user_id="+de.user.id)},De=de?.status===Vs.CLOSED;return e.jsxs(be,{open:l,onOpenChange:d,children:[e.jsx(Je,{asChild:!0,children:n??e.jsx(J,{variant:"outline",children:t("actions.view_ticket")})}),e.jsxs(fe,{className:"flex h-[90vh] max-w-6xl flex-col gap-0 p-0",children:[e.jsx(ye,{}),e.jsxs("div",{className:"flex h-full",children:[e.jsx(J,{variant:"ghost",size:"icon",className:"absolute left-2 top-2 z-50 md:hidden",onClick:()=>b(!w),children:e.jsx(pn,{className:N("h-4 w-4 transition-transform",!w&&"rotate-180")})}),e.jsxs("div",{className:N("absolute inset-y-0 left-0 z-40 flex flex-col border-r bg-background transition-transform duration-200 ease-in-out md:relative",w?"-translate-x-full":"translate-x-0","w-80 md:w-80 md:translate-x-0"),children:[e.jsxs("div",{className:"space-y-4 border-b p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-semibold",children:t("list.title")}),e.jsx(J,{variant:"ghost",size:"icon",className:"hidden h-8 w-8 md:flex",onClick:()=>b(!w),children:e.jsx(pn,{className:N("h-4 w-4 transition-transform",!w&&"rotate-180")})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Jh,{className:"absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted-foreground"}),e.jsx(T,{placeholder:t("list.search_placeholder"),value:C,onChange:le=>S(le.target.value),className:"pl-8"})]})]}),e.jsx(zs,{className:"flex-1",children:e.jsx("div",{className:"w-full",children:M?e.jsx(sp,{}):te.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4 text-muted-foreground",children:t(C?"list.no_search_results":"list.no_tickets")}):te.map(le=>e.jsx(tp,{ticket:le,isActive:le.id===_,onClick:()=>{E(le.id),window.innerWidth<768&&b(!0)}},le.id))})})]}),e.jsxs("div",{className:"relative flex flex-1 flex-col",children:[!w&&e.jsx("div",{className:"absolute inset-0 z-30 bg-black/20 md:hidden",onClick:()=>b(!0)}),Z?e.jsx(ep,{}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col space-y-4 border-b p-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("h2",{className:"text-2xl font-semibold",children:de?.subject}),e.jsx(q,{variant:De?"secondary":"default",children:t(De?"status.closed":"status.processing")}),!De&&e.jsx(Qe,{title:t("actions.close_confirm_title"),description:t("actions.close_confirm_description"),confirmText:t("actions.close_confirm_button"),variant:"destructive",onConfirm:X,children:e.jsxs(J,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-destructive",children:[e.jsx(jl,{className:"h-4 w-4"}),t("actions.close_ticket")]})})]}),e.jsxs("div",{className:"flex items-center space-x-4 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx(gt,{className:"h-4 w-4"}),e.jsx("span",{children:de?.user?.email})]}),e.jsx(ke,{orientation:"vertical",className:"h-4"}),e.jsxs("div",{className:"flex items-center space-x-1",children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsxs("span",{children:[t("detail.created_at")," ",we(de?.created_at)]})]}),e.jsx(ke,{orientation:"vertical",className:"h-4"}),e.jsx(q,{variant:"outline",children:de?.level!=null&&t(`level.${de.level===Oe.LOW?"low":de.level===Oe.MIDDLE?"medium":"high"}`)})]})]}),de?.user&&e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(J,{variant:"outline",size:"icon",className:"h-8 w-8",title:t("detail.user_info"),onClick:()=>{p(de.user),k(!0)},children:e.jsx(gt,{className:"h-4 w-4"})}),e.jsx(ul,{user_id:de.user.id,dialogTrigger:e.jsx(J,{variant:"outline",size:"icon",className:"h-8 w-8",title:t("detail.traffic_records"),children:e.jsx(Xh,{className:"h-4 w-4"})})}),e.jsx(J,{variant:"outline",size:"icon",className:"h-8 w-8",title:t("detail.order_records"),onClick:Ns,children:e.jsx(Zh,{className:"h-4 w-4"})})]})]})}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx("div",{ref:a,className:"h-full space-y-4 overflow-y-auto p-6",children:de?.messages?.length===0?e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:t("detail.no_messages")}):de?.messages?.map(le=>e.jsx(pl,{variant:le.is_me?"sent":"received",className:le.is_me?"ml-auto":"mr-auto",children:e.jsx(fl,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"whitespace-pre-wrap break-words",children:le.message}),e.jsx("div",{className:"text-right",children:e.jsx("time",{className:"text-[10px] text-muted-foreground",children:we(le.created_at)})})]})})},le.id))})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs("div",{className:"relative flex items-center space-x-2",children:[e.jsx(gl,{ref:i,disabled:De||c,placeholder:t(De?"detail.input.closed_placeholder":"detail.input.reply_placeholder"),className:"flex-1 resize-none rounded-lg border bg-background p-3 focus-visible:ring-1",value:m,onChange:le=>o(le.target.value),onKeyDown:le=>{le.key==="Enter"&&!le.shiftKey&&(le.preventDefault(),R())}}),e.jsx(J,{disabled:De||c||!m.trim(),onClick:R,children:t(c?"detail.input.sending":"detail.input.send")})]})})]})]})]})]})]})}const np=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M19 4H5a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3V7a3 3 0 0 0-3-3m-.41 2l-5.88 5.88a1 1 0 0 1-1.42 0L5.41 6ZM20 17a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7.41l5.88 5.88a3 3 0 0 0 4.24 0L20 7.41Z"})}),rp=s=>e.jsx("svg",{className:"inline-block",viewBox:"0 0 24 24",width:"1.2em",height:"1.2em",...s,children:e.jsx("path",{fill:"currentColor",d:"M21.92 11.6C19.9 6.91 16.1 4 12 4s-7.9 2.91-9.92 7.6a1 1 0 0 0 0 .8C4.1 17.09 7.9 20 12 20s7.9-2.91 9.92-7.6a1 1 0 0 0 0-.8M12 18c-3.17 0-6.17-2.29-7.9-6C5.83 8.29 8.83 6 12 6s6.17 2.29 7.9 6c-1.73 3.71-4.73 6-7.9 6m0-10a4 4 0 1 0 4 4a4 4 0 0 0-4-4m0 6a2 2 0 1 1 2-2a2 2 0 0 1-2 2"})}),lp=s=>{const{t:n}=V("ticket");return[{accessorKey:"id",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.id")}),cell:({row:t})=>e.jsx(q,{variant:"outline",children:t.getValue("id")}),enableSorting:!1,enableHiding:!1},{accessorKey:"subject",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.subject")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(np,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"max-w-[500px] truncate font-medium",children:t.getValue("subject")})]}),enableSorting:!1,enableHiding:!1,size:4e3},{accessorKey:"level",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.level")}),cell:({row:t})=>{const r=t.getValue("level"),a=r===Oe.LOW?"default":r===Oe.MIDDLE?"secondary":"destructive";return e.jsx(q,{variant:a,className:"whitespace-nowrap",children:n(`level.${r===Oe.LOW?"low":r===Oe.MIDDLE?"medium":"high"}`)})},filterFn:(t,r,a)=>a.includes(t.getValue(r))},{accessorKey:"status",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.status")}),cell:({row:t})=>{const r=t.getValue("status"),a=t.original.reply_status,i=r===Vs.CLOSED?n("status.closed"):n(a===0?"status.replied":"status.pending"),l=r===Vs.CLOSED?"default":a===0?"secondary":"destructive";return e.jsx(q,{variant:l,className:"whitespace-nowrap",children:i})}},{accessorKey:"updated_at",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.updated_at")}),cell:({row:t})=>e.jsxs("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:we(t.getValue("updated_at"))})]}),enableSorting:!0},{accessorKey:"created_at",header:({column:t})=>e.jsx(O,{column:t,title:n("columns.created_at")}),cell:({row:t})=>e.jsx("div",{className:"text-sm text-muted-foreground",children:we(t.getValue("created_at"))}),enableSorting:!0,meta:{isFlexGrow:!0}},{id:"actions",header:({column:t})=>e.jsx(O,{className:"justify-end",column:t,title:n("columns.actions")}),cell:({row:t})=>{const r=t.original.status!==Vs.CLOSED;return e.jsxs("div",{className:"flex items-center justify-center",children:[e.jsx(ap,{ticketId:t.original.id,dialogTrigger:e.jsx(J,{variant:"ghost",size:"icon",className:"h-8 w-8",title:n("actions.view_details"),children:e.jsx(rp,{className:"h-4 w-4"})})}),r&&e.jsx(Qe,{title:n("actions.close_confirm_title"),description:n("actions.close_confirm_description"),confirmText:n("actions.close_confirm_button"),variant:"destructive",onConfirm:async()=>{gd(t.original.id).then(()=>{A.success(n("actions.close_success")),s()})},children:e.jsx(J,{variant:"ghost",size:"icon",className:"h-8 w-8",title:n("actions.close_ticket"),children:e.jsx(jl,{className:"h-4 w-4"})})})]})}}]};function ip(){const[s,n]=u.useState({}),[t,r]=u.useState({}),[a,i]=u.useState([{id:"status",value:"0"}]),[l,d]=u.useState([]),[m,o]=u.useState({pageIndex:0,pageSize:20}),{refetch:c,data:h}=re({queryKey:["orderList",m,a,l],queryFn:()=>pd({pageSize:m.pageSize,current:m.pageIndex+1,filter:a,sort:l})}),_=ns({data:h?.data??[],columns:lp(c),state:{sorting:l,columnVisibility:t,rowSelection:s,columnFilters:a,pagination:m},rowCount:h?.total??0,manualPagination:!0,manualFiltering:!0,manualSorting:!0,enableRowSelection:!0,onRowSelectionChange:n,onSortingChange:d,onColumnFiltersChange:i,onColumnVisibilityChange:r,getCoreRowModel:rs(),getFilteredRowModel:ds(),getPaginationRowModel:us(),onPaginationChange:o,getSortedRowModel:ms(),getFacetedRowModel:Ds(),getFacetedUniqueValues:Ps(),initialState:{columnPinning:{right:["actions"]}}});return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Bh,{table:_,refetch:c}),e.jsx(hs,{table:_,showPagination:!0})]})}function op(){const{t:s}=V("ticket");return e.jsxs(xl,{refreshData:()=>{},children:[e.jsxs(Ee,{children:[e.jsxs(Re,{children:[e.jsx(Ke,{}),e.jsxs("div",{className:"ml-auto flex items-center space-x-4",children:[e.jsx(Ae,{}),e.jsx($e,{})]})]}),e.jsxs(Fe,{className:"flex flex-col",fixedHeight:!0,children:[e.jsx("div",{className:"mb-2 flex items-center justify-between space-y-2",children:e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:s("title")}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:s("description")})]})}),e.jsx("div",{className:"-mx-4 flex-1 overflow-auto px-4 py-1 lg:flex-row lg:space-x-12 lg:space-y-0",children:e.jsx(ip,{})})]})]}),e.jsx(hl,{})]})}const cp=Object.freeze(Object.defineProperty({__proto__:null,default:op},Symbol.toStringTag,{value:"Module"}));export{hp as a,mp as c,xp as g,pp as r};