From 0dae9397b08f86387af36b2c1d18dd2c2d820a67 Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 28 Sep 2026 02:59:43 +0800 Subject: [PATCH] perf: streamline cloud deployment and billing --- web/app/Controllers/CloudAdminController.php | 20 ++ web/app/Controllers/CloudApiController.php | 203 ++++++++++++++---- web/app/Controllers/CloudPageController.php | 4 + .../Services/Cloud/CloudInvoiceService.php | 106 +++++++++ web/app/Services/Cloud/CloudOrderService.php | 44 +--- .../Services/Cloud/CloudUserIsoFeature.php | 47 ++++ web/app/Services/View.php | 5 + web/config/routes_cloud.php | 2 + web/public/cloud/admin.js | 25 ++- web/public/cloud/client.css | 6 + web/public/cloud/deploy.js | 3 +- web/public/cloud/detail.js | 12 +- web/public/cloud/invoices.js | 18 +- web/public/cloud/runtime.js | 179 ++++++++------- .../views/venix/admin/hosts/index.tpl | 10 +- .../views/venix/cloud/pages/deploy.tpl | 6 +- .../views/venix/cloud/pages/invoices.tpl | 5 + .../views/venix/cloud/pages/isos.tpl | 2 +- web/resources/views/venix/layout_assets.tpl | 2 +- .../views/venix/user/panel_sidebar.tpl | 2 + web/tests/CloudFinancialWorkflowTest.php | 15 ++ .../CloudInstanceReadPerformanceTest.php | 67 ++++++ web/tests/CloudInvoiceDetailContractTest.php | 29 +++ web/tests/CloudUserISOContractTest.php | 49 +++-- web/tests/VirtualizationAssetsTest.php | 37 +++- 25 files changed, 711 insertions(+), 187 deletions(-) create mode 100644 web/app/Services/Cloud/CloudUserIsoFeature.php create mode 100644 web/tests/CloudInstanceReadPerformanceTest.php diff --git a/web/app/Controllers/CloudAdminController.php b/web/app/Controllers/CloudAdminController.php index 17514747..f6422f1c 100644 --- a/web/app/Controllers/CloudAdminController.php +++ b/web/app/Controllers/CloudAdminController.php @@ -7,6 +7,7 @@ use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInput; use App\Services\Cloud\CloudInstanceDiscovery; +use App\Services\Cloud\CloudUserIsoFeature; final class CloudAdminController { @@ -139,6 +140,25 @@ final class CloudAdminController return $response->withJson((new CloudEngineClient())->host((int) $args['id'], 'POST', 'host/test', $actor, $body)); } + public function userIsoSettings($request, $response) + { + $write = $request->getMethod() !== 'GET'; + $this->actor($request, $write); + if (!$write) { + return $response->withJson(['enabled' => CloudUserIsoFeature::enabled()]); + } + + $body = CloudInput::object($request); + CloudInput::only($body, ['enabled']); + $enabled = filter_var($body['enabled'] ?? null, FILTER_VALIDATE_BOOLEAN, + FILTER_NULL_ON_FAILURE); + if ($enabled === null) { + throw new CloudError('用户 ISO 开关状态无效'); + } + CloudUserIsoFeature::save($enabled); + return $response->withJson(['enabled' => $enabled]); + } + public function templates($request, $response, $args = []) { $method = $request->getMethod(); diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index bb6d1d52..4d0a464c 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -23,6 +23,7 @@ use App\Services\Cloud\CloudInvoiceService; use App\Services\Cloud\CloudOrderService; use App\Services\Cloud\CloudSecrets; use App\Services\Cloud\CloudSSHKeys; +use App\Services\Cloud\CloudUserIsoFeature; final class CloudApiController { @@ -116,11 +117,16 @@ final class CloudApiController public function plans($request, $response) { $plans = []; - foreach (Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get() as $plan) { + $available = Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get(); + $hostIds = $available->pluck('host_id')->map(static fn ($id) => (int) $id) + ->filter(static fn ($id) => $id > 0)->unique()->values()->all(); + $hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds) + ->where('enabled', 1)->get()->keyBy('id'); + foreach ($available as $plan) { if ((int) $plan->stock === 0) { continue; } - $host = CloudHost::where('id', $plan->host_id)->where('enabled', 1)->first(); + $host = $hosts->get((int) $plan->host_id); if ($host !== null) { $plans[] = ['id' => (int) $plan->id, 'name' => $plan->name, 'price' => (string) $plan->price, 'cpu_cores' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib, @@ -208,17 +214,40 @@ final class CloudApiController return $this->createProvisionInvoice($request, $response, $actor); } $user = Auth::getUser(); - $invoices = CloudInvoice::where('user_id', $actor['user_id']) - // The unified page must never hide a newly-created opening bill - // behind older invoices whose service due dates are farther in - // the future. Keep all actionable bills first, then newest audit - // history; pagination can extend the historical tail later. + $query = $request->getQueryParams(); + $pageValue = $query['page'] ?? '1'; + if (is_array($pageValue) + || preg_match('/^[1-9][0-9]{0,8}$/D', (string) $pageValue) !== 1) { + throw new CloudError('账单页码无效'); + } + $perPage = 10; + $base = CloudInvoice::where('user_id', $actor['user_id']); + $total = (clone $base)->count(); + $totalPages = max(1, (int) ceil($total / $perPage)); + $page = min((int) $pageValue, $totalPages); + $records = (clone $base) + // A new actionable bill must not be hidden behind historical + // records whose service due date happens to be farther away. ->orderByRaw("CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END") - ->orderByDesc('created_at')->orderByDesc('id')->limit(200)->get() - ->map(fn ($invoice) => CloudInvoiceService::display($invoice))->all(); - return $this->json($response, ['invoices' => $invoices, - 'payment_methods' => CloudInvoicePaymentService::methods($user), - 'balance' => (string) $user->money]); + ->orderByDesc('created_at')->orderByDesc('id') + ->offset(($page - 1) * $perPage)->limit($perPage) + ->get(['id', 'purpose', 'instance_id', 'order_id', 'user_id', + 'due_at', 'amount', 'status', 'created_at']); + $count = $records->count(); + return $this->json($response, [ + 'invoices' => CloudInvoiceService::listSummaries($records), + 'pagination' => [ + 'page' => $page, + 'per_page' => $perPage, + 'total' => $total, + 'total_pages' => $totalPages, + 'has_previous' => $page > 1, + 'has_next' => $page < $totalPages, + 'from' => $count === 0 ? 0 : (($page - 1) * $perPage) + 1, + 'to' => $count === 0 ? 0 : (($page - 1) * $perPage) + $count, + ], + 'balance' => (string) $user->money, + ]); } private function createProvisionInvoice($request, $response, array $actor) @@ -300,26 +329,119 @@ final class CloudApiController return $this->json($response, CloudJobService::display($job)); } - private function vmData(CloudInstance $instance, array $actor): array + private function unavailableVm(CloudInstance $instance): array + { + return ['name' => $instance->name, 'state' => 'unknown', + 'detail' => '宿主机暂时无法连接']; + } + + /** + * Resolve list-only VM dependencies in fixed-size database queries and one + * engine inventory request per visible host. The database collection is + * authoritative: an engine row is only merged when its UUID is present in + * the already actor-scoped instance collection. + */ + private function vmListContexts($instances, array $actor): array + { + if ($instances->isEmpty()) { + return []; + } + $instanceIds = $instances->pluck('id')->map(fn ($id) => (int) $id)->all(); + $hostIds = $instances->pluck('host_id')->map(fn ($id) => (int) $id) + ->unique()->values()->all(); + $periodIds = $instances->pluck('current_period_id')->filter( + fn ($id) => $id !== null)->map(fn ($id) => (int) $id)->unique()->values()->all(); + + $hosts = []; + foreach (CloudHost::whereIn('id', $hostIds)->get() as $host) { + $hosts[(int) $host->id] = $host; + } + $periods = []; + if ($periodIds !== []) { + foreach (CloudServicePeriod::whereIn('id', $periodIds) + ->whereIn('instance_id', $instanceIds)->get() as $period) { + $periods[(int) $period->id] = $period; + } + } + $futurePeriods = []; + foreach (CloudServicePeriod::whereIn('instance_id', $instanceIds) + ->where('status', 'scheduled') + ->selectRaw('instance_id, COUNT(*) AS period_count') + ->groupBy('instance_id')->get() as $row) { + $futurePeriods[(int) $row->instance_id] = (int) $row->period_count; + } + + $engine = new CloudEngineClient(); + $liveByInstance = []; + foreach ($instances->groupBy(fn ($instance) => (int) $instance->host_id) as $hostId => $group) { + $allowed = []; + foreach ($group as $instance) { + $allowed[strtolower((string) $instance->uuid)] = (int) $instance->id; + $liveByInstance[(int) $instance->id] = $this->unavailableVm($instance); + } + try { + $inventory = $engine->host((int) $hostId, 'GET', 'vms', $actor); + foreach (is_array($inventory['items'] ?? null) ? $inventory['items'] : [] as $vm) { + if (!is_array($vm) || !is_string($vm['uuid'] ?? null)) { + continue; + } + $instanceId = $allowed[strtolower(trim($vm['uuid']))] ?? null; + if ($instanceId !== null) { + $liveByInstance[$instanceId] = $vm; + } + } + } catch (CloudError $error) { + // Preserve a useful database-backed row when one host is down; + // another host's inventory must still remain visible. + } + } + + $contexts = []; + foreach ($instances as $instance) { + $period = $instance->current_period_id === null + ? null : ($periods[(int) $instance->current_period_id] ?? null); + if ($period !== null && (int) $period->instance_id !== (int) $instance->id) { + $period = null; + } + $contexts[(int) $instance->id] = [ + 'vm' => $liveByInstance[(int) $instance->id] ?? $this->unavailableVm($instance), + 'host' => $hosts[(int) $instance->host_id] ?? null, + 'period' => $period, + 'future_periods' => (int) ($futurePeriods[(int) $instance->id] ?? 0), + ]; + } + return $contexts; + } + + private function vmData(CloudInstance $instance, array $actor, ?array $context = null): array { $owner = (int) $instance->user_id === (int) $actor['user_id']; $global = ($actor['is_admin'] ?? false) && ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false); $spec = json_decode($instance->spec_json, true) ?: []; - try { - $vm = (new CloudEngineClient())->host((int) $instance->host_id, 'GET', 'vms/' . rawurlencode($instance->uuid), $actor); - } catch (CloudError $error) { - $vm = ['name' => $instance->name, 'state' => 'unknown', 'detail' => '宿主机暂时无法连接']; + if ($context === null) { + try { + $vm = (new CloudEngineClient())->host((int) $instance->host_id, 'GET', + 'vms/' . rawurlencode($instance->uuid), $actor); + } catch (CloudError $error) { + $vm = $this->unavailableVm($instance); + } + $host = CloudHost::find($instance->host_id); + $period = $instance->current_period_id === null ? null + : CloudServicePeriod::where('id', $instance->current_period_id) + ->where('instance_id', $instance->id)->first(); + $futurePeriods = CloudServicePeriod::where('instance_id', $instance->id) + ->where('status', 'scheduled')->count(); + } else { + $vm = is_array($context['vm'] ?? null) + ? $context['vm'] : $this->unavailableVm($instance); + $host = $context['host'] ?? null; + $period = $context['period'] ?? null; + $futurePeriods = max(0, (int) ($context['future_periods'] ?? 0)); } - $host = CloudHost::find($instance->host_id); $createdAt = ($spec['record_source'] ?? '') === 'discovered' ? (is_string($vm['created_at'] ?? null) && trim($vm['created_at']) !== '' ? $vm['created_at'] : null) : gmdate('Y-m-d\TH:i:s\Z', (int) $instance->created_at); - $period = $instance->current_period_id === null ? null - : CloudServicePeriod::where('id', $instance->current_period_id) - ->where('instance_id', $instance->id)->first(); - $futurePeriods = CloudServicePeriod::where('instance_id', $instance->id) - ->where('status', 'scheduled')->count(); $maximumFuturePeriods = max(1, min(120, (int) Config::get('cloud_max_renewal_periods_ahead', 24))); $lifecycleActive = (string) $instance->status === 'active'; @@ -364,8 +486,11 @@ final class CloudApiController if (!$actor['is_admin']) { $query->where('user_id', $actor['user_id']); } - return $this->json($response, ['vms' => $query->orderByDesc('id')->limit(200)->get()->map( - fn ($instance) => $this->vmData($instance, $actor))->all()]); + $instances = $query->orderByDesc('id')->limit(200)->get(); + $contexts = $this->vmListContexts($instances, $actor); + return $this->json($response, ['vms' => $instances->map( + fn ($instance) => $this->vmData($instance, $actor, + $contexts[(int) $instance->id] ?? []))->all()]); } public function vm($request, $response, $args) @@ -567,28 +692,23 @@ final class CloudApiController } } $engine = new CloudEngineClient(); + if (!isset($query['vm_id'])) { + // Deployment needs only the cloud template catalog. Avoid the + // expensive resources, rescue ISO and personal ISO calls here. + $templates = $engine->host($hostId, 'GET', 'vm-templates', $actor); + return $this->json($response, [ + 'host_id' => $hostId, + 'templates' => $templates['templates'] ?? [], + ]); + } $value = $engine->host($hostId, 'GET', 'resources', $actor); $templates = $engine->host($hostId, 'GET', 'vm-templates', $actor); $rescue = $engine->host($hostId, 'GET', 'rescue-templates', $actor); // The configured root ISO pool can contain administrator or legacy - // files. Ordinary deployment only exposes actor-owned catalog IDs. + // files and is never exposed through this user API. unset($value['isos'], $value['iso_images']); $value['templates'] = $templates['templates'] ?? []; $value['rescue_templates'] = $rescue['templates'] ?? []; - $value['user_isos'] = []; - if (!isset($query['vm_id'])) { - try { - $userIsos = $engine->request('GET', '/internal/v1/user-isos', $actor); - $value['user_isos'] = $this->publicUserIsoRecords($userIsos['isos'] ?? []); - } catch (CloudError $error) { - // During a code-only online update PHP can briefly run ahead - // of the restarted engine. A missing new endpoint must not - // break cloud-template deployment; all other errors fail shut. - if ($error->httpStatus !== 404) { - throw $error; - } - } - } $value['host_id'] = $hostId; return $this->json($response, $value); } @@ -605,6 +725,7 @@ final class CloudApiController public function userIsos($request, $response) { $actor = $this->actor($request); + CloudUserIsoFeature::assertEnabled(); $engine = new CloudEngineClient(); if ($request->getMethod() === 'POST') { $this->userIsoImportAllowed($actor, true); @@ -635,6 +756,7 @@ final class CloudApiController public function userIsoJob($request, $response, $args) { $actor = $this->actor($request); + CloudUserIsoFeature::assertEnabled(); $jobId = (string) ($args['job_id'] ?? ''); if (preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $jobId) !== 1) { throw new CloudError('ISO 下载任务编号无效'); @@ -650,6 +772,7 @@ final class CloudApiController public function deleteUserIso($request, $response, $args) { $actor = $this->actor($request); + CloudUserIsoFeature::assertEnabled(); $isoId = (string) ($args['id'] ?? ''); if (preg_match('/^[0-9a-f]{32}$/D', $isoId) !== 1) { throw new CloudError('ISO 镜像标识无效'); diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 828c2cfb..9e0bc0c2 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -2,6 +2,7 @@ namespace App\Controllers; +use App\Services\Cloud\CloudUserIsoFeature; use App\Services\View; /** User pages deliberately do not load the administrator theme styles. */ @@ -34,6 +35,9 @@ final class CloudPageController public function isoImages($request, $response, $args) { + if (!CloudUserIsoFeature::enabled()) { + return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); + } return $this->render($response, 'isos', 'ISO 镜像'); } diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index d9051df9..00b5dc9e 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -306,6 +306,112 @@ final class CloudInvoiceService }, 3); } + /** + * Build the compact rows used by the paginated invoice list without + * loading the order, instance and job once for every invoice. + * + * @param iterable $invoices + * @return array> + */ + public static function listSummaries(iterable $invoices): array + { + $records = []; + $orderIds = []; + $renewalInstanceIds = []; + $ownerIds = []; + foreach ($invoices as $invoice) { + if (!$invoice instanceof CloudInvoice) { + continue; + } + $records[] = $invoice; + $ownerIds[(int) $invoice->user_id] = (int) $invoice->user_id; + $purpose = (string) ($invoice->purpose ?: 'renewal'); + if ($purpose === 'provision' && $invoice->order_id !== null) { + $orderIds[(int) $invoice->order_id] = (int) $invoice->order_id; + } elseif ($purpose === 'renewal' && $invoice->instance_id !== null) { + $renewalInstanceIds[(int) $invoice->instance_id] + = (int) $invoice->instance_id; + } + } + if ($records === []) { + return []; + } + + $orders = []; + if ($orderIds !== []) { + foreach (CloudOrder::whereIn('id', array_values($orderIds)) + ->whereIn('user_id', array_values($ownerIds)) + ->get(['id', 'user_id', 'status']) as $order) { + $orders[self::listKey((int) $order->user_id, (int) $order->id)] = $order; + } + } + $instances = []; + if ($renewalInstanceIds !== []) { + foreach (CloudInstance::whereIn('id', array_values($renewalInstanceIds)) + ->whereIn('user_id', array_values($ownerIds)) + ->get(['id', 'user_id', 'status']) as $instance) { + $instances[self::listKey((int) $instance->user_id, (int) $instance->id)] + = $instance; + } + } + $jobs = []; + if ($orderIds !== []) { + foreach (CloudJob::whereIn('order_id', array_values($orderIds)) + ->whereIn('user_id', array_values($ownerIds)) + ->get(['id', 'order_id', 'user_id', 'status']) as $job) { + $jobs[self::listKey((int) $job->user_id, (int) $job->order_id)] = $job; + } + } + + $now = time(); + $summaries = []; + foreach ($records as $invoice) { + $ownerId = (int) $invoice->user_id; + $purpose = (string) ($invoice->purpose ?: 'renewal'); + $title = match ($purpose) { + 'recharge' => '余额充值', + 'provision' => '实例开通', + 'renewal' => '实例续费', + default => '账单', + }; + $order = $purpose === 'provision' && $invoice->order_id !== null + ? ($orders[self::listKey($ownerId, (int) $invoice->order_id)] ?? null) + : null; + $job = $order === null + ? null : ($jobs[self::listKey($ownerId, (int) $order->id)] ?? null); + $instance = $purpose === 'renewal' && $invoice->instance_id !== null + ? ($instances[self::listKey($ownerId, (int) $invoice->instance_id)] ?? null) + : null; + $status = (string) $invoice->status; + if ($purpose === 'renewal' + && ($instance === null || (string) $instance->status === 'deleted')) { + if (in_array($status, ['open', 'overdue'], true)) { + $status = 'void'; + } + } elseif ($status === 'open' && (int) $invoice->due_at <= $now) { + $status = 'overdue'; + } + $summaries[] = [ + 'id' => (string) $invoice->id, + 'title' => $title, + 'type_label' => $title, + 'purpose' => $purpose, + 'amount' => (string) $invoice->amount, + 'status' => $status, + 'created_at' => (int) $invoice->created_at, + 'order_status' => $order?->status, + 'fulfillment_status' => $job?->status ?? $order?->status, + 'job_status' => $job?->status, + ]; + } + return $summaries; + } + + private static function listKey(int $userId, int $recordId): string + { + return $userId . ':' . $recordId; + } + public static function display(CloudInvoice $invoice): array { $now = time(); diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index 6d82ea5b..c4a997d0 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -16,7 +16,7 @@ final class CloudOrderService public static function purchase(array $input, array $actor): CloudOrder { - CloudInput::only($input, ['plan_id', 'source', 'template_id', 'iso_id', 'guest_ssh_key_id', + CloudInput::only($input, ['plan_id', 'source', 'template_id', 'guest_ssh_key_id', 'root_password', 'name', 'idempotency_key']); $name = CloudInput::name($input['name'] ?? null); $idempotency = $input['idempotency_key'] ?? ''; @@ -28,21 +28,13 @@ final class CloudOrderService throw new CloudError('请选择套餐'); } $source = $input['source'] ?? 'cloud'; - if (!in_array($source, ['cloud', 'iso'], true)) { - throw new CloudError('系统来源无效'); - } - $template = $input['template_id'] ?? ''; - $isoId = $input['iso_id'] ?? ''; - if ($source === 'cloud') { - $template = CloudInput::template($template); - } - if ($source === 'iso' && (!is_string($isoId) - || preg_match('/^[0-9a-f]{32}$/D', $isoId) !== 1)) { - throw new CloudError('请选择安装 ISO'); + if ($source !== 'cloud') { + throw new CloudError('当前只支持从云镜像部署实例'); } + $template = CloudInput::template($input['template_id'] ?? ''); ksort($input); $requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('payload_key')); - return (new User())->getConnection()->transaction(function () use ($input, $actor, $planId, $source, $name, $template, $isoId, $idempotency, $requestHash) { + return (new User())->getConnection()->transaction(function () use ($input, $actor, $planId, $source, $name, $template, $idempotency, $requestHash) { $user = User::where('id', $actor['user_id'])->lockForUpdate()->first(); if ($user === null || (int) $user->enable !== 1) { throw new CloudError('账户不可用', 403); @@ -72,31 +64,17 @@ final class CloudOrderService if ($host === null) { throw new CloudError('套餐对应宿主机暂不可用', 409); } - if ($source === 'iso') { - // The user row locked above is also locked by ISO deletion. - // Validate ownership and host scope while holding that common - // lock, so a concurrent delete cannot create an invalid bill. - $selected = (new CloudEngineClient())->request('GET', - '/internal/v1/user-isos/' . $isoId, $actor); - $selectedId = $selected['iso']['id'] ?? null; - if (!is_string($selectedId) || !hash_equals($isoId, $selectedId)) { - throw new CloudError('所选 ISO 不存在、已删除或不属于当前账户', 409); - } - } $price = CloudMoney::cents($plan->price); $payload = ['source' => $source, 'name' => $name, 'vcpu' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib, 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => $host->default_network]; $credential = null; - if ($source === 'cloud') { - $key = CloudSSHKeys::owned($input['guest_ssh_key_id'] ?? null, (int) $user->id); - $password = CloudInput::password($input['root_password'] ?? null); - $payload += ['template_id' => $template, 'guest_ssh_public_key' => $key?->public_key ?? '', - 'root_password' => $password, 'public_ip_cidr' => '', 'gateway' => '', 'dns_servers' => []]; - $credential = ['password' => $password, 'login_name' => 'root', 'auth_mode' => $key ? 'password_and_key' : 'password']; - } else { - $payload['user_iso_id'] = $isoId; - } + $key = CloudSSHKeys::owned($input['guest_ssh_key_id'] ?? null, (int) $user->id); + $password = CloudInput::password($input['root_password'] ?? null); + $payload += ['template_id' => $template, 'guest_ssh_public_key' => $key?->public_key ?? '', + 'root_password' => $password, 'public_ip_cidr' => '', 'gateway' => '', 'dns_servers' => []]; + $credential = ['password' => $password, 'login_name' => 'root', + 'auth_mode' => $key ? 'password_and_key' : 'password']; $safeSpec = CloudInput::safeResult($payload); $safeSpec['plan_name'] = $plan->name; $safeSpec['plan_id'] = (int) $plan->id; diff --git a/web/app/Services/Cloud/CloudUserIsoFeature.php b/web/app/Services/Cloud/CloudUserIsoFeature.php new file mode 100644 index 00000000..ed13831b --- /dev/null +++ b/web/app/Services/Cloud/CloudUserIsoFeature.php @@ -0,0 +1,47 @@ +value('value'); + } catch (\Throwable $error) { + error_log('Unable to read the user ISO feature switch: ' . get_class($error)); + return self::$cached = false; + } + + return self::$cached = in_array(strtolower(trim((string) $value)), + ['1', 'true', 'yes', 'on'], true); + } + + public static function assertEnabled(): void + { + if (!self::enabled()) { + throw new CloudError('用户 ISO 功能当前未开放', 403); + } + } + + public static function save(bool $enabled): void + { + $row = Configurations::where('name', self::CONFIG_KEY)->first(); + if ($row === null) { + $row = new Configurations(); + $row->name = self::CONFIG_KEY; + } + $row->value = $enabled ? 'true' : 'false'; + $row->save(); + self::$cached = $enabled; + } +} diff --git a/web/app/Services/View.php b/web/app/Services/View.php index eb76b58a..33151e0a 100644 --- a/web/app/Services/View.php +++ b/web/app/Services/View.php @@ -3,6 +3,7 @@ namespace App\Services; use App\Models\Configurations; +use App\Services\Cloud\CloudUserIsoFeature; use Smarty; class View @@ -53,6 +54,10 @@ class View 'transaction_records_visible', $user === null || !$user->isLogin || !UserFeatureRestrictionService::isTransactionRecordsRestricted($user) ); + // Navigation is rendered server-side, but the API repeats this check. + // Hiding this link is never treated as the authorisation boundary. + $smarty->assign('user_iso_enabled', is_object($user) && $user->isLogin + ? CloudUserIsoFeature::enabled() : false); return $smarty; } diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index b2402046..bc564a34 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -41,6 +41,8 @@ $app->group('/api/v1', function () { $this->map(['GET', 'POST'], '/admin/hosts', 'App\Controllers\CloudAdminController:hosts'); $this->map(['GET', 'PUT', 'PATCH'], '/admin/hosts/{id:[0-9]+}', 'App\Controllers\CloudAdminController:hosts'); $this->post('/admin/hosts/{id:[0-9]+}/test', 'App\Controllers\CloudAdminController:test'); + $this->map(['GET', 'PUT'], '/admin/user-iso/settings', + 'App\Controllers\CloudAdminController:userIsoSettings'); foreach (['cloud' => 'cloud-templates', 'rescue' => 'rescue-templates'] as $kind => $name) { $this->map(['GET', 'POST'], '/admin/' . $name, 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); $this->get('/admin/' . $name . '/import-jobs/{job_id}', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js index 8b17ad8d..545136bb 100644 --- a/web/public/cloud/admin.js +++ b/web/public/cloud/admin.js @@ -25,6 +25,29 @@ function unixTime(value) { return new Date(seconds * 1000).toLocaleString('zh-CN', { hour12: false }); } async function loadHosts() { state.hosts = collection(await api('/api/v1/admin/hosts'), 'hosts').map(profile); return state.hosts; } +async function loadUserIsoSettings() { + const settings = await api('/api/v1/admin/user-iso/settings'); + byId('user-iso-enabled').checked = settings?.enabled === true; +} +async function saveUserIsoSettings(event) { + event.preventDefault(); + if (state.busy) return; + const button = byId('user-iso-settings-save'); + state.busy = true; + button.disabled = true; + try { + const settings = await api('/api/v1/admin/user-iso/settings', { + method: 'PUT', body: { enabled: byId('user-iso-enabled').checked }, + }); + byId('user-iso-enabled').checked = settings?.enabled === true; + notice(settings?.enabled ? '用户 ISO 功能已开放。' : '用户 ISO 功能已关闭。'); + } catch (error) { + notice(error.message, true); + } finally { + state.busy = false; + button.disabled = !canManage; + } +} function resetScan() { state.scanned = null; state.scanTarget = ''; if (byId('host-fingerprint')) byId('host-fingerprint').textContent = ''; if (byId('host-fingerprint-confirm')) byId('host-fingerprint-confirm').checked = false; } function fillHost(host) { byId('host-form').reset(); resetScan(); const h = host || {}; byId('host-id').value = h.id || ''; byId('host-form-title').textContent = host ? `编辑宿主机 · ${h.name}` : '添加宿主机'; @@ -126,7 +149,7 @@ async function records() { async function initialize() { if (!root) return; try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。'); - if (root.dataset.cloudAdmin === 'hosts') { await loadHosts(); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); } + if (root.dataset.cloudAdmin === 'hosts') { await Promise.all([loadHosts(), loadUserIsoSettings()]); renderHosts(); fillHost(null); byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings); for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan); if (!canManage) { byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); byId('user-iso-settings-form').querySelectorAll('input,button').forEach(input => { input.disabled = true; }); } notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。'); } else if (['templates', 'rescue'].includes(root.dataset.cloudAdmin)) { await loadHosts(); const select = byId('catalog-host'); select.replaceChildren(); for (const host of state.hosts) { const option = element('option', '', `${host.name} · ${host.region || '地区未设置'}`); option.value = String(host.id); select.append(option); } select.addEventListener('change', loadCatalog); if (byId('template-import')) byId('template-import').addEventListener('submit', importTemplate); if (byId('rescue-upload')) byId('rescue-upload').addEventListener('submit', uploadRescue); await loadCatalog(); } else { byId('admin-records-refresh').addEventListener('click', records); await records(); } } catch (error) { notice(error.message, true); } diff --git a/web/public/cloud/client.css b/web/public/cloud/client.css index fdcd87d3..f356f1a9 100644 --- a/web/public/cloud/client.css +++ b/web/public/cloud/client.css @@ -58,6 +58,10 @@ .cloud-invoice-list-amount { grid-area: amount; min-width: 105px; text-align: right; } .cloud-invoice-list-amount span { display: block; margin-bottom: 5px; color: #91a0af; font-size: 10px; font-weight: 700; } .cloud-invoice-list-amount strong { display: block; color: #1e354d; font-size: 18px; line-height: 1.25; white-space: nowrap; } +.invoice-pagination { display: flex; align-items: center; justify-content: flex-end; gap: 12px; margin-top: 18px; } +.invoice-pagination[hidden] { display: none; } +.invoice-pagination > span { min-width: 145px; color: #75899b; font-size: 11px; font-weight: 700; text-align: center; } +.invoice-pagination[aria-busy="true"] > span { opacity: .65; } .invoice-detail-workspace { width: 100%; margin: 0 auto 48px; } .invoice-detail-heading { margin-bottom: 22px; } .inventory-panel.invoice-detail-card,.inventory-panel.invoice-detail-section { min-height: 0; overflow: hidden; } @@ -179,6 +183,8 @@ .cloud-order-actions .row-button { flex: 1 1 145px; } .invoice-balance-card { align-items: flex-start; flex-wrap: wrap; } .invoice-balance-card strong { flex: 1 1 calc(100% - 130px); } + .invoice-pagination { justify-content: space-between; gap: 8px; } + .invoice-pagination > span { min-width: 0; flex: 1; } .invoice-detail-hero { flex-direction: column; padding: 21px 18px; } .invoice-detail-total { justify-items: start; } .invoice-detail-total > strong { font-size: 22px; } diff --git a/web/public/cloud/deploy.js b/web/public/cloud/deploy.js index b0d8eed0..a69457cd 100644 --- a/web/public/cloud/deploy.js +++ b/web/public/cloud/deploy.js @@ -3,14 +3,13 @@ const assetVersion = new URL(import.meta.url).searchParams.get('v'); if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { bindPageCleanup, buy, byId, initializeSession, openCreate, - showError, updateSource, + showError, } = await import(runtimeUrl.href); export async function initialize() { try { if (!await initializeSession('create')) return; bindPageCleanup(); - byId('create-form')?.querySelectorAll('[name="source"]').forEach(radio => radio.addEventListener('change', updateSource)); byId('create-form')?.addEventListener('submit', buy); await openCreate(); } catch (error) { showError('cloud-page-error', error.message); } diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index dcbc613d..5a0e537f 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -4,8 +4,8 @@ if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { VM_DETAIL_TABS, bindPageCleanup, byId, clearCredential, clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential, - drawVmTrafficDaily, initializeSession, loadVmMetrics, loadVmTrafficDaily, - loadVms, renderVmDetail, renderVmMetrics, selectVmByApiId, + drawVmTrafficDaily, initializeSession, loadVm, loadVmMetrics, loadVmTrafficDaily, + renderVmDetail, renderVmMetrics, selectVmByApiId, selectedVm, setVmDetailTab, showError, state, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, } = await import(runtimeUrl.href); @@ -63,7 +63,7 @@ export async function initialize() { setVmDetailTab(state.detailTab); byId('vm-detail-refresh-button')?.addEventListener('click', async () => { - await loadVms(); + await loadVm(vmId); if (trafficDailyViewVisible()) await loadVmTrafficDaily(true); }); byId('vm-detail-ip-copy')?.addEventListener('click', async () => { @@ -97,7 +97,7 @@ export async function initialize() { if (timer !== null) window.clearInterval(timer); timer = window.setInterval(() => { if (!document.hidden) { - void loadVms(); + void loadVm(vmId); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); } }, 15000); @@ -109,13 +109,13 @@ export async function initialize() { }); window.addEventListener('pageshow', event => { if (!event.persisted) return; - void loadVms(); + void loadVm(vmId); setVmDetailTab(state.detailTab); startPolling(); }); document.addEventListener('visibilitychange', () => { if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); } - else { void loadVms(); setVmDetailTab(state.detailTab); } + else { void loadVm(vmId); setVmDetailTab(state.detailTab); } }); } catch (error) { showError('cloud-page-error', error.message); } } diff --git a/web/public/cloud/invoices.js b/web/public/cloud/invoices.js index 7e4ebdd2..e552bab9 100644 --- a/web/public/cloud/invoices.js +++ b/web/public/cloud/invoices.js @@ -10,13 +10,21 @@ export async function initialize() { try { if (!await initializeSession('invoices')) return; bindPageCleanup(); - byId('invoices-refresh')?.addEventListener('click', loadInvoices); - await loadInvoices(); + byId('invoices-refresh')?.addEventListener('click', () => { void loadInvoices(state.invoicePage); }); + byId('invoices-previous')?.addEventListener('click', () => { + if (state.invoiceLoading || !state.invoicePagination.has_previous) return; + void loadInvoices(Math.max(1, state.invoicePage - 1)); + }); + byId('invoices-next')?.addEventListener('click', () => { + if (state.invoiceLoading || !state.invoicePagination.has_next) return; + void loadInvoices(state.invoicePage + 1); + }); + await loadInvoices(1); let timer = null; const startPolling = () => { if (timer !== null) window.clearInterval(timer); timer = window.setInterval(() => { - if (!document.hidden && state.invoicePollTimers.size === 0) void loadInvoices(); + if (!document.hidden && state.invoicePollTimers.size === 0) void loadInvoices(state.invoicePage); }, 15000); }; startPolling(); @@ -26,12 +34,12 @@ export async function initialize() { }); window.addEventListener('pageshow', event => { if (!event.persisted) return; - void loadInvoices(); + void loadInvoices(state.invoicePage); startPolling(); }); document.addEventListener('visibilitychange', () => { if (document.hidden) stopInvoicePoll(); - else void loadInvoices(); + else void loadInvoices(state.invoicePage); }); } catch (error) { showError('cloud-page-error', error.message); } } diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 44b0398e..ecab3148 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -1,7 +1,7 @@ // PHP owns authentication, authorisation, ownership and purchasing. No engine // address, token, host credential or unrestricted create API exists in this UI. const byId = (id) => document.getElementById(id); -const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, selectedRegionHostId: '', invoices: [], invoicePaymentMethods: [], selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; +const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; // Keep the historical storage key so an interrupted deployment made just // before an online update can still reconcile to the same opening invoice. const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:'; @@ -10,7 +10,6 @@ const CLOUD_PATHS = Object.freeze({ instances: '/user/cloud/instances', deploy: '/user/cloud/deploy', keys: '/user/cloud/ssh-keys', - isos: '/user/cloud/iso-images', invoices: '/user/cloud/invoices', }); const vmPagePath = (id, child = '') => `${CLOUD_PATHS.instances}/${encodeURIComponent(String(id))}${child ? `/${child}` : ''}`; @@ -175,6 +174,31 @@ async function loadVms() { catch (error) { showError('cloud-page-error', error.message); if (!state.vms.length && byId('vm-table-body')) renderVMs(true); } finally { state.loadingVMs = false; } } +async function loadVm(apiId = selectedVm()?.api_id || document.body.dataset.vmId, raise = false) { + const id = String(apiId || ''); + if (!id) { + const error = new Error('虚拟机标识缺失。'); + showError('cloud-page-error', error.message); + if (raise) throw error; + return null; + } + if (state.loadingVMs) return selectedVm() || null; + state.loadingVMs = true; + try { + const vm = normalizeVm(await api(`/api/v1/vms/${encodeURIComponent(id)}`)); + state.vms = [vm]; + state.selectedVmId = vm.uuid; + showError('cloud-page-error', ''); + if (state.view === 'detail') renderVmDetail(vm); + return vm; + } catch (error) { + showError('cloud-page-error', error.message); + if (raise) throw error; + return null; + } finally { + state.loadingVMs = false; + } +} function renderVmDetail(vm) { text('vm-detail-name', vm.name); text('vm-detail-state', stateLabel(vm.state)); byId('vm-detail-state').className = `state-pill ${stateCategory(vm.state)}`; for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm)); @@ -227,7 +251,7 @@ function renderVmService(vm) { progress.classList.remove('is-exhausted'); } } -async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVms(); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } +async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVm(vm.api_id); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } async function deleteVm() { const vm = selectedVm(); if (!vm?.can_delete) return toast('当前账户无权删除该实例。', 'error'); if (state.mutationBusy) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true } }); toast('删除任务已提交,正在执行…'); if (result.job_id) await pollJob('delete', result.job_id); navigate(CLOUD_PATHS.instances); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); } async function credential(copy = false) { @@ -253,7 +277,6 @@ function renderKeyCards(kind) { for (const key of state.sshKeys) { const button = makeElement('button', 'ssh-key-option'); button.type = 'button'; button.setAttribute('aria-pressed', String(state.selectedKeys[kind] === String(key.id))); button.append(makeElement('strong', 'ssh-key-choice-label', key.name)); button.addEventListener('click', () => { state.selectedKeys[kind] = state.selectedKeys[kind] === String(key.id) ? '' : String(key.id); renderKeyCards(kind); }); container.append(button); } if (!state.sshKeys.length) container.append(makeElement('p', 'muted', '暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。')); } -function sourceMode() { return byId('create-form')?.querySelector('[name="source"]:checked')?.value || 'cloud'; } function flagForCountry(code) { const normalized = String(code || '').trim().toUpperCase(); if (!/^[A-Z]{2}$/.test(normalized)) return '🌐'; @@ -281,20 +304,9 @@ function setDeploymentStepEnabled(id, enabled) { function updateCreateAvailability() { const plan = state.plans.find(item => String(item.id) === byId('vm-plan')?.value); const validHost = plan && String(plan.host_id) === state.selectedRegionHostId; - const validMedia = sourceMode() === 'cloud' ? Boolean(byId('vm-template')?.value) : Boolean(byId('vm-iso')?.value); + const validMedia = Boolean(byId('vm-template')?.value); if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !validHost || !state.resources || !validMedia; } -function updateSource() { - if (state.mutationBusy) return; - const cloud = sourceMode() === 'cloud'; - byId('vm-iso-field').hidden = cloud; - byId('vm-iso').disabled = cloud || !state.resources; - byId('vm-template-field').hidden = !cloud; - byId('vm-template').disabled = !cloud || !state.resources; - byId('vm-cloud-fields').hidden = !cloud; - byId('vm-root-password').disabled = !cloud || !state.resources; - updateCreateAvailability(); -} function strongPassword(value) { return !value || (value.length >= 12 && new TextEncoder().encode(value).length <= 256 && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9\s]/.test(value) && !/[\r\n\0]/.test(value)); } function formatUsd(value) { const amount = Number(value); @@ -322,16 +334,13 @@ function planBillingLabel(plan) { const traffic = planTrafficBytes(plan); return `${days === null ? '账期未提供' : `${Math.floor(days)} 天/期`} · ${traffic === null ? '每期流量未提供' : `每期流量 ${formatTrafficQuota(traffic)}`}`; } -function resetInstallChoices(message = '请先选择实例规格。') { +function resetInstallChoices() { state.resourceController?.abort(); state.resourceController = null; state.resources = null; state.templates = []; byId('vm-template').value = ''; - byId('vm-iso').value = ''; renderTemplateCatalog('vm-template'); - byId('vm-iso-catalog').replaceChildren(makeElement('p', 'template-catalog-empty', message)); - byId('create-form').querySelectorAll('[name="source"]').forEach(radio => { radio.disabled = true; }); byId('vm-name').disabled = true; byId('vm-root-password').disabled = true; setDeploymentStepEnabled('vm-source-step', false); @@ -386,37 +395,6 @@ function renderPlanPicker() { }); container.replaceChildren(header, ...rows); } -function renderUserIsoCatalog(records) { - const input = byId('vm-iso'); - const container = byId('vm-iso-catalog'); - const isos = Array.isArray(records) ? records.filter(item => item && /^[0-9a-f]{32}$/.test(String(item.id || ''))) : []; - if (!isos.some(item => String(item.id) === input.value)) input.value = ''; - const cards = isos.map(record => { - const id = String(record.id); - const button = makeElement('button', 'user-iso-option'); - button.type = 'button'; - button.dataset.isoId = id; - button.setAttribute('aria-pressed', String(input.value === id)); - button.setAttribute('aria-label', `选择 ISO ${record.name || id}`); - button.append(makeElement('span', 'user-iso-symbol', '◉'), makeElement('strong', '', record.name || '未命名 ISO'), makeElement('small', '', formatBytes(firstNumber(record.size_bytes)))); - button.addEventListener('click', () => { - input.value = id; - container.querySelectorAll('.user-iso-option').forEach(option => option.setAttribute('aria-pressed', String(option.dataset.isoId === id))); - showError('create-error', ''); - updateCreateAvailability(); - }); - return button; - }); - if (!cards.length) { - const empty = makeElement('div', 'template-catalog-empty user-iso-empty'); - empty.append(makeElement('span', '', '你的全局个人库还没有 ISO。')); - const link = makeElement('a', 'ssh-key-picker-manage', '前往 ISO 上传'); - link.href = CLOUD_PATHS.isos; - empty.append(link); - cards.push(empty); - } - container.replaceChildren(...cards); -} async function selectRegion(hostId) { if (state.mutationBusy) return; const normalized = String(hostId || ''); @@ -428,7 +406,7 @@ async function selectRegion(hostId) { renderRegionPicker(); renderPlanPicker(); setDeploymentStepEnabled('vm-plan-step', true); - resetInstallChoices('请选择实例规格后加载你的全局个人 ISO。'); + resetInstallChoices(); showError('create-error', ''); } async function selectPlan(planId) { @@ -454,7 +432,7 @@ async function loadPlanResources() { const planId = byId('vm-plan').value; const plan = state.plans.find(item => String(item.id) === planId && String(item.host_id) === state.selectedRegionHostId); const epoch = ++state.formEpoch; - resetInstallChoices('正在加载全局个人 ISO…'); + resetInstallChoices(); state.resourceController = new AbortController(); if (!plan) return; try { @@ -463,12 +441,12 @@ async function loadPlanResources() { state.resources = resources; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); - renderUserIsoCatalog(items(resources.user_isos)); - byId('create-form').querySelectorAll('[name="source"]').forEach(radio => { radio.disabled = false; }); + byId('vm-template').disabled = false; byId('vm-name').disabled = false; + byId('vm-root-password').disabled = false; setDeploymentStepEnabled('vm-source-step', true); setDeploymentStepEnabled('vm-config-step', true); - updateSource(); + updateCreateAvailability(); } catch (error) { if (epoch === state.formEpoch && error.name !== 'AbortError') showError('create-error', error.message); } } function provisionInvoiceStorageKey() { return `${PROVISION_INVOICE_STORAGE_PREFIX}${state.userId || 'unknown'}`; } @@ -525,10 +503,9 @@ async function existingProvisionInvoice(key) { } async function buy(event) { event.preventDefault(); if (state.mutationBusy) return; - const cloud = sourceMode() === 'cloud'; const password = byId('vm-root-password').value; - if (cloud && !strongPassword(password)) return showError('create-error', '密码需至少 12 个字符,包含大写、小写、数字和符号。'); - if (cloud && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。'); - if (!cloud && !/^[0-9a-f]{32}$/.test(byId('vm-iso').value)) return showError('create-error', '请选择自己上传的安装 ISO。'); + const password = byId('vm-root-password').value; + if (!strongPassword(password)) return showError('create-error', '密码需至少 12 个字符,包含大写、小写、数字和符号。'); + if (!byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。'); if (!byId('vm-plan').value || !state.resources) return showError('create-error', '请先选择可用套餐。'); const selectedPlan = state.plans.find(plan => String(plan.id) === byId('vm-plan').value); if (!selectedPlan || String(selectedPlan.host_id) !== state.selectedRegionHostId) return showError('create-error', '地区与实例规格不匹配,请重新选择。'); @@ -538,8 +515,9 @@ async function buy(event) { const formBody = byId('create-form')?.querySelector('.workspace-form-body'); if (formBody) { formBody.inert = true; formBody.setAttribute('aria-busy', 'true'); } byId('create-submit').disabled = true; showError('create-error', ''); - const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: sourceMode() }; - if (cloud) { body.template_id = byId('vm-template').value; if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (password) body.root_password = password; } else body.iso_id = byId('vm-iso').value; + const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: 'cloud', template_id: byId('vm-template').value }; + if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; + if (password) body.root_password = password; try { const fingerprint = await provisionInvoiceFingerprint(body); const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint); @@ -888,6 +866,26 @@ function renderInvoices() { row.append(detail, actions, amount); container.append(row); } } +function renderInvoicePagination() { + const navigation = byId('invoices-pagination'); + if (!navigation) return; + const pagination = state.invoicePagination || {}; + const page = Math.max(1, Number(pagination.page) || 1); + const totalPages = Math.max(1, Number(pagination.total_pages) || 1); + const total = Math.max(0, Number(pagination.total) || 0); + navigation.hidden = total === 0; + navigation.setAttribute('aria-busy', String(state.invoiceLoading)); + text('invoices-page-label', `第 ${page} / ${totalPages} 页 · 共 ${total} 条`); + const previous = byId('invoices-previous'); + const next = byId('invoices-next'); + if (previous) previous.disabled = state.invoiceLoading || !pagination.has_previous; + if (next) next.disabled = state.invoiceLoading || !pagination.has_next; + const refresh = byId('invoices-refresh'); + if (refresh) { + refresh.disabled = state.invoiceLoading; + refresh.setAttribute('aria-busy', String(state.invoiceLoading)); + } +} function renderInvoiceSpecification(invoice) { const panel = byId('invoice-specification-panel'); const container = byId('invoice-specification'); @@ -1029,15 +1027,48 @@ async function loadInvoiceDetail(invoiceId = document.body.dataset.invoiceId) { renderInvoiceDetail(payload.invoice, payload); showError('cloud-page-error', ''); return payload.invoice; } catch (error) { showError('cloud-page-error', error.message); throw error; } } -async function loadInvoices() { +async function loadInvoices(page = state.invoicePage) { + if (state.invoiceLoading) return state.invoiceLoadPromise; + const requestedPage = Math.max(1, Math.trunc(Number(page) || state.invoicePage || 1)); + state.invoiceLoading = true; + renderInvoicePagination(); + const request = (async () => { + try { + const payload = await api(`/api/v1/invoices?page=${encodeURIComponent(requestedPage)}`); + const pagination = payload?.pagination && typeof payload.pagination === 'object' + ? payload.pagination : {}; + const actualPage = Math.max(1, Math.trunc(Number(pagination.page) || requestedPage)); + const totalPages = Math.max(1, Math.trunc(Number(pagination.total_pages) || 1)); + const total = Math.max(0, Math.trunc(Number(pagination.total) || 0)); + state.invoicePage = actualPage; + state.invoicePagination = { + page: actualPage, + per_page: Math.max(1, Math.trunc(Number(pagination.per_page) || 10)), + total, + total_pages: totalPages, + has_previous: pagination.has_previous === true || actualPage > 1, + has_next: pagination.has_next === true || actualPage < totalPages, + from: Math.max(0, Math.trunc(Number(pagination.from) || 0)), + to: Math.max(0, Math.trunc(Number(pagination.to) || 0)), + }; + state.invoices = Array.isArray(payload.invoices) ? payload.invoices : []; + text('invoices-balance', formatUsd(payload.balance)); + renderInvoices(); + showError('cloud-page-error', ''); + return payload; + } catch (error) { + showError('cloud-page-error', error.message); + return null; + } + })(); + state.invoiceLoadPromise = request; try { - const payload = await api('/api/v1/invoices'); - state.invoices = (Array.isArray(payload.invoices) ? payload.invoices : []).slice() - .sort((left, right) => Number(right.created_at || 0) - Number(left.created_at || 0) - || Number(right.id || 0) - Number(left.id || 0)); - state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : []; - text('invoices-balance', formatUsd(payload.balance)); renderInvoices(); showError('cloud-page-error', ''); - } catch (error) { showError('cloud-page-error', error.message); } + return await request; + } finally { + state.invoiceLoading = false; + state.invoiceLoadPromise = null; + renderInvoicePagination(); + } } async function openReinstall(vm) { if (!vm?.can_operate) return toast('实例服务已到期或正在执行策略,日常操作暂不可用。', 'error'); @@ -1824,10 +1855,8 @@ async function initializeSession(view) { } async function selectVmByApiId(apiId) { - await loadVms(); - const vm = state.vms.find(item => item.api_id === String(apiId)); + const vm = await loadVm(apiId, true); if (!vm) throw new Error('虚拟机不存在或当前账户无权访问。'); - state.selectedVmId = vm.uuid; return vm; } @@ -1847,9 +1876,9 @@ export { clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential, drawVmTrafficDaily, initializeSession, invoicePagePath, loadInvoiceDetail, loadInvoices, loadKeys, loadPlanResources, loadVmMetrics, loadVmTrafficDaily, - loadVms, navigate, openCreate, openReinstall, openRescue, reinstall, + loadVm, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm, scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics, - stopVmTrafficDaily, toast, trafficDailyViewVisible, updateSource, vmIp, + stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, vmPagePath, }; diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index 5f9648c0..2d209d35 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -5,6 +5,14 @@

宿主机设置

SSH 使用宿主机已有的 root 账号和私钥。先扫描并核对 SSH 主机指纹,再保存。私钥和口令加密存储,不会回显;后台会持续采集虚拟机指标。

正在加载…

+
+
+
用户 ISO 功能
+

默认关闭。关闭后普通用户看不到 ISO 导航和页面,相关读取、导入、任务及删除接口也会拒绝访问。

+ +
+
+
添加宿主机
@@ -16,7 +24,7 @@
仅通过 HTTPS 提交;请勿将密钥粘贴到工单或日志。
加密保存,面板重启后可自动连接,后台采样不依赖网页登录。
-
用户 ISO 会自动保存到此目录/<用户ID>/;必须使用目录类型存储池。
+
开放用户 ISO 功能后,个人镜像会同步到此目录;必须使用目录类型存储池。
只分配该地址池内未使用的地址;可输入 .113/28,后台会规范为 .112/28。
diff --git a/web/resources/views/venix/cloud/pages/deploy.tpl b/web/resources/views/venix/cloud/pages/deploy.tpl index b1f1f6e6..2e5c8bf0 100644 --- a/web/resources/views/venix/cloud/pages/deploy.tpl +++ b/web/resources/views/venix/cloud/pages/deploy.tpl @@ -15,10 +15,8 @@

请先选择地区。

-
3

选择安装方式

-
安装方式
-
系统镜像 *
- +
3

选择系统镜像

+
4

实例信息

diff --git a/web/resources/views/venix/cloud/pages/invoices.tpl b/web/resources/views/venix/cloud/pages/invoices.tpl index 5832074e..377aa2e3 100644 --- a/web/resources/views/venix/cloud/pages/invoices.tpl +++ b/web/resources/views/venix/cloud/pages/invoices.tpl @@ -2,4 +2,9 @@
BILLING

账单信息

部署实例时先生成开通账单,支付完成后才开始创建;实例到期前 7 天会自动生成续费账单。实例到期后立即停用网络,到期满 3 天仍未续费,实例及系统盘将被永久删除。

当前账户余额$—余额充值

正在加载…

+
diff --git a/web/resources/views/venix/cloud/pages/isos.tpl b/web/resources/views/venix/cloud/pages/isos.tpl index bdb80160..0cd3221a 100644 --- a/web/resources/views/venix/cloud/pages/isos.tpl +++ b/web/resources/views/venix/cloud/pages/isos.tpl @@ -1,5 +1,5 @@
-
PERSONAL INSTALL MEDIA

ISO 镜像

从 HTTPS 直链导入一次,即可在所有地区部署;首次使用时由面板自动同步至目标宿主机。

部署实例
+
PERSONAL INSTALL MEDIA

ISO 镜像

从 HTTPS 直链导入并保存到个人 ISO 库;此功能仅在管理员开放期间可用。

返回实例
↓

远程下载 ISO

填写可直接下载的 HTTPS 地址,完成后可用于全部宿主机。

diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 3907ca80..50ccb59d 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1 +1 @@ -{assign var=venix_asset_version value='2026092803' scope='global'} +{assign var=venix_asset_version value='2026092804' scope='global'} diff --git a/web/resources/views/venix/user/panel_sidebar.tpl b/web/resources/views/venix/user/panel_sidebar.tpl index 80d3c4e7..c6d56ca6 100644 --- a/web/resources/views/venix/user/panel_sidebar.tpl +++ b/web/resources/views/venix/user/panel_sidebar.tpl @@ -20,9 +20,11 @@ 部署实例 + {if !empty($user_iso_enabled)} ISO 上传 + {/if} SSH 公钥 diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index 17b9b107..bdcef594 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -79,6 +79,13 @@ namespace { $openingInvoice = CloudInvoice::where('order_id', $first->id)->first(); $openingDisplay = $openingInvoice === null ? [] : CloudInvoiceService::display($openingInvoice); + $connection = Capsule::connection('default'); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + $openingSummaries = $openingInvoice === null ? [] + : CloudInvoiceService::listSummaries(array_fill(0, 25, $openingInvoice)); + $summaryQueryCount = count($connection->getQueryLog()); + $connection->disableQueryLog(); $assert($first->id === $same->id && (string) $first->status === 'awaiting_payment' && $openingInvoice !== null @@ -95,6 +102,14 @@ namespace { && CloudJob::count() === 0 && Shop::find(1)->stock === 9, 'Idempotent deployment request charged money, queued work, lost its opening invoice, or reserved stock twice.'); + $assert(count($openingSummaries) === 25 + && $summaryQueryCount <= 3 + && array_keys($openingSummaries[0] ?? []) === [ + 'id', 'title', 'type_label', 'purpose', 'amount', 'status', 'created_at', + 'order_status', 'fulfillment_status', 'job_status', + ] + && ($openingSummaries[0]['order_status'] ?? null) === 'awaiting_payment', + 'Invoice list summaries are not compact or use per-invoice association queries.'); try { CloudOrderService::purchase($input + ['vcpu' => 64], $actor); throw new RuntimeException('Resource bypass accepted.'); } catch (CloudError $e) {} try { CloudOrderService::purchase(array_replace($input, ['name' => 'changed']), $actor); throw new RuntimeException('Idempotency conflict accepted.'); } catch (CloudError $e) { $assert($e->httpStatus === 409, 'Wrong idempotency response.'); } try { diff --git a/web/tests/CloudInstanceReadPerformanceTest.php b/web/tests/CloudInstanceReadPerformanceTest.php new file mode 100644 index 00000000..9f58b0d8 --- /dev/null +++ b/web/tests/CloudInstanceReadPerformanceTest.php @@ -0,0 +1,67 @@ + (int) \$instance->host_id)") + && substr_count($contexts, "->host((int) \$hostId, 'GET', 'vms', \$actor)") === 1, + 'Instance inventory is not requested once per visible host.'); +$assert(str_contains($contexts, 'CloudHost::whereIn') + && str_contains($contexts, 'CloudServicePeriod::whereIn') + && str_contains($contexts, "->groupBy('instance_id')"), + 'Instance host and service-period dependencies are no longer bulk loaded.'); +$assert(str_contains($contexts, + "\$allowed[strtolower((string) \$instance->uuid)] = (int) \$instance->id") + && str_contains($contexts, + "\$instanceId = \$allowed[strtolower(trim(\$vm['uuid']))] ?? null") + && str_contains($contexts, 'if ($instanceId !== null)'), + 'Engine inventory is not strictly intersected with actor-visible database UUIDs.'); +$assert(str_contains($list, '$contexts = $this->vmListContexts($instances, $actor)') + && str_contains($list, '$contexts[(int) $instance->id] ?? []'), + 'The VM list bypasses its bulk contexts and may reintroduce per-row reads.'); +$assert(str_contains($detailApi, + '$this->vmData(CloudAccess::instance($args[\'id\'], $actor), $actor)'), + 'The single-instance API no longer starts from the owner-scoped access check.'); + +$loadVm = $section($runtime, 'async function loadVm(', + 'function renderVmDetail('); +$selection = $section($runtime, 'async function selectVmByApiId(', + 'function bindPageCleanup('); +$assert(str_contains($loadVm, "api(`/api/v1/vms/\${encodeURIComponent(id)}`)") + && str_contains($loadVm, 'state.vms = [vm]'), + 'The detail loader does not use the single-instance API.'); +$assert(str_contains($selection, 'await loadVm(apiId, true)') + && !str_contains($selection, 'loadVms('), + 'Detail selection still fetches the full VM list.'); +$assert(!str_contains($detail, 'loadVms') + && substr_count($detail, 'loadVm(vmId)') >= 4, + 'Detail refresh or polling still loads every instance.'); + +echo "Cloud instance bulk-list and single-detail read paths passed.\n"; diff --git a/web/tests/CloudInvoiceDetailContractTest.php b/web/tests/CloudInvoiceDetailContractTest.php index 00b9cc16..d2dac1b8 100644 --- a/web/tests/CloudInvoiceDetailContractTest.php +++ b/web/tests/CloudInvoiceDetailContractTest.php @@ -41,6 +41,35 @@ $assert(str_contains($pageMethod, "'invoice-detail'") && str_contains($pageController, "assign('cloud_invoice_id', \$invoiceId)"), 'The detail page does not validate and pass its numeric invoice id independently.'); +$listMethod = $section($apiController, 'public function invoices(', + 'private function createProvisionInvoice('); +$assert(str_contains($listMethod, '$perPage = 10;') + && str_contains($listMethod, "\$query['page'] ?? '1'") + && str_contains($listMethod, "'pagination' => [") + && str_contains($listMethod, "'total_pages' => \$totalPages") + && str_contains($listMethod, 'CloudInvoiceService::listSummaries($records)'), + 'The invoice list is not using its fixed ten-row server-side pagination contract.'); +$assert(!str_contains($listMethod, 'CloudInvoiceService::display(') + && !str_contains($listMethod, 'CloudInvoicePaymentService::methods(') + && !str_contains($listMethod, "'payment_methods' =>"), + 'The list still expands full invoice details or exposes detail-only payment methods.'); +$summaryMethod = $section($invoiceService, 'public static function listSummaries(', + 'private static function listKey('); +$assert(substr_count($summaryMethod, '::whereIn(') === 3 + && str_contains($summaryMethod, "->get(['id', 'user_id', 'status'])") + && str_contains($summaryMethod, "->get(['id', 'order_id', 'user_id', 'status'])"), + 'Invoice list associations are not loaded with fixed-size batch queries.'); +foreach (['id', 'title', 'type_label', 'purpose', 'amount', 'status', 'created_at', + 'order_status', 'fulfillment_status', 'job_status'] as $field) { + $assert(str_contains($summaryMethod, "'{$field}' =>"), + 'Invoice list summary is missing field: ' . $field); +} +foreach (['payment_methods', 'payment_reference', 'paid_via', 'specification', + 'traffic_quota_bytes', 'payment_deadline_at'] as $detailOnlyField) { + $assert(!str_contains($summaryMethod, "'{$detailOnlyField}' =>"), + 'Invoice list summary leaked detail-only field: ' . $detailOnlyField); +} + $apiMethod = $section($apiController, 'public function invoice(', 'public function payInvoice('); $assert(str_contains($apiMethod, "CloudInvoice::where('id', \$args['id'])") diff --git a/web/tests/CloudUserISOContractTest.php b/web/tests/CloudUserISOContractTest.php index b4efc0a3..469f5cd8 100644 --- a/web/tests/CloudUserISOContractTest.php +++ b/web/tests/CloudUserISOContractTest.php @@ -12,12 +12,18 @@ $assert = static function ($condition, $message) { $routes = file_get_contents($web . '/config/routes_cloud.php'); $pages = file_get_contents($web . '/config/routes.php'); $controller = file_get_contents($web . '/app/Controllers/CloudApiController.php'); +$pageController = file_get_contents($web . '/app/Controllers/CloudPageController.php'); +$adminController = file_get_contents($web . '/app/Controllers/CloudAdminController.php'); +$feature = file_get_contents($web . '/app/Services/Cloud/CloudUserIsoFeature.php'); +$view = file_get_contents($web . '/app/Services/View.php'); $client = file_get_contents($web . '/app/Services/Cloud/CloudEngineClient.php'); $orders = file_get_contents($web . '/app/Services/Cloud/CloudOrderService.php'); $runtime = file_get_contents($web . '/public/cloud/runtime.js'); $isoClient = file_get_contents($web . '/public/cloud/iso-images.js'); $isoPage = file_get_contents($web . '/resources/views/venix/cloud/pages/isos.tpl'); $sidebar = file_get_contents($web . '/resources/views/venix/user/panel_sidebar.tpl'); +$hostAdmin = file_get_contents($web . '/resources/views/venix/admin/hosts/index.tpl'); +$adminClient = file_get_contents($web . '/public/cloud/admin.js'); $engine = file_get_contents($project . '/engine/virsh_panel/app.py'); $internal = file_get_contents($project . '/engine/virsh_panel/internal.py'); $userIsos = file_get_contents($project . '/engine/virsh_panel/user_isos.py'); @@ -28,12 +34,21 @@ $assert(str_contains($pages, "'/cloud/iso-images'") && str_contains($routes, "'/user-isos/import-jobs/{job_id:") && str_contains($routes, "'/user-isos/{id:[0-9a-f]{32}}'") && !str_contains($routes, "'/user-isos/targets'") + && str_contains($sidebar, '{if !empty($user_iso_enabled)}') && str_contains($sidebar, 'href="/user/cloud/iso-images"'), - 'The authenticated personal ISO page and API routes are incomplete.'); + 'The gated personal ISO page and API routes are incomplete.'); -$assert(str_contains($controller, "CloudInput::only(\$body, ['name', 'url'])") - && str_contains($controller, "unset(\$value['isos'], \$value['iso_images'])") - && str_contains($controller, "\$value['user_isos']") +$assert(substr_count($controller, 'CloudUserIsoFeature::assertEnabled();') === 3 + && str_contains($pageController, 'if (!CloudUserIsoFeature::enabled())') + && str_contains($feature, "public const CONFIG_KEY = 'cloud_user_iso_enabled'") + && str_contains($feature, 'return false;') + && str_contains($view, "assign('user_iso_enabled'") + && str_contains($view, '? CloudUserIsoFeature::enabled() : false') + && str_contains($adminController, 'public function userIsoSettings(') + && str_contains($routes, "['GET', 'PUT'], '/admin/user-iso/settings'") + && str_contains($hostAdmin, 'id="user-iso-enabled"') + && str_contains($adminClient, "api('/api/v1/admin/user-iso/settings'") + && str_contains($controller, "CloudInput::only(\$body, ['name', 'url'])") && str_contains($controller, "\$actor['can_manage'] = true") && str_contains($controller, "['awaiting_payment', 'queued', 'running', 'uncertain']") && str_contains($controller, "hash_equals(\$isoId, \$spec['user_iso_id'])") @@ -44,19 +59,27 @@ $assert(str_contains($controller, "CloudInput::only(\$body, ['name', 'url'])") && str_contains($controller, "User::where('id', \$actor['user_id'])->lockForUpdate()") && str_contains($client, 'safeUserIsoMessage') && str_contains($client, "?? '用户 ISO 操作未成功,请稍后重试或联系管理员'") - && str_contains($controller, 'if ($error->httpStatus !== 404)') && !str_contains($controller, 'userIsoTargets(') && !str_contains($controller, 'userIsoHost('), - 'PHP must expose only owner-scoped ISO records and a narrow remote-import request.'); + 'PHP must fail closed behind one global switch and retain owner-scoped ISO operations.'); -$assert(str_contains($orders, "'iso_id'") - && str_contains($orders, "\$payload['user_iso_id'] = \$isoId") - && str_contains($orders, "'/internal/v1/user-isos/' . \$isoId") - && str_contains($orders, 'hash_equals($isoId, $selectedId)') +$assert(str_contains($orders, "if (\$source !== 'cloud')") + && str_contains($orders, '当前只支持从云镜像部署实例') + && !str_contains($orders, "'iso_id'") + && !str_contains($orders, "\$payload['user_iso_id']") && !str_contains($orders, 'iso_path') - && str_contains($runtime, "body.iso_id = byId('vm-iso').value") + && str_contains($runtime, "source: 'cloud'") + && !str_contains($runtime, "body.iso_id") + && !str_contains($runtime, "byId('vm-iso')") && !str_contains($runtime, 'body.iso_path ='), - 'Provisioning must use opaque ISO IDs instead of browser-supplied host paths.'); + 'Provisioning must be cloud-template-only on both browser and server boundaries.'); + +$assert(str_contains($controller, "\$available->pluck('host_id')") + && str_contains($controller, "CloudHost::whereIn('id', \$hostIds)") + && str_contains($controller, 'Deployment needs only the cloud template catalog') + && str_contains($controller, "\$engine->host(\$hostId, 'GET', 'vm-templates', \$actor)") + && str_contains($controller, "'templates' => \$templates['templates'] ?? []"), + 'Plan listing must preload hosts and deployment resources must return a lightweight cloud-template catalog.'); $assert(str_contains($isoClient, 'epoch !== pageState.loadEpoch') && str_contains($isoClient, "error.name !== 'AbortError'") @@ -73,7 +96,7 @@ $assert(str_contains($isoClient, 'epoch !== pageState.loadEpoch') && !str_contains($isoClient, '/user-isos/targets'), 'Personal ISO UI must use one global owner library and recover safely from BFCache.'); -$assert(str_contains($isoPage, '即可在所有地区部署') +$assert(str_contains($isoPage, '仅在管理员开放期间可用') && str_contains($isoPage, '个人 ISO 库累计和单文件均不得超过 10 GiB') && str_contains($isoPage, '文件名必须以 .iso 结尾') && !str_contains($isoPage, '选择地区') diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php index fb7320b5..8cc7b28b 100644 --- a/web/tests/VirtualizationAssetsTest.php +++ b/web/tests/VirtualizationAssetsTest.php @@ -98,24 +98,28 @@ $assert(str_contains($baseStyles, '.ssh-key-details small{display:block;margin:0 $assert(str_contains($cloudTemplate, '>实例管理') && str_contains($cloudTemplate, '>部署实例'), 'Instance page terminology missing'); $assert(str_contains($sharedSidebar, '>我的实例') && str_contains($sharedSidebar, '>部署实例'), 'Shared sidebar instance terminology missing'); $assert(str_contains($sharedSidebar, 'href="/user/cloud/iso-images"') + && str_contains($sharedSidebar, '{if !empty($user_iso_enabled)}') && str_contains($sharedSidebar, '>ISO 上传') && str_contains($cloudShell, "cloud_page == 'isos'") && str_contains($clientEntry, "isos: '/cloud/iso-images.js'"), 'User-owned ISO page must be reachable from shared navigation and module bootstrap.'); $regionPosition = strpos($cloudTemplate, 'id="vm-region-picker"'); $planPosition = strpos($cloudTemplate, 'id="vm-plan-picker"'); -$sourcePosition = strpos($cloudTemplate, 'class="create-source-picker"'); +$sourcePosition = strpos($cloudTemplate, 'id="vm-template-catalog"'); $assert($regionPosition !== false && $planPosition > $regionPosition && $sourcePosition > $planPosition && str_contains($clientScript, 'function renderRegionPicker()') && str_contains($clientScript, 'function renderPlanPicker()') - && str_contains($clientScript, "body.iso_id = byId('vm-iso').value") - && str_contains($clientScript, 'if (cloud && !strongPassword(password))') + && str_contains($clientScript, "source: 'cloud'") + && !str_contains($clientScript, "body.iso_id") + && !str_contains($cloudTemplate, 'class="create-source-picker"') + && !str_contains($cloudTemplate, 'id="vm-iso"') + && str_contains($clientScript, 'if (!strongPassword(password))') && str_contains($clientScript, 'formBody.inert = true') && str_contains($clientScript, 'formBody.inert = false') && !str_contains($clientScript, 'body.iso_path ='), - 'Deployment must select region, then plan, then an opaque account-owned ISO ID.'); + 'Deployment must select region, plan and a cloud image without exposing an installation-mode switch.'); $planRendererStart = strpos($clientScript, 'function renderPlanPicker()'); -$planRendererEnd = strpos($clientScript, 'function renderUserIsoCatalog(', $planRendererStart); +$planRendererEnd = strpos($clientScript, 'async function selectRegion(', $planRendererStart); $planRenderer = $planRendererStart === false || $planRendererEnd === false ? '' : substr($clientScript, $planRendererStart, $planRendererEnd - $planRendererStart); @@ -184,6 +188,29 @@ $assert(str_contains($clientScript, "recharge: '余额充值', provision: '实 && str_contains($clientScript, "link.href = invoicePagePath(invoice.id)") && !str_contains($clientScript, 'invoice.invoice_no'), 'Invoice rows must use short database IDs, type labels, a right-aligned amount and a detail link.'); +$runtimeScript = file_get_contents($public . '/runtime.js'); +$invoicesModule = file_get_contents($public . '/invoices.js'); +$invoiceLoaderStart = strpos($runtimeScript, 'async function loadInvoices('); +$invoiceLoaderEnd = $invoiceLoaderStart === false ? false + : strpos($runtimeScript, 'async function openReinstall(', $invoiceLoaderStart); +$invoiceLoader = $invoiceLoaderStart === false || $invoiceLoaderEnd === false + ? '' : substr($runtimeScript, $invoiceLoaderStart, $invoiceLoaderEnd - $invoiceLoaderStart); +$assert(str_contains($cloudTemplate, 'id="invoices-pagination"') + && str_contains($cloudTemplate, 'id="invoices-previous"') + && str_contains($cloudTemplate, 'id="invoices-next"') + && str_contains($cloudTemplate, 'id="invoices-page-label"') + && str_contains($clientStyles, '.invoice-pagination'), + 'The invoice list is missing its accessible previous/next pagination controls.'); +$assert(str_contains($invoiceLoader, '/api/v1/invoices?page=${encodeURIComponent(requestedPage)}') + && str_contains($invoiceLoader, 'if (state.invoiceLoading) return state.invoiceLoadPromise;') + && str_contains($invoiceLoader, 'state.invoicePagination = {') + && !str_contains($invoiceLoader, 'payment_methods'), + 'Invoice pagination must fetch one server page at a time without detail-only payment data.'); +$assert(str_contains($invoicesModule, "byId('invoices-previous')") + && str_contains($invoicesModule, "byId('invoices-next')") + && str_contains($invoicesModule, 'loadInvoices(state.invoicePage + 1)') + && str_contains($invoicesModule, 'state.invoiceLoading'), + 'Invoice pages must load only after a guarded previous/next click.'); $assert(str_contains($cloudTemplate, 'id="invoice-payment-methods"') && str_contains($cloudTemplate, 'id="invoice-payment-submit"') && str_contains($clientScript, "{ id: 'balance', name: '账户余额'")