diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 9fe4d0ec..baf63f7e 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -8,7 +8,6 @@ use App\Models\CloudJob; use App\Models\CloudOrder; use App\Models\CloudServicePeriod; use App\Models\CloudSSHKey; -use App\Models\Shop; use App\Models\User; use App\Services\Auth; use App\Services\AdminCsrf; @@ -221,9 +220,9 @@ final class CloudApiController } } - public function plans($request, $response) + public function catalog($request, $response) { - return $this->json($response, ['plans' => CloudDeploymentPageService::plans()]); + return $this->json($response, CloudDeploymentPageService::saleCatalog()); } public function orders($request, $response) @@ -1221,10 +1220,9 @@ final class CloudApiController { $actor = $this->actor($request); $query = $request->getQueryParams(); - $engine = new CloudEngineClient(); // Cloud images are a panel-wide catalog. Host-specific replication is // owned by the private engine and must not make the browser reload or - // replace the catalog whenever a customer changes region or plan. + // replace the catalog whenever a customer changes region, line or offer. $catalog = CloudDeploymentPageService::freshTemplateCatalog($actor); $templatePayload = [ 'templates' => is_array($catalog['templates'] ?? null) @@ -1233,40 +1231,19 @@ final class CloudApiController // Replication state is a host-internal catalog detail. It can contain // pool names, source paths, or future engine fields and is not needed // by the user image picker, so never copy it into a public response. - if (isset($query['vm_id'])) { - $hostId = (int) CloudAccess::instance($query['vm_id'], $actor)->host_id; - } elseif (isset($query['plan_id'])) { - // Compatibility for a browser opened before global catalogs were - // deployed. New clients request /resources once without a plan. - $plan = Shop::where('id', $query['plan_id'] ?? 0)->where('status', 1)->first(); - $hostId = (int) ($plan?->host_id ?? 0); - if (!CloudHost::where('id', $hostId)->where('enabled', 1)->exists()) { - throw new CloudError('套餐宿主机不可用', 404); - } - } else { - return $this->json($response, $templatePayload); - } if (!isset($query['vm_id'])) { - return $this->json($response, $templatePayload + ['host_id' => $hostId]); + return $this->json($response, $templatePayload); } - $value = $engine->host($hostId, 'GET', 'resources', $actor); + $hostId = (int) CloudAccess::instance($query['vm_id'], $actor)->host_id; + $engine = new CloudEngineClient(); $rescue = $engine->host($hostId, 'GET', 'rescue-templates', $actor); - // The engine resource response contains host pool/bridge names and - // root-pool filenames. The browser only needs the public catalog and - // rescue display names, so construct a fixed DTO instead of unsetting - // a few currently-known fields and accidentally exposing future ones. + // The rescue response can contain host paths or future internal fields. + // The browser only needs display names, so construct a fixed DTO instead + // of unsetting a few currently-known fields and exposing future ones. $public = $templatePayload; $public['rescue_templates'] = $this->publicRescueTemplates( $rescue['templates'] ?? [] ); - $public['host_id'] = $hostId; - if (is_int($value['storage_available_gib'] ?? null) - || is_float($value['storage_available_gib'] ?? null)) { - $capacity = (float) $value['storage_available_gib']; - if (is_finite($capacity) && $capacity >= 0 && $capacity <= 1048576) { - $public['storage_available_gib'] = $capacity; - } - } return $this->json($response, $public); } diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index e9cd3ed6..f950ffe1 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -85,31 +85,52 @@ final class CloudPageController { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); - $plans = CloudDeploymentPageService::publicPagePlans(); - $regions = CloudDeploymentPageService::regions($plans); + $saleCatalog = CloudDeploymentPageService::saleCatalog(); + $regions = $saleCatalog['regions']; + $lines = $saleCatalog['lines']; + $offers = $saleCatalog['offers']; + $linesEnabled = $saleCatalog['lines_enabled'] === true; $catalog = CloudDeploymentPageService::templateCatalogForPage($actor); $templates = is_array($catalog['templates'] ?? null) ? $catalog['templates'] : []; $catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true; $keys = $this->sshKeyOptions((int) $actor['user_id']); - $defaultHostId = $regions === [] ? 0 : (int) $regions[0]['host_id']; - $bootstrapRegions = array_map(static fn (array $region): array => - array_diff_key($region, ['plans' => true]), $regions); + $defaultRegionId = $regions === [] ? 0 : (int) $regions[0]['id']; + $defaultLineId = 0; + $firstLineId = 0; + foreach ($lines as $line) { + if ((int) $line['region_id'] !== $defaultRegionId) { + continue; + } + $firstLineId = $firstLineId ?: (int) $line['id']; + if ($line['is_default'] === true) { + $defaultLineId = (int) $line['id']; + break; + } + } + $defaultLineId = $defaultLineId ?: $firstLineId; $payload = [ 'user' => $this->userBootstrap($user, $actor), - 'plans' => $plans, - 'regions' => $bootstrapRegions, + 'regions' => $regions, + 'lines' => $lines, + 'offers' => $offers, + 'lines_enabled' => $linesEnabled, 'templates' => $templates, 'ssh_keys' => $keys, - 'default_host_id' => $defaultHostId, + 'default_region_id' => $defaultRegionId, + 'default_line_id' => $defaultLineId, 'catalog_unavailable' => $catalogUnavailable, ]; return $this->render($response, 'deploy', '部署实例', '', '', [ 'cloud_deploy_regions' => $regions, + 'cloud_deploy_lines' => $lines, + 'cloud_deploy_offers' => $offers, + 'cloud_deploy_lines_enabled' => $linesEnabled, 'cloud_deploy_template_groups' => CloudDeploymentPageService::templateGroups($templates), 'cloud_deploy_ssh_keys' => $keys, - 'cloud_deploy_default_host_id' => $defaultHostId, + 'cloud_deploy_default_region_id' => $defaultRegionId, + 'cloud_deploy_default_line_id' => $defaultLineId, 'cloud_deploy_catalog_unavailable' => $catalogUnavailable, 'cloud_deploy_bootstrap_json' => $this->safeJson($payload), ]); @@ -283,9 +304,13 @@ final class CloudPageController $smarty->assign('cloud_detail_has_ssh_keys', false); $smarty->assign('cloud_detail_no_ssh_keys', true); $smarty->assign('cloud_deploy_regions', []); + $smarty->assign('cloud_deploy_lines', []); + $smarty->assign('cloud_deploy_offers', []); + $smarty->assign('cloud_deploy_lines_enabled', false); $smarty->assign('cloud_deploy_template_groups', []); $smarty->assign('cloud_deploy_ssh_keys', []); - $smarty->assign('cloud_deploy_default_host_id', 0); + $smarty->assign('cloud_deploy_default_region_id', 0); + $smarty->assign('cloud_deploy_default_line_id', 0); $smarty->assign('cloud_deploy_catalog_unavailable', false); $smarty->assign('cloud_deploy_bootstrap_json', '{}'); $smarty->assign('cloud_ssh_keys', []); diff --git a/web/app/Services/Cloud/CloudDeploymentPageService.php b/web/app/Services/Cloud/CloudDeploymentPageService.php index b4b6740a..8bf5b607 100644 --- a/web/app/Services/Cloud/CloudDeploymentPageService.php +++ b/web/app/Services/Cloud/CloudDeploymentPageService.php @@ -2,11 +2,10 @@ namespace App\Services\Cloud; -use App\Models\CloudHost; +use App\Models\CloudOffer; use App\Models\CloudSSHKey; use App\Models\CloudTemplateRetirement; use App\Models\Configurations; -use App\Models\Shop; /** * Database-backed first-paint data for instance deployment and reinstall. @@ -17,80 +16,98 @@ use App\Models\Shop; */ final class CloudDeploymentPageService { + private const GIB = 1073741824; private const TEMPLATE_SNAPSHOT_KEY = 'cloud_public_template_catalog_v1'; private const TEMPLATE_SNAPSHOT_VERSION = 1; private const TEMPLATE_SNAPSHOT_REFRESH_SECONDS = 300; - public static function plans(): array + /** + * Build the public Region -> Line -> Offer sale catalog. + * + * Hosts are not part of the sale catalog. Pools are read only to validate + * the active offer chain, and neither placement identity enters this DTO. + */ + public static function saleCatalog(): array { - $plans = []; - $available = Shop::where('status', 1)->orderBy('sort')->orderBy('id')->get(); - $hostIds = $available->pluck('host_id')->map(static fn ($id): int => (int) $id) - ->filter(static fn (int $id): bool => $id > 0)->unique()->values()->all(); - $hosts = $hostIds === [] ? collect() : CloudHost::whereIn('id', $hostIds) - ->where('enabled', 1)->get(['id', 'name', 'country_code', 'region'])->keyBy('id'); - - foreach ($available as $plan) { - if ((int) $plan->stock === 0) { - continue; - } - $host = $hosts->get((int) $plan->host_id); - if ($host === null) { - continue; - } - $plans[] = [ - 'id' => (int) $plan->id, - 'name' => (string) $plan->name, - 'price' => (string) $plan->price, - 'cpu_cores' => (int) $plan->cpu_cores, - 'memory_mib' => (int) $plan->memory_mib, - 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, - 'disk_gib' => (int) $plan->disk_gib, - 'validity_days' => (int) $plan->validity_days, - 'traffic_quota_bytes' => (int) $plan->traffic_quota_bytes, - 'traffic_gib' => $plan->trafficGiB(), - 'stock' => (int) $plan->stock, - 'host_id' => (int) $host->id, - 'host_name' => (string) $host->name, - 'country_code' => strtoupper(trim((string) ($host->country_code ?? ''))), - 'region' => trim((string) $host->region), - ]; + $linesEnabled = CloudNetworkLineFeature::enabled(); + $query = CloudOffer::query()->from('cloud_offers as offer') + ->join('shop as plan', 'plan.id', '=', 'offer.plan_id') + ->join('cloud_resource_pools as pool', 'pool.id', '=', 'offer.resource_pool_id') + ->join('cloud_network_lines as line', 'line.id', '=', 'pool.line_id') + ->join('cloud_regions as region', 'region.id', '=', 'line.region_id') + ->where('offer.status', 1) + ->where('offer.stock', '<>', 0) + ->where('offer.currency', 'USD') + ->where('plan.status', 1) + ->where('pool.status', 'active') + ->where('line.status', 'active') + ->where('region.status', 'active'); + if (!$linesEnabled) { + $query->where('line.is_default', 1); } - return $plans; - } - - /** Plans embedded in user HTML omit the administrator-facing host label. */ - public static function publicPagePlans(): array - { - return array_map(static function (array $plan): array { - unset($plan['host_name']); - return $plan; - }, self::plans()); - } + $rows = $query->orderByDesc('region.sort')->orderBy('region.id') + ->orderByDesc('line.sort')->orderBy('line.id') + ->orderByDesc('offer.sort')->orderBy('offer.id') + ->get([ + 'offer.id as offer_id', 'offer.name as offer_name', + 'offer.price as offer_price', + 'plan.cpu_cores', 'plan.memory_mib', 'plan.bandwidth_mbps', + 'plan.disk_gib', 'plan.validity_days', 'plan.traffic_quota_bytes', + 'line.id as line_id', 'line.name as line_name', 'line.is_default', + 'region.id as region_id', 'region.name as region_name', + 'region.country_code', + ]); - public static function regions(array $plans): array - { $regions = []; - foreach ($plans as $plan) { - $hostId = max(0, (int) ($plan['host_id'] ?? 0)); - if ($hostId === 0) { - continue; - } - if (!isset($regions[$hostId])) { - $countryCode = strtoupper(trim((string) ($plan['country_code'] ?? ''))); - $regions[$hostId] = [ - 'host_id' => $hostId, + $lines = []; + $offers = []; + foreach ($rows as $row) { + $regionId = (int) $row->region_id; + $lineId = (int) $row->line_id; + if (!isset($regions[$regionId])) { + $countryCode = strtoupper(trim((string) $row->country_code)); + $regions[$regionId] = [ + 'id' => $regionId, + 'name' => trim((string) $row->region_name), 'country_code' => $countryCode, 'flag' => self::countryFlag($countryCode), - 'region' => trim((string) ($plan['region'] ?? '')) ?: '地区未设置', - 'plans' => [], ]; } - $regions[$hostId]['plans'][] = $plan; + if (!isset($lines[$lineId])) { + $lines[$lineId] = [ + 'id' => $lineId, + 'region_id' => $regionId, + 'name' => trim((string) $row->line_name), + 'is_default' => (bool) $row->is_default, + ]; + } + $trafficBytes = max(0, (int) $row->traffic_quota_bytes); + $trafficGiB = intdiv($trafficBytes, self::GIB); + $offers[] = [ + 'id' => (int) $row->offer_id, + 'name' => trim((string) $row->offer_name), + 'price' => number_format((float) $row->offer_price, 2, '.', ''), + 'currency' => 'USD', + 'region_id' => $regionId, + 'line_id' => $lineId, + 'cpu_cores' => (int) $row->cpu_cores, + 'memory_mib' => (int) $row->memory_mib, + 'bandwidth_mbps' => (int) $row->bandwidth_mbps, + 'disk_gib' => (int) $row->disk_gib, + 'validity_days' => (int) $row->validity_days, + 'traffic_quota_bytes' => $trafficBytes, + 'traffic_gib' => $trafficGiB, + 'traffic_tib' => self::formatDecimalUnit($trafficGiB, 1024, 10), + ]; } - return array_values($regions); + return [ + 'lines_enabled' => $linesEnabled, + 'regions' => array_values($regions), + 'lines' => array_values($lines), + 'offers' => $offers, + ]; } public static function sshKeys(int $userId): array @@ -431,4 +448,11 @@ final class CloudDeploymentPageService return mb_chr(127397 + ord($countryCode[0]), 'UTF-8') . mb_chr(127397 + ord($countryCode[1]), 'UTF-8'); } + + private static function formatDecimalUnit(int $value, int $unit, int $precision): string + { + $formatted = number_format($value / $unit, $precision, '.', ''); + $formatted = rtrim(rtrim($formatted, '0'), '.'); + return $formatted === '' ? '0' : $formatted; + } } diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index b9ed4f7b..c57bb0d2 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -4,7 +4,7 @@ $app->get('/api/v1/session', 'App\Controllers\CloudApiController:session'); $app->post('/api/internal/cloud/session-introspection', 'App\Controllers\CloudInternalController:introspection'); $app->group('/api/v1', function () { $this->get('/announcements', 'App\Controllers\AnnouncementController:index'); - $this->get('/plans', 'App\Controllers\CloudApiController:plans'); + $this->get('/catalog', 'App\Controllers\CloudApiController:catalog'); $this->map(['GET', 'POST'], '/orders', 'App\Controllers\CloudApiController:orders'); $this->get('/orders/by-request/{key:[A-Za-z0-9_.-]+}', 'App\Controllers\CloudApiController:orderRequest'); diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 3bed4d54..7dd77784 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -3,7 +3,7 @@ import { toast } from './toast.js?v=2026100102'; // 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: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', 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, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; +const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', 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, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, 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:'; @@ -16,7 +16,7 @@ const CLOUD_PATHS = Object.freeze({ const vmPagePath = (id, child = '') => `${CLOUD_PATHS.instances}/${encodeURIComponent(String(id))}${child ? `/${child}` : ''}`; const navigate = (path) => location.assign(path); const text = (id, value) => { byId(id).textContent = value ?? '—'; }; -const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : []; +const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : []; function readBootstrap(id) { const source = byId(id); if (!source) return null; @@ -392,26 +392,60 @@ function flagForCountry(code) { return String.fromCodePoint(...Array.from(normalized, character => 127397 + character.charCodeAt(0))); } function saleRegions() { - const regions = new Map(); + const regions = []; + const seen = new Set(); for (const region of state.regions) { - const hostId = String(region?.host_id ?? region?.id ?? ''); - if (!/^\d+$/.test(hostId) || regions.has(hostId)) continue; - regions.set(hostId, { - hostId, + const id = String(region?.id ?? ''); + if (!/^[1-9]\d*$/.test(id) || seen.has(id)) continue; + seen.add(id); + regions.push({ + id, countryCode: String(region.country_code || '').trim().toUpperCase(), - region: String(region.region || region.name || '地区未设置').trim() || '地区未设置', + name: String(region.name || '地区未设置').trim() || '地区未设置', }); } - for (const plan of state.plans) { - const hostId = String(plan?.host_id || ''); - if (!/^\d+$/.test(hostId) || regions.has(hostId)) continue; - regions.set(hostId, { - hostId, - countryCode: String(plan.country_code || '').trim().toUpperCase(), - region: String(plan.region || '地区未设置').trim() || '地区未设置', + return regions; +} +function saleLines(regionId = state.selectedRegionId) { + const lines = []; + const seen = new Set(); + for (const line of state.lines) { + const id = String(line?.id ?? ''); + if (!/^[1-9]\d*$/.test(id) || seen.has(id) + || String(line?.region_id ?? '') !== String(regionId) + || (!state.linesEnabled && line?.is_default !== true)) continue; + seen.add(id); + lines.push({ + id, + regionId: String(line.region_id), + name: String(line.name || '线路未设置').trim() || '线路未设置', + isDefault: line.is_default === true, }); } - return Array.from(regions.values()); + return lines; +} +function saleOffers(regionId = state.selectedRegionId, lineId = state.selectedLineId) { + return state.offers.filter(offer => /^[1-9]\d*$/.test(String(offer?.id ?? '')) + && String(offer?.region_id ?? '') === String(regionId) + && String(offer?.line_id ?? '') === String(lineId) + && String(offer?.currency || '').toUpperCase() === 'USD'); +} +function defaultSaleLine(lines) { return lines.find(line => line.isDefault) || lines[0] || null; } +function applySaleCatalog(catalog) { + state.regions = bootstrapItems(catalog, 'regions'); + state.lines = bootstrapItems(catalog, 'lines'); + state.offers = bootstrapItems(catalog, 'offers'); + state.linesEnabled = catalog?.lines_enabled === true; + const regions = saleRegions(); + const requestedRegionId = String(catalog?.default_region_id ?? ''); + state.selectedRegionId = regions.some(region => region.id === requestedRegionId) + ? requestedRegionId : (regions[0]?.id || ''); + const lines = saleLines(state.selectedRegionId); + const requestedLineId = String(catalog?.default_line_id ?? ''); + state.selectedLineId = lines.some(line => line.id === requestedLineId) + ? requestedLineId : (defaultSaleLine(lines)?.id || ''); + byId('vm-region').value = state.selectedRegionId; + byId('vm-line').value = state.selectedLineId; } function setDeploymentStepEnabled(id, enabled) { const step = byId(id); @@ -420,36 +454,35 @@ function setDeploymentStepEnabled(id, enabled) { step.setAttribute('aria-disabled', String(!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 offer = saleOffers().find(item => String(item.id) === byId('vm-offer')?.value); const validMedia = Boolean(byId('vm-template')?.value); - if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !validHost || !validMedia; + if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !offer || !validMedia; } function strongPassword(value) { return !value || (value.length >= 12 && value.length <= 128 && /^[\x21-\x7e]+$/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9]/.test(value)); } function formatUsd(value) { const amount = Number(value); - if (!Number.isFinite(amount) || amount < 0) return '$—'; - return `$${amount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; + if (!Number.isFinite(amount) || amount < 0) return '$— USD'; + return `$${amount.toFixed(2)} USD`; } function formatMemoryGiB(memoryMib) { const amount = Number(memoryMib); if (!Number.isFinite(amount) || amount < 0) return '— GB'; return `${(amount / 1024).toLocaleString('en-US', { maximumFractionDigits: 1 })} GB`; } -function formatTrafficTiBFromGiB(trafficGiB) { - const amount = Number(trafficGiB); +function formatTrafficTiB(trafficTiB) { + const amount = Number(trafficTiB); if (!Number.isFinite(amount) || amount < 0) return '—'; if (amount === 0) return '不限'; - return `${(amount / 1024).toLocaleString('en-US', { maximumFractionDigits: 10 })} TB`; + return `${amount.toFixed(10).replace(/\.?0+$/, '')} TB`; } -function planValidityDays(plan) { return firstNumber(plan?.validity_days, plan?.service_days, plan?.period_days); } -function planTrafficBytes(plan) { - const gib = firstNumber(plan?.traffic_gib); - return firstNumber(plan?.traffic_quota_bytes, gib === null ? null : gib * 1024 ** 3); +function offerValidityDays(offer) { return firstNumber(offer?.validity_days, offer?.service_days, offer?.period_days); } +function offerTrafficBytes(offer) { + const gib = firstNumber(offer?.traffic_gib); + return firstNumber(offer?.traffic_quota_bytes, gib === null ? null : gib * 1024 ** 3); } -function planBillingLabel(plan) { - const days = planValidityDays(plan); - const traffic = planTrafficBytes(plan); +function offerBillingLabel(offer) { + const days = offerValidityDays(offer); + const traffic = offerTrafficBytes(offer); return `${days === null ? '账期未提供' : `${Math.floor(days)} 天/期`} · ${traffic === null ? '每期流量未提供' : `每期流量 ${formatTrafficQuota(traffic)}`}`; } function resetInstallChoices() { @@ -474,109 +507,151 @@ function renderRegionPicker() { const cards = saleRegions().map(region => { const button = makeElement('button', 'region-option'); button.type = 'button'; - button.dataset.hostId = region.hostId; - button.setAttribute('aria-pressed', String(state.selectedRegionHostId === region.hostId)); - button.setAttribute('aria-label', `选择地区 ${region.region}`); - button.append(makeElement('span', 'region-flag', flagForCountry(region.countryCode)), makeElement('strong', '', region.region)); - button.addEventListener('click', () => void selectRegion(region.hostId)); + button.dataset.regionId = region.id; + button.setAttribute('aria-pressed', String(state.selectedRegionId === region.id)); + button.setAttribute('aria-label', `选择地区 ${region.name}`); + button.append(makeElement('span', 'region-flag', flagForCountry(region.countryCode)), makeElement('strong', '', region.name)); + button.addEventListener('click', () => void selectRegion(region.id)); return button; }); if (!cards.length) cards.push(makeElement('p', 'template-catalog-empty', '暂无可部署地区,请联系管理员配置在售商品。')); container.replaceChildren(...cards); - byId('vm-region-host').value = state.selectedRegionHostId; -} -function renderPlanPicker() { - const container = byId('vm-plan-picker'); - const selectedPlanId = byId('vm-plan').value; - const plans = state.plans.filter(plan => String(plan.host_id) === state.selectedRegionHostId); - if (!plans.length) { - container.replaceChildren(makeElement('p', 'template-catalog-empty', '当前地区暂无可用实例规格。')); + byId('vm-region').value = state.selectedRegionId; +} +function renderLinePicker() { + const container = byId('vm-line-picker'); + if (!container) return; + const cards = saleLines().map(line => { + const button = makeElement('button', 'line-option'); + button.type = 'button'; + button.dataset.lineId = line.id; + button.setAttribute('aria-pressed', String(state.selectedLineId === line.id)); + button.setAttribute('aria-label', `选择线路 ${line.name}`); + button.append(makeElement('strong', '', line.name)); + button.addEventListener('click', () => void selectLine(line.id)); + return button; + }); + if (!cards.length) cards.push(makeElement('p', 'template-catalog-empty', '当前地区暂无可用线路。')); + container.replaceChildren(...cards); +} +function renderOfferPicker() { + const container = byId('vm-offer-picker'); + const selectedOfferId = byId('vm-offer').value; + const offers = saleOffers(); + if (!offers.length) { + container.replaceChildren(makeElement('p', 'template-catalog-empty', '当前选择暂无可用实例规格。')); return; } - const header = makeElement('div', 'plan-table-head'); - ['名称', 'CPU', '内存', '硬盘', '每月流量', '价格'].forEach(label => header.append(makeElement('span', '', label))); - const rows = plans.map(plan => { - const button = makeElement('button', 'plan-option'); - const memory = formatMemoryGiB(plan.memory_mib); - const traffic = formatTrafficTiBFromGiB(plan.traffic_gib); - const price = formatUsd(plan.price); + const header = makeElement('div', 'offer-table-head'); + ['名称', 'CPU', '内存', '硬盘', '每期流量', '价格'].forEach(label => header.append(makeElement('span', '', label))); + const rows = offers.map(offer => { + const button = makeElement('button', 'offer-option'); + const memory = formatMemoryGiB(offer.memory_mib); + const traffic = formatTrafficTiB(offer.traffic_tib); + const price = formatUsd(offer.price); button.type = 'button'; - button.dataset.planId = String(plan.id); - button.setAttribute('aria-pressed', String(selectedPlanId === String(plan.id))); - button.setAttribute('aria-label', `选择实例规格 ${plan.name},${plan.cpu_cores} vCPU,内存 ${memory},硬盘 ${plan.disk_gib} GB,每月流量 ${traffic},价格 ${price}`); + button.dataset.offerId = String(offer.id); + button.setAttribute('aria-pressed', String(selectedOfferId === String(offer.id))); + button.setAttribute('aria-label', `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price}`); button.append( - makeElement('strong', 'plan-option-name', plan.name), - makeElement('span', 'plan-option-value', `${plan.cpu_cores} vCPU`), - makeElement('span', 'plan-option-value', memory), - makeElement('span', 'plan-option-value', `${plan.disk_gib} GB`), - makeElement('span', 'plan-option-value', traffic), - makeElement('strong', 'plan-option-price', price), + makeElement('strong', 'offer-option-name', offer.name), + makeElement('span', 'offer-option-value', `${offer.cpu_cores} vCPU`), + makeElement('span', 'offer-option-value', memory), + makeElement('span', 'offer-option-value', `${offer.disk_gib} GB`), + makeElement('span', 'offer-option-value', traffic), + makeElement('strong', 'offer-option-price', price), ); - button.addEventListener('click', () => void selectPlan(String(plan.id))); + button.addEventListener('click', () => void selectOffer(String(offer.id))); return button; }); container.replaceChildren(header, ...rows); } -async function selectRegion(hostId) { +async function selectRegion(regionId) { if (state.mutationBusy) return; - const normalized = String(hostId || ''); - if (!saleRegions().some(region => region.hostId === normalized)) return; - if (state.selectedRegionHostId === normalized && byId('vm-plan').value) return; - state.selectedRegionHostId = normalized; - byId('vm-plan').value = ''; + const normalized = String(regionId || ''); + if (!saleRegions().some(region => region.id === normalized)) return; + if (state.selectedRegionId === normalized) return; + state.selectedRegionId = normalized; + state.selectedLineId = defaultSaleLine(saleLines(normalized))?.id || ''; + byId('vm-region').value = state.selectedRegionId; + byId('vm-line').value = state.selectedLineId; + byId('vm-offer').value = ''; renderRegionPicker(); - renderPlanPicker(); - setDeploymentStepEnabled('vm-plan-step', true); + renderLinePicker(); + renderOfferPicker(); + setDeploymentStepEnabled('vm-line-step', state.linesEnabled); + setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId)); + showError('create-error', ''); + updateCreateAvailability(); +} +async function selectLine(lineId) { + if (state.mutationBusy) return; + const line = saleLines().find(item => item.id === String(lineId)); + if (!line || state.selectedLineId === line.id) return; + state.selectedLineId = line.id; + byId('vm-line').value = line.id; + byId('vm-offer').value = ''; + byId('vm-line-picker')?.querySelectorAll('.line-option').forEach(button => { + button.setAttribute('aria-pressed', String(button.dataset.lineId === line.id)); + }); + renderOfferPicker(); + setDeploymentStepEnabled('vm-offer-step', true); showError('create-error', ''); updateCreateAvailability(); } -async function selectPlan(planId) { +async function selectOffer(offerId) { if (state.mutationBusy) return; - const plan = state.plans.find(item => String(item.id) === String(planId) && String(item.host_id) === state.selectedRegionHostId); - if (!plan) return; - byId('vm-plan').value = String(plan.id); - byId('vm-plan-picker').querySelectorAll('.plan-option').forEach(button => { - button.setAttribute('aria-pressed', String(button.dataset.planId === String(plan.id))); + const offer = saleOffers().find(item => String(item.id) === String(offerId)); + if (!offer) return; + byId('vm-offer').value = String(offer.id); + byId('vm-offer-picker').querySelectorAll('.offer-option').forEach(button => { + button.setAttribute('aria-pressed', String(button.dataset.offerId === String(offer.id))); }); showError('create-error', ''); updateCreateAvailability(); } async function openCreate(bootstrap = null) { state.view = 'create'; state.selectedVmId = null; showError('create-error', ''); - byId('vm-plan').value = ''; - if (bootstrap && Array.isArray(bootstrap.plans) && Array.isArray(bootstrap.templates)) { - state.regions = bootstrapItems(bootstrap, 'regions'); - state.plans = bootstrapItems(bootstrap, 'plans'); - if (!state.plans.length) state.plans = state.regions.flatMap(region => Array.isArray(region?.plans) ? region.plans : []); + byId('vm-offer').value = ''; + if (bootstrap && Array.isArray(bootstrap.offers) && Array.isArray(bootstrap.regions) + && Array.isArray(bootstrap.lines) && Array.isArray(bootstrap.templates)) { + applySaleCatalog(bootstrap); state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates'); state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true; state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys'); state.resources = { templates: state.templates }; state.selectedKeys.create = ''; - const regions = saleRegions(); - const requestedDefault = bootstrap.default_host_id ?? bootstrap.default_region?.host_id ?? bootstrap.default_region; - const requestedHostId = String(requestedDefault ?? ''); - state.selectedRegionHostId = regions.some(region => region.hostId === requestedHostId) - ? requestedHostId : (regions[0]?.hostId || ''); - byId('vm-region-host').value = state.selectedRegionHostId; renderRegionPicker(); - renderPlanPicker(); + renderLinePicker(); + renderOfferPicker(); renderTemplateCatalog('vm-template'); renderKeyCards('create'); byId('vm-template').disabled = !state.templates.some(item => item?.id); byId('vm-name').disabled = false; byId('vm-root-password').disabled = false; - setDeploymentStepEnabled('vm-plan-step', Boolean(state.selectedRegionHostId)); + setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId)); + setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId)); setDeploymentStepEnabled('vm-source-step', true); setDeploymentStepEnabled('vm-config-step', true); updateCreateAvailability(); return; } - state.regions = []; - state.selectedRegionHostId = ''; byId('vm-region-host').value = ''; - setDeploymentStepEnabled('vm-plan-step', false); resetInstallChoices(); + state.regions = []; state.lines = []; state.offers = []; state.linesEnabled = false; + state.selectedRegionId = ''; state.selectedLineId = ''; + byId('vm-region').value = ''; byId('vm-line').value = ''; + setDeploymentStepEnabled('vm-line-step', false); + setDeploymentStepEnabled('vm-offer-step', false); + resetInstallChoices(); const results = await Promise.allSettled([ - api('/api/v1/plans').then(plans => { state.plans = items(plans); renderRegionPicker(); }), + api('/api/v1/catalog').then(catalog => { + applySaleCatalog(catalog); + renderRegionPicker(); + renderLinePicker(); + renderOfferPicker(); + setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId)); + setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId)); + updateCreateAvailability(); + }), loadKeys(), loadGlobalTemplates(), ]); @@ -646,16 +721,16 @@ async function buy(event) { const password = byId('vm-root-password').value; if (!strongPassword(password)) return showError('create-error', '密码需为 12 至 128 位英文可打印字符且不能包含空格,并包含大写、小写、数字和符号。'); if (!byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。'); - if (!byId('vm-plan').value) 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', '地区与实例规格不匹配,请重新选择。'); - const purchaseSummary = selectedPlan ? `${formatUsd(selectedPlan.price)},${planBillingLabel(selectedPlan)}` : '所选套餐'; + if (!byId('vm-offer').value) return showError('create-error', '请先选择可用实例规格。'); + const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value); + if (!selectedOffer) return showError('create-error', '地区、线路与实例规格不匹配,请重新选择。'); + const purchaseSummary = `${formatUsd(selectedOffer.price)},${offerBillingLabel(selectedOffer)}`; if (!confirm(`确认创建此实例?将先生成 ${purchaseSummary} 的开通账单,支付完成后才会开始创建。`)) return; state.mutationBusy = true; 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: 'cloud', template_id: byId('vm-template').value }; + const body = { offer_id: Number(byId('vm-offer').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 { diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index 8bea679e..0055a522 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -201,7 +201,7 @@ tbody tr:hover{background:#fcfefe} #rescue-template-file{height:auto;padding:10px 12px} @media(max-width:510px){.rescue-template-cards{grid-template-columns:repeat(2,minmax(0,1fr))}.rescue-actions .button{width:100%}.rescue-template-row{align-items:flex-start;flex-direction:column}} -/* Region-first instance deployment and account-owned installation media. */ +/* Region/line/offer instance deployment and account-owned installation media. */ .deploy-flow{display:grid;gap:0} .deployment-step{min-width:0;padding:0 0 29px;margin:0 0 27px;border-bottom:1px solid #e8eef2;transition:opacity .18s} .deployment-step:last-of-type{margin-bottom:0;border-bottom:0} @@ -215,18 +215,23 @@ tbody tr:hover{background:#fcfefe} .region-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)} .region-option strong{min-width:0;font-size:13px;line-height:1.5;overflow-wrap:anywhere} .region-flag{display:grid;place-items:center;flex:none;width:38px;height:38px;border-radius:10px;background:#f0f4f7;font-size:25px;line-height:1} -.plan-picker{display:grid;min-width:0;overflow:hidden;border:1px solid #dce7ec;border-radius:11px;background:#fff} -.plan-table-head,.plan-option{display:grid;grid-template-columns:minmax(150px,1.35fr) repeat(5,minmax(92px,1fr));align-items:center;column-gap:18px} -.plan-table-head{padding:13px 48px 13px 19px;border-bottom:1px solid #e5ecef;background:#f8fafb;color:#8292a3;font-size:10px;font-weight:800} -.plan-option{position:relative;width:100%;min-width:0;min-height:72px;padding:15px 48px 15px 19px;border:0;border-bottom:1px solid #e7edef;border-radius:0;background:#fff;color:#4e6577;text-align:left} -.plan-option:last-of-type{border-bottom:0;border-bottom-right-radius:10px;border-bottom-left-radius:10px} -.plan-option:hover{background:#f7fbfc} -.plan-option:focus-visible{z-index:2;outline:3px solid rgba(18,166,176,.22);outline-offset:-3px} -.plan-option[aria-pressed="true"]{z-index:1;background:#eef9fa;box-shadow:inset 0 0 0 2px #2eabb4;color:#30485d} -.plan-option[aria-pressed="true"]::after{content:"✓";position:absolute;top:8px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900} -.plan-option-name,.plan-option-price{min-width:0;color:#273d52;font-size:12px;overflow-wrap:anywhere} -.plan-option-price{color:#0d929d;font-size:13px} -.plan-option-value{min-width:0;font-size:11px;font-weight:700;white-space:nowrap} +.line-picker{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px} +.line-option{min-width:0;min-height:58px;padding:13px 16px;border:1px solid #dce7ec;border-radius:11px;background:#fff;color:#30485d;text-align:left} +.line-option:hover{border-color:#87cdd1;background:#f8fcfc} +.line-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)} +.line-option strong{font-size:13px;line-height:1.5;overflow-wrap:anywhere} +.offer-picker{display:grid;min-width:0;overflow:hidden;border:1px solid #dce7ec;border-radius:11px;background:#fff} +.offer-table-head,.offer-option{display:grid;grid-template-columns:minmax(150px,1.35fr) repeat(5,minmax(92px,1fr));align-items:center;column-gap:18px} +.offer-table-head{padding:13px 48px 13px 19px;border-bottom:1px solid #e5ecef;background:#f8fafb;color:#8292a3;font-size:10px;font-weight:800} +.offer-option{position:relative;width:100%;min-width:0;min-height:72px;padding:15px 48px 15px 19px;border:0;border-bottom:1px solid #e7edef;border-radius:0;background:#fff;color:#4e6577;text-align:left} +.offer-option:last-of-type{border-bottom:0;border-bottom-right-radius:10px;border-bottom-left-radius:10px} +.offer-option:hover{background:#f7fbfc} +.offer-option:focus-visible{z-index:2;outline:3px solid rgba(18,166,176,.22);outline-offset:-3px} +.offer-option[aria-pressed="true"]{z-index:1;background:#eef9fa;box-shadow:inset 0 0 0 2px #2eabb4;color:#30485d} +.offer-option[aria-pressed="true"]::after{content:"✓";position:absolute;top:8px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900} +.offer-option-name,.offer-option-price{min-width:0;color:#273d52;font-size:12px;overflow-wrap:anywhere} +.offer-option-price{color:#0d929d;font-size:13px} +.offer-option-value{min-width:0;font-size:11px;font-weight:700;white-space:nowrap} /* Keep every user-facing button control free of browser or hover underlines. Plain content and navigation links intentionally keep their own styling. */ body[data-cloud-page] :is(button, [role="button"], .button, .row-button, .icon-button, .vu-btn, .vu-icon-btn), @@ -259,18 +264,18 @@ body.vu-body .ssh-key-picker-manage:hover { .user-isos-grid .host-test-status{margin:16px 0 0} @media(max-width:960px){.user-isos-grid{grid-template-columns:1fr}} @media(max-width:740px){ - .region-picker{grid-template-columns:repeat(2,minmax(0,1fr))} - .plan-table-head{display:none} - .plan-option:first-of-type{border-top-left-radius:10px;border-top-right-radius:10px} - .plan-option{grid-template-columns:repeat(2,minmax(0,1fr));gap:13px 18px;min-height:0;padding:18px 45px 18px 18px} - .plan-option-name{grid-column:1/-1;font-size:13px} - .plan-option-value,.plan-option-price{display:grid;gap:3px;white-space:normal} - .plan-option-value::before,.plan-option-price::before{color:#91a0ae;font-size:9px;font-weight:800} - .plan-option>:nth-child(2)::before{content:"CPU"} - .plan-option>:nth-child(3)::before{content:"内存"} - .plan-option>:nth-child(4)::before{content:"硬盘"} - .plan-option>:nth-child(5)::before{content:"每月流量"} - .plan-option>:nth-child(6)::before{content:"价格"} + .region-picker,.line-picker{grid-template-columns:repeat(2,minmax(0,1fr))} + .offer-table-head{display:none} + .offer-option:first-of-type{border-top-left-radius:10px;border-top-right-radius:10px} + .offer-option{grid-template-columns:repeat(2,minmax(0,1fr));gap:13px 18px;min-height:0;padding:18px 45px 18px 18px} + .offer-option-name{grid-column:1/-1;font-size:13px} + .offer-option-value,.offer-option-price{display:grid;gap:3px;white-space:normal} + .offer-option-value::before,.offer-option-price::before{color:#91a0ae;font-size:9px;font-weight:800} + .offer-option>:nth-child(2)::before{content:"CPU"} + .offer-option>:nth-child(3)::before{content:"内存"} + .offer-option>:nth-child(4)::before{content:"硬盘"} + .offer-option>:nth-child(5)::before{content:"每期流量"} + .offer-option>:nth-child(6)::before{content:"价格"} } -@media(max-width:510px){.deployment-step{padding-bottom:23px;margin-bottom:22px}.deployment-step-heading{margin-bottom:16px}.region-picker{grid-template-columns:1fr}.region-option{min-height:66px}.plan-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;padding:15px 14px 14px 16px}.plan-option::after{content:"";position:absolute;top:13px;right:14px;display:grid;place-items:center;width:22px;height:22px;border:1.5px solid #bdccd4;border-radius:50%;background:#fff;color:transparent;font-size:12px;font-weight:900}.plan-option[aria-pressed="true"]{box-shadow:none}.plan-option[aria-pressed="true"]::after{content:"✓";top:13px;right:14px;width:22px;height:22px;border:1.5px solid #18a6b0;background:#18a6b0;color:#fff}.plan-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}.plan-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;font-size:14px;white-space:nowrap}.plan-option-price::before{display:none;content:none}.plan-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}.plan-option-value::before{color:#718599;font-size:9px;font-weight:800;white-space:nowrap}.plan-option>:nth-child(2){grid-column:1}.plan-option>:nth-child(3){grid-column:2}.plan-option>:nth-child(4){grid-column:3}.plan-option>:nth-child(5){grid-column:4}.template-family-card{height:140px;min-height:140px;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden;box-shadow:none}.template-family-summary{height:100%;min-height:100%;border:0;border-radius:inherit;background:transparent}.template-family-card[open]{z-index:70;border-color:#a8dadd;box-shadow:0 12px 28px rgba(30,66,82,.14)}.template-family-card.has-selection{border-color:#2eabb4;background:#f5fbfb}.template-versions{position:absolute;inset:0;z-index:80;width:auto;height:auto;max-height:none;margin:0;padding:6px 8px 40px;overflow-y:auto;border:0;border-radius:inherit;background:#fbfdfd;box-shadow:none;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.template-family-card[open] .template-family-footer{position:absolute;right:7px;bottom:7px;z-index:90;width:32px;min-height:32px;border-radius:999px;background:#eaf8f8}.template-family-card[open] .template-family-selection{display:none}.user-iso-row{align-items:flex-start;flex-direction:column}.user-iso-row .row-button{width:100%}} +@media(max-width:510px){.deployment-step{padding-bottom:23px;margin-bottom:22px}.deployment-step-heading{margin-bottom:16px}.region-picker,.line-picker{grid-template-columns:1fr}.region-option{min-height:66px}.line-option{min-height:54px}.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;padding:15px 14px 14px 16px}.offer-option::after{content:"";position:absolute;top:13px;right:14px;display:grid;place-items:center;width:22px;height:22px;border:1.5px solid #bdccd4;border-radius:50%;background:#fff;color:transparent;font-size:12px;font-weight:900}.offer-option[aria-pressed="true"]{box-shadow:none}.offer-option[aria-pressed="true"]::after{content:"✓";top:13px;right:14px;width:22px;height:22px;border:1.5px solid #18a6b0;background:#18a6b0;color:#fff}.offer-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}.offer-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;font-size:14px;white-space:nowrap}.offer-option-price::before{display:none;content:none}.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}.offer-option-value::before{color:#718599;font-size:9px;font-weight:800;white-space:nowrap}.offer-option>:nth-child(2){grid-column:1}.offer-option>:nth-child(3){grid-column:2}.offer-option>:nth-child(4){grid-column:3}.offer-option>:nth-child(5){grid-column:4}.template-family-card{height:140px;min-height:140px;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden;box-shadow:none}.template-family-summary{height:100%;min-height:100%;border:0;border-radius:inherit;background:transparent}.template-family-card[open]{z-index:70;border-color:#a8dadd;box-shadow:0 12px 28px rgba(30,66,82,.14)}.template-family-card.has-selection{border-color:#2eabb4;background:#f5fbfb}.template-versions{position:absolute;inset:0;z-index:80;width:auto;height:auto;max-height:none;margin:0;padding:6px 8px 40px;overflow-y:auto;border:0;border-radius:inherit;background:#fbfdfd;box-shadow:none;overscroll-behavior:contain;-webkit-overflow-scrolling:touch}.template-family-card[open] .template-family-footer{position:absolute;right:7px;bottom:7px;z-index:90;width:32px;min-height:32px;border-radius:999px;background:#eaf8f8}.template-family-card[open] .template-family-selection{display:none}.user-iso-row{align-items:flex-start;flex-direction:column}.user-iso-row .row-button{width:100%}} .vm-state-sync{display:block;margin-top:4px;color:#8b9aaa;font-size:10px;line-height:1.35;white-space:nowrap}.vm-state-sync.stale{color:#b98129}.vm-state-sync.offline{color:#bd5b63}.vm-detail-state-stack{display:flex;flex-direction:column;align-items:flex-end;gap:3px}.vm-detail-state-stack .vm-state-sync{margin-top:0} diff --git a/web/resources/views/venix/cloud/pages/deploy.tpl b/web/resources/views/venix/cloud/pages/deploy.tpl index 27fefe5f..8e808c9a 100644 --- a/web/resources/views/venix/cloud/pages/deploy.tpl +++ b/web/resources/views/venix/cloud/pages/deploy.tpl @@ -6,48 +6,61 @@
1

选择地区

- +
{if empty($cloud_deploy_regions)}

暂无可部署地区,请联系管理员配置在售商品。

{else} {foreach $cloud_deploy_regions as $region} - {/foreach} {/if}
-
-
2

选择实例规格

- -
- {assign var=default_region_has_plans value=false} - {foreach $cloud_deploy_regions as $region} - {if $region.host_id == $cloud_deploy_default_host_id && !empty($region.plans)} - {assign var=default_region_has_plans value=true} -
名称CPU内存硬盘每月流量价格
- {foreach $region.plans as $plan} - {assign var=plan_memory_gib value=$plan.memory_mib/1024} - {assign var=plan_traffic_tib value=$plan.traffic_gib/1024} - - {/foreach} + {if !empty($cloud_deploy_lines_enabled)} +
+
2

选择线路

+
+ {assign var=default_region_has_lines value=false} + {foreach $cloud_deploy_lines as $line} + {if $line.region_id == $cloud_deploy_default_region_id} + {assign var=default_region_has_lines value=true} + + {/if} + {/foreach} + {if !$default_region_has_lines}

当前地区暂无可用线路。

{/if} +
+
+ {/if} + +
+
{if !empty($cloud_deploy_lines_enabled)}3{else}2{/if}

选择实例规格

+ +
+ {assign var=default_line_has_offers value=false} + {foreach $cloud_deploy_offers as $offer} + {if $offer.region_id == $cloud_deploy_default_region_id && $offer.line_id == $cloud_deploy_default_line_id} + {if !$default_line_has_offers}
名称CPU内存硬盘每期流量价格
{/if} + {assign var=default_line_has_offers value=true} + {assign var=offer_memory_gib value=$offer.memory_mib/1024} + {/if} {/foreach} - {if !$default_region_has_plans}

当前地区暂无可用实例规格。

{/if} + {if !$default_line_has_offers}

当前选择暂无可用实例规格。

{/if}
-
3

选择系统镜像

+
{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}

选择系统镜像

{if empty($cloud_deploy_template_groups)}

{if !empty($cloud_deploy_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}

@@ -70,7 +83,7 @@
-
4

实例信息

+
{if !empty($cloud_deploy_lines_enabled)}5{else}4{/if}

实例信息

留空时由系统生成 vm- 加 6 位随机编码。
SSH 公钥(可选)
{if empty($cloud_deploy_ssh_keys)}

暂无公钥,可先到“公钥管理”添加。不选公钥也会生成强密码。

{else}{foreach $cloud_deploy_ssh_keys as $key}{/foreach}{/if}
管理我的公钥
留空时生成 32 位完全随机密码;自行设置需为 12–128 位不含空格的英文可打印字符,包含大写、小写、数字和符号。
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 4b3ec6b0..4f0b7113 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100309' scope='global'} +{assign var=venix_asset_version value='2026100310' scope='global'} diff --git a/web/tests/CloudDeploymentPageSsrContractTest.php b/web/tests/CloudDeploymentPageSsrContractTest.php index b6af5bcf..595ce8fc 100644 --- a/web/tests/CloudDeploymentPageSsrContractTest.php +++ b/web/tests/CloudDeploymentPageSsrContractTest.php @@ -20,12 +20,14 @@ $section = static function (string $source, string $start, string $end): string }; $controller = file_get_contents($root . '/app/Controllers/CloudPageController.php'); +$apiController = file_get_contents($root . '/app/Controllers/CloudApiController.php'); $service = file_get_contents($root . '/app/Services/Cloud/CloudDeploymentPageService.php'); $deployTemplate = file_get_contents($root . '/resources/views/venix/cloud/pages/deploy.tpl'); $reinstallTemplate = file_get_contents($root . '/resources/views/venix/cloud/pages/reinstall.tpl'); $deployModule = file_get_contents($root . '/public/cloud/deploy.js'); $reinstallModule = file_get_contents($root . '/public/cloud/reinstall.js'); $runtime = file_get_contents($root . '/public/cloud/runtime.js'); +$routes = file_get_contents($root . '/config/routes_cloud.php'); $cloudShell = file_get_contents($root . '/resources/views/venix/cloud/page.tpl'); $layoutAssets = file_get_contents($root . '/resources/views/venix/layout_assets.tpl'); @@ -38,19 +40,33 @@ $openCreate = $section($runtime, 'async function openCreate(', $openReinstall = $section($runtime, 'async function openReinstall(', 'async function pollJob('); $selectRegion = $section($runtime, 'async function selectRegion(', - 'async function selectPlan('); -$selectPlan = $section($runtime, 'async function selectPlan(', + 'async function selectLine('); +$selectLine = $section($runtime, 'async function selectLine(', + 'async function selectOffer('); +$selectOffer = $section($runtime, 'async function selectOffer(', 'async function openCreate('); +$buy = $section($runtime, 'async function buy(', + 'function clearReinstallPasswordCard('); +$saleCatalog = $section($service, 'public static function saleCatalog(', + 'public static function sshKeys('); +$catalogApi = $section($apiController, 'public function catalog(', + 'public function orders('); +$resourcesApi = $section($apiController, 'public function resources(', + 'private function userIsoWriteActor('); $sshKeyOptions = $section($controller, 'private function sshKeyOptions(', 'private function reinstallVm('); $assert(str_contains($deployController, 'CloudAccess::actor(false)') - && str_contains($deployController, 'CloudDeploymentPageService::publicPagePlans()') - && str_contains($deployController, 'CloudDeploymentPageService::regions($plans)') + && str_contains($deployController, 'CloudDeploymentPageService::saleCatalog()') + && str_contains($deployController, "'regions' => \$regions") + && str_contains($deployController, "'lines' => \$lines") + && str_contains($deployController, "'offers' => \$offers") + && str_contains($deployController, "'lines_enabled' => \$linesEnabled") && str_contains($deployController, 'CloudDeploymentPageService::templateCatalogForPage($actor)') && str_contains($deployController, '$this->sshKeyOptions((int) $actor[\'user_id\'])') && str_contains($deployController, - '$defaultHostId = $regions === [] ? 0 : (int) $regions[0][\'host_id\']') + '$defaultRegionId = $regions === [] ? 0 : (int) $regions[0][\'id\']') + && str_contains($deployController, "'default_line_id' => \$defaultLineId") && str_contains($deployController, "'catalog_unavailable' => \$catalogUnavailable") && str_contains($deployController, "'cloud_deploy_catalog_unavailable' => \$catalogUnavailable") @@ -72,12 +88,21 @@ $assert(str_contains($deployTemplate, 'class="mdi mdi-key-variant ssh-key-choice && str_contains($reinstallTemplate, 'class="ssh-key-choice-check"') && str_contains($reinstallTemplate, ',指纹 {$key.fingerprint|escape:"html"}'), 'Deployment and reinstall first paint must render the compact SSH key picker consistently.'); -$assert(str_contains($service, "->orderBy('sort')->orderBy('id')") - && str_contains($service, "->where('enabled', 1)") - && str_contains($service, 'if ((int) $plan->stock === 0)') - && str_contains($service, 'return array_values($regions);') - && str_contains($service, "unset(\$plan['host_name'])"), - 'Available plans and regions must retain administrator sale order and omit private host labels.'); +$assert(str_contains($saleCatalog, "->join('shop as plan'") + && str_contains($saleCatalog, "->join('cloud_resource_pools as pool'") + && str_contains($saleCatalog, "->join('cloud_network_lines as line'") + && str_contains($saleCatalog, "->join('cloud_regions as region'") + && str_contains($saleCatalog, "->where('offer.stock', '<>', 0)") + && str_contains($saleCatalog, "->where('offer.currency', 'USD')") + && str_contains($saleCatalog, "\$query->where('line.is_default', 1)") + && str_contains($saleCatalog, "'lines_enabled' => \$linesEnabled") + && str_contains($saleCatalog, "'currency' => 'USD'") + && str_contains($saleCatalog, "'traffic_tib' => self::formatDecimalUnit(\$trafficGiB, 1024, 10)") + && str_contains($service, 'private static function formatDecimalUnit(') + && !str_contains($saleCatalog, "'host_id' =>") + && !str_contains($saleCatalog, "'plan_id' =>") + && !str_contains($saleCatalog, "'resource_pool_id' =>"), + 'Public sale catalog must follow the active offer chain, enforce the default-line switch and omit placement identities.'); $assert(str_contains($service, "private const TEMPLATE_SNAPSHOT_KEY") && str_contains($service, 'TEMPLATE_SNAPSHOT_REFRESH_SECONDS') && str_contains($service, "'checked_at' => time()") @@ -92,15 +117,24 @@ $assert(str_contains($service, "private const TEMPLATE_SNAPSHOT_KEY") $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/json"') && str_contains($deployTemplate, '{$cloud_deploy_bootstrap_json nofilter}') && str_contains($deployTemplate, '{foreach $cloud_deploy_regions as $region}') - && str_contains($deployTemplate, '$region.host_id == $cloud_deploy_default_host_id') - && str_contains($deployTemplate, '{foreach $region.plans as $plan}') + && str_contains($deployTemplate, 'data-region-id="{$region.id|escape:"html"}"') + && str_contains($deployTemplate, '{if !empty($cloud_deploy_lines_enabled)}') + && str_contains($deployTemplate, '{foreach $cloud_deploy_lines as $line}') + && str_contains($deployTemplate, 'data-line-id="{$line.id|escape:"html"}"') + && str_contains($deployTemplate, '{foreach $cloud_deploy_offers as $offer}') + && str_contains($deployTemplate, 'data-offer-id="{$offer.id|escape:"html"}"') + && str_contains($deployTemplate, '{$offer.traffic_tib|escape:"html"} TB') + && str_contains($deployTemplate, '${$offer.price|escape:"html"} USD') + && str_contains($deployTemplate, 'USD') && str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}') && str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}') && str_contains($deployTemplate, '$cloud_deploy_catalog_unavailable') && str_contains($deployTemplate, '系统镜像目录暂时无法读取') && !str_contains($deployTemplate, '请先选择地区') - && !str_contains($deployTemplate, '正在加载'), - 'Deployment HTML must immediately show regions, first-region plans, images and saved keys.'); + && !str_contains($deployTemplate, '正在加载') + && !str_contains($deployTemplate, 'host_id') + && !str_contains($deployTemplate, 'plan_id'), + 'Deployment HTML must immediately show regions, optional lines, offers, images and saved keys without host identities.'); $assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')") && str_contains($deployModule, "initializeSession('create', bootstrap?.user)") && str_contains($deployModule, 'openCreate(bootstrap)') @@ -109,30 +143,63 @@ $assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')") && !str_contains($deployModule, '/api/v1/resources') && !str_contains($deployModule, '/api/v1/ssh-keys'), 'Deployment page initialization must hydrate embedded data without a second data request.'); +$assert(str_contains($routes, + '$this->get(\'/catalog\', \'App\\Controllers\\CloudApiController:catalog\');') + && !str_contains($routes, '$this->get(\'/plans\'') + && !str_contains($apiController, 'public function plans(') + && str_contains($openCreate, "api('/api/v1/catalog')") + && !str_contains($runtime, '/api/v1/plans') + && !str_contains($runtime, 'payload?.plans'), + 'The public sale catalog must use only the catalog endpoint and response contract.'); $deployHydrationEnd = strpos($openCreate, ' return;'); $deployFallback = strpos($openCreate, 'Promise.allSettled(['); $assert($openCreate !== '' - && str_contains($openCreate, 'Array.isArray(bootstrap.plans)') + && str_contains($openCreate, 'Array.isArray(bootstrap.offers)') + && str_contains($openCreate, 'Array.isArray(bootstrap.regions)') + && str_contains($openCreate, 'Array.isArray(bootstrap.lines)') && str_contains($openCreate, 'Array.isArray(bootstrap.templates)') - && str_contains($openCreate, "bootstrapItems(bootstrap, 'regions')") + && str_contains($openCreate, 'applySaleCatalog(bootstrap)') && str_contains($openCreate, 'bootstrap.catalog_unavailable === true') - && str_contains($openCreate, 'bootstrap.default_host_id') - && str_contains($openCreate, "(regions[0]?.hostId || '')") + && str_contains($runtime, 'catalog?.default_region_id') + && str_contains($runtime, 'catalog?.default_line_id') && str_contains($openCreate, "renderTemplateCatalog('vm-template')") && $deployHydrationEnd !== false && $deployFallback !== false && $deployHydrationEnd < $deployFallback && !str_contains(substr($openCreate, 0, $deployHydrationEnd), "api('/api/v1/"), - 'Deployment hydration must select the requested/first region and paint all data before any fallback.'); -$assert($selectRegion !== '' && $selectPlan !== '' + 'Deployment hydration must select the requested/first region and line and paint all data before any fallback.'); +$assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== '' && !str_contains($selectRegion, 'resetInstallChoices()') && !str_contains($selectRegion, 'renderTemplateCatalog(') && !str_contains($selectRegion, 'loadGlobalTemplates(') && !str_contains($selectRegion, "byId('vm-template').value") - && !str_contains($selectPlan, 'resetInstallChoices()') - && !str_contains($selectPlan, 'renderTemplateCatalog(') - && !str_contains($selectPlan, 'loadGlobalTemplates(') - && !str_contains($selectPlan, "byId('vm-template').value"), - 'Changing a region or plan must never clear or reload the global image selection.'); + && !str_contains($selectLine, 'resetInstallChoices()') + && !str_contains($selectLine, 'renderTemplateCatalog(') + && !str_contains($selectLine, 'loadGlobalTemplates(') + && !str_contains($selectLine, "byId('vm-template').value") + && !str_contains($selectOffer, 'resetInstallChoices()') + && !str_contains($selectOffer, 'renderTemplateCatalog(') + && !str_contains($selectOffer, 'loadGlobalTemplates(') + && str_contains($buy, 'offer_id: Number(byId(\'vm-offer\').value)') + && !str_contains($buy, 'plan_id:') + && str_contains($buy, 'provisionInvoiceFingerprint(body)') + && str_contains($buy, 'pendingProvisionInvoiceKey(fingerprint)'), + 'Changing a region, line or offer must preserve the global image and purchasing must keep offer-scoped idempotency.'); + +$assert(str_contains($catalogApi, 'CloudDeploymentPageService::saleCatalog()') + && str_contains($resourcesApi, 'CloudDeploymentPageService::freshTemplateCatalog($actor)') + && !str_contains($resourcesApi, "\$query['plan_id']") + && !str_contains($resourcesApi, "['host_id']") + && str_contains($resourcesApi, 'CloudAccess::instance($query[\'vm_id\'], $actor)') + && str_contains($resourcesApi, 'return $this->json($response, $templatePayload);') + && !str_contains($resourcesApi, 'storage_available_gib') + && !str_contains($resourcesApi, "'GET', 'resources'"), + 'Catalog APIs must return global images and never expose a plan-derived or VM host identifier.'); + +$assert(str_contains($runtime, 'return `$${amount.toFixed(2)} USD`;') + && str_contains($runtime, 'formatTrafficTiB(offer.traffic_tib)') + && str_contains($runtime, "amount.toFixed(10).replace(/\\.?0+\$/, '')") + && !str_contains($runtime, "amount.toLocaleString('en-US', { minimumFractionDigits: 2"), + 'SSR and hydration must use the same fixed USD and trimmed ten-decimal TiB text.'); $assert(str_contains($reinstallController, 'CloudAccess::actor(false)') && str_contains($reinstallController, 'CloudInstancePageService::detailForActor($actor, $vmId)') diff --git a/web/tests/CloudPlanDefinitionTest.php b/web/tests/CloudPlanDefinitionTest.php index aa087520..52737b11 100644 --- a/web/tests/CloudPlanDefinitionTest.php +++ b/web/tests/CloudPlanDefinitionTest.php @@ -133,7 +133,7 @@ namespace { && !str_contains($shopController, "'host_id' => \$shop->host_id"), 'The administrator catalog must keep canonical plan units and move placement/pricing to offers.'); $assert(str_contains($client, 'function formatUsd(value)') - && str_contains($client, 'formatUsd(plan.price)') + && str_contains($client, 'formatUsd(offer.price)') && str_contains($client, 'formatUsd(invoice.amount)') && str_contains($client, 'formatUsd(balance)') && !str_contains($client, '¥') && !str_contains($invoiceView, '¥') diff --git a/web/tests/CloudUserISOContractTest.php b/web/tests/CloudUserISOContractTest.php index 75193532..5aa3f940 100644 --- a/web/tests/CloudUserISOContractTest.php +++ b/web/tests/CloudUserISOContractTest.php @@ -75,14 +75,16 @@ $assert(str_contains($orders, "if (\$source !== 'cloud')") && !str_contains($runtime, 'body.iso_path ='), 'Provisioning must be cloud-template-only on both browser and server boundaries.'); -$assert(str_contains($deploymentPages, "\$available->pluck('host_id')") - && str_contains($deploymentPages, "CloudHost::whereIn('id', \$hostIds)") - && str_contains($controller, 'CloudDeploymentPageService::plans()') +$assert(str_contains($deploymentPages, "->join('cloud_resource_pools as pool'") + && str_contains($deploymentPages, "->join('cloud_network_lines as line'") + && str_contains($deploymentPages, "->join('cloud_regions as region'") + && str_contains($deploymentPages, "\$query->where('line.is_default', 1)") + && str_contains($controller, 'CloudDeploymentPageService::saleCatalog()') && str_contains($controller, 'CloudDeploymentPageService::freshTemplateCatalog($actor)') && str_contains($deploymentPages, "'/internal/v1/vm-templates'") && str_contains($controller, "return \$this->json(\$response, \$templatePayload);") && !str_contains($controller, "\$engine->host(\$hostId, 'GET', 'vm-templates', \$actor)"), - 'Plan listing must preload hosts and deployment resources must return the global cloud-template catalog.'); + 'Offer listing must follow the region/line catalog while deployment resources remain one global cloud-template catalog.'); $assert(str_contains($isoClient, 'epoch !== pageState.loadEpoch') && str_contains($isoClient, "error.name !== 'AbortError'") diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php index 313116be..2ec65951 100644 --- a/web/tests/VirtualizationAssetsTest.php +++ b/web/tests/VirtualizationAssetsTest.php @@ -190,12 +190,18 @@ $assert(str_contains($sharedSidebar, 'href="/user/cloud/iso-images"') && 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"'); +$linePosition = strpos($cloudTemplate, 'id="vm-line-picker"'); +$offerPosition = strpos($cloudTemplate, 'id="vm-offer-picker"'); $sourcePosition = strpos($cloudTemplate, 'id="vm-template-catalog"'); -$assert($regionPosition !== false && $planPosition > $regionPosition && $sourcePosition > $planPosition +$assert($regionPosition !== false && $linePosition > $regionPosition + && $offerPosition > $linePosition && $sourcePosition > $offerPosition && str_contains($clientScript, 'function renderRegionPicker()') - && str_contains($clientScript, 'function renderPlanPicker()') + && str_contains($clientScript, 'function renderLinePicker()') + && str_contains($clientScript, 'function renderOfferPicker()') && str_contains($clientScript, "source: 'cloud'") + && str_contains($clientScript, "offer_id: Number(byId('vm-offer').value)") + && !str_contains($deployTemplate, 'host_id') + && !str_contains($deployTemplate, 'plan_id') && !str_contains($clientScript, "body.iso_id") && !str_contains($cloudTemplate, 'class="create-source-picker"') && !str_contains($cloudTemplate, 'id="vm-iso"') @@ -205,54 +211,59 @@ $assert($regionPosition !== false && $planPosition > $regionPosition && $sourceP && str_contains($clientScript, 'formBody.inert = true') && str_contains($clientScript, 'formBody.inert = false') && !str_contains($clientScript, 'body.iso_path ='), - 'Deployment must select region, plan and a cloud image without exposing an installation-mode switch.'); + 'Deployment must select region, optional line, offer and a global cloud image without exposing placement details.'); $assert(str_contains($deployTemplate, '实例名称(可选)') && str_contains($deployTemplate, '留空自动生成,例如 vm-k7m4p2') && str_contains($deployTemplate, 'vm- 加 6 位随机编码') && !preg_match('/id="vm-name"[^>]*\srequired(?:\s|>)/', $deployTemplate), 'Deployment instance name must be optional and explain its short generated default.'); -$planRendererStart = strpos($clientScript, 'function renderPlanPicker()'); -$planRendererEnd = strpos($clientScript, 'async function selectRegion(', $planRendererStart); -$planRenderer = $planRendererStart === false || $planRendererEnd === false +$offerRendererStart = strpos($clientScript, 'function renderOfferPicker()'); +$offerRendererEnd = strpos($clientScript, 'async function selectRegion(', $offerRendererStart); +$offerRenderer = $offerRendererStart === false || $offerRendererEnd === false ? '' - : substr($clientScript, $planRendererStart, $planRendererEnd - $planRendererStart); -$assert(str_contains($planRenderer, "'plan-table-head'") - && str_contains($planRenderer, 'formatMemoryGiB(plan.memory_mib)') - && str_contains($planRenderer, 'formatTrafficTiBFromGiB(plan.traffic_gib)') - && str_contains($planRenderer, 'formatUsd(plan.price)') - && !str_contains($planRenderer, 'bandwidth_mbps') - && str_contains($baseStyles, '.plan-option[aria-pressed="true"]::after{content:"✓"') - && str_contains($baseStyles, '.plan-option>:nth-child(6)::before{content:"价格"}') + : substr($clientScript, $offerRendererStart, $offerRendererEnd - $offerRendererStart); +$assert(str_contains($offerRenderer, "'offer-table-head'") + && str_contains($offerRenderer, 'formatMemoryGiB(offer.memory_mib)') + && str_contains($offerRenderer, 'formatTrafficTiB(offer.traffic_tib)') + && str_contains($offerRenderer, 'formatUsd(offer.price)') + && !str_contains($offerRenderer, 'bandwidth_mbps') + && str_contains($baseStyles, '.offer-option[aria-pressed="true"]::after{content:"✓"') + && str_contains($baseStyles, '.offer-option>:nth-child(6)::before{content:"价格"}') && !str_contains($cloudTemplate, 'id="vm-plan-summary"') && !str_contains($cloudTemplate, 'class="vm-auto-public-pool"') && !str_contains($cloudTemplate, 'id="create-cloud-tip"') && !str_contains($cloudTemplate, 'id="create-iso-tip"'), - 'Deployment plans must use selectable specification rows without obsolete helper panels.'); + 'Deployment offers must use selectable specification rows without obsolete helper panels.'); $assert(str_contains($baseStyles, - '.plan-option:last-of-type{border-bottom:0;border-bottom-right-radius:10px;border-bottom-left-radius:10px}') + '.offer-option:last-of-type{border-bottom:0;border-bottom-right-radius:10px;border-bottom-left-radius:10px}') && str_contains($baseStyles, - '.plan-option:first-of-type{border-top-left-radius:10px;border-top-right-radius:10px}') + '.offer-option:first-of-type{border-top-left-radius:10px;border-top-right-radius:10px}') && str_contains($baseStyles, - '.plan-option[aria-pressed="true"]{z-index:1;background:#eef9fa;box-shadow:inset 0 0 0 2px #2eabb4;'), - 'Selected plan rows must preserve rounded first/last corners without clipping their inset border.'); + '.offer-option[aria-pressed="true"]{z-index:1;background:#eef9fa;box-shadow:inset 0 0 0 2px #2eabb4;'), + 'Selected offer rows must preserve rounded first/last corners without clipping their inset border.'); $runtimeDeployScript = file_get_contents($public . '/runtime.js'); $selectRegionStart = strpos($runtimeDeployScript, 'async function selectRegion('); $selectRegionEnd = $selectRegionStart === false ? false - : strpos($runtimeDeployScript, 'async function selectPlan(', $selectRegionStart); + : strpos($runtimeDeployScript, 'async function selectLine(', $selectRegionStart); $selectRegion = $selectRegionStart === false || $selectRegionEnd === false ? '' : substr($runtimeDeployScript, $selectRegionStart, $selectRegionEnd - $selectRegionStart); -$selectPlanStart = strpos($runtimeDeployScript, 'async function selectPlan('); -$selectPlanEnd = $selectPlanStart === false ? false - : strpos($runtimeDeployScript, 'async function openCreate(', $selectPlanStart); -$selectPlan = $selectPlanStart === false || $selectPlanEnd === false ? '' - : substr($runtimeDeployScript, $selectPlanStart, $selectPlanEnd - $selectPlanStart); -$assert($selectPlan !== '' - && !str_contains($selectPlan, 'renderPlanPicker();') - && str_contains($selectPlan, - "byId('vm-plan-picker').querySelectorAll('.plan-option').forEach(button => {") - && str_contains($selectPlan, - "button.setAttribute('aria-pressed', String(button.dataset.planId === String(plan.id)));"), - 'Selecting a plan must preserve the focused row instead of replacing the plan list.'); +$selectLineStart = strpos($runtimeDeployScript, 'async function selectLine('); +$selectLineEnd = $selectLineStart === false ? false + : strpos($runtimeDeployScript, 'async function selectOffer(', $selectLineStart); +$selectLine = $selectLineStart === false || $selectLineEnd === false ? '' + : substr($runtimeDeployScript, $selectLineStart, $selectLineEnd - $selectLineStart); +$selectOfferStart = strpos($runtimeDeployScript, 'async function selectOffer('); +$selectOfferEnd = $selectOfferStart === false ? false + : strpos($runtimeDeployScript, 'async function openCreate(', $selectOfferStart); +$selectOffer = $selectOfferStart === false || $selectOfferEnd === false ? '' + : substr($runtimeDeployScript, $selectOfferStart, $selectOfferEnd - $selectOfferStart); +$assert($selectOffer !== '' + && !str_contains($selectOffer, 'renderOfferPicker();') + && str_contains($selectOffer, + "byId('vm-offer-picker').querySelectorAll('.offer-option').forEach(button => {") + && str_contains($selectOffer, + "button.setAttribute('aria-pressed', String(button.dataset.offerId === String(offer.id)));"), + 'Selecting an offer must preserve the focused row instead of replacing the offer list.'); $openCreateStart = strpos($runtimeDeployScript, 'async function openCreate('); $openCreateEnd = $openCreateStart === false ? false : strpos($runtimeDeployScript, 'async function loadGlobalTemplates()', $openCreateStart); @@ -272,18 +283,24 @@ $reinstallHydrationReturn = $reinstallBootstrapStart === false ? false $reinstallFallbackRequest = strpos($openReinstall, "api(`/api/v1/resources?vm_id="); $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/json"') && str_contains($deployTemplate, '{foreach $cloud_deploy_regions as $region}') - && str_contains($deployTemplate, '$region.host_id == $cloud_deploy_default_host_id') - && str_contains($deployTemplate, '{foreach $region.plans as $plan}') + && str_contains($deployTemplate, '{foreach $cloud_deploy_lines as $line}') + && str_contains($deployTemplate, '{foreach $cloud_deploy_offers as $offer}') + && str_contains($deployTemplate, '$cloud_deploy_lines_enabled') + && str_contains($deployTemplate, 'USD') && str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}') && str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}') - && !str_contains($deployTemplate, '正在加载系统镜像'), - 'Deployment HTML must contain regions, first-region plans, images and SSH keys before hydration.'); -$assert(str_contains($deploymentPageService, "->orderBy('sort')->orderBy('id')") - && str_contains($deploymentPageService, "->where('enabled', 1)") - && str_contains($deploymentPageService, "'plans' => []") - && str_contains($cloudPageController, '$defaultHostId = $regions === [] ? 0 : (int) $regions[0][\'host_id\']') + && !str_contains($deployTemplate, '正在加载系统镜像') + && !str_contains($deployTemplate, 'host_id') + && !str_contains($deployTemplate, 'plan_id'), + 'Deployment HTML must contain regions, optional lines, offers, images and SSH keys before hydration.'); +$assert(str_contains($deploymentPageService, "->join('cloud_resource_pools as pool'") + && str_contains($deploymentPageService, "->join('cloud_network_lines as line'") + && str_contains($deploymentPageService, "->where('offer.stock', '<>', 0)") + && str_contains($deploymentPageService, "\$query->where('line.is_default', 1)") + && str_contains($cloudPageController, '$defaultRegionId = $regions === [] ? 0 : (int) $regions[0][\'id\']') + && str_contains($cloudPageController, "'default_line_id' => \$defaultLineId") && str_contains($cloudPageController, "'cloud_deploy_bootstrap_json' => \$this->safeJson(\$payload)"), - 'Deployment SSR must preserve sale order and select the first available host region by default.'); + 'Deployment SSR must follow the active offer chain and select the first available region and line.'); $assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')") && str_contains($deployModule, "initializeSession('create', bootstrap?.user)") && str_contains($deployModule, 'openCreate(bootstrap)') @@ -292,15 +309,22 @@ $assert(str_contains($deployModule, "readBootstrap('deploy-bootstrap')") && !str_contains($deployModule, '/api/v1/resources') && !str_contains($deployModule, '/api/v1/ssh-keys'), 'Deployment first paint must hydrate its embedded payload without initial data API requests.'); -$assert(str_contains($openCreate, 'Array.isArray(bootstrap.plans)') +$assert(str_contains($openCreate, 'Array.isArray(bootstrap.offers)') + && str_contains($openCreate, 'Array.isArray(bootstrap.regions)') + && str_contains($openCreate, 'Array.isArray(bootstrap.lines)') && str_contains($openCreate, 'Array.isArray(bootstrap.templates)') - && str_contains($openCreate, "bootstrapItems(bootstrap, 'regions')") - && str_contains($openCreate, 'bootstrap.default_host_id') - && str_contains($openCreate, "(regions[0]?.hostId || '')") + && str_contains($openCreate, 'applySaleCatalog(bootstrap)') && str_contains($openCreate, "renderTemplateCatalog('vm-template')") && $deployHydrationReturn !== false && $deployFallbackRequest !== false && $deployHydrationReturn < $deployFallbackRequest, - 'Deployment hydration must use the embedded full catalog and first valid region before any compatibility fallback.'); + 'Deployment hydration must use the embedded full catalog and first valid region/line before any compatibility fallback.'); +$assert(str_contains($cloudRoutes, + '$this->get(\'/catalog\', \'App\\Controllers\\CloudApiController:catalog\');') + && !str_contains($cloudRoutes, '$this->get(\'/plans\'') + && str_contains($openCreate, "api('/api/v1/catalog')") + && !str_contains($runtimeDeployScript, '/api/v1/plans') + && !str_contains($runtimeDeployScript, 'payload?.plans'), + 'Deployment fallback must use only the public sale-catalog endpoint and response shape.'); $assert(str_contains($reinstallTemplate, 'id="reinstall-bootstrap" type="application/json"') && str_contains($reinstallTemplate, '$cloud_reinstall_vm.name') && str_contains($reinstallTemplate, '{foreach $cloud_reinstall_template_groups as $group}') @@ -316,16 +340,20 @@ $assert(str_contains($reinstallTemplate, 'id="reinstall-bootstrap" type="applica && $reinstallHydrationReturn !== false && $reinstallFallbackRequest !== false && $reinstallHydrationReturn < $reinstallFallbackRequest, 'Reinstall HTML must embed VM, image and key data and hydrate without initial data API requests.'); -$assert($selectRegion !== '' && $selectPlan !== '' +$assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== '' && !str_contains($selectRegion, 'resetInstallChoices()') && !str_contains($selectRegion, 'renderTemplateCatalog(') && !str_contains($selectRegion, 'loadGlobalTemplates(') && !str_contains($selectRegion, "byId('vm-template').value") - && !str_contains($selectPlan, 'resetInstallChoices()') - && !str_contains($selectPlan, 'renderTemplateCatalog(') - && !str_contains($selectPlan, 'loadGlobalTemplates(') - && !str_contains($selectPlan, "byId('vm-template').value"), - 'Changing regions or plans must preserve the global image catalog and selected image.'); + && !str_contains($selectLine, 'resetInstallChoices()') + && !str_contains($selectLine, 'renderTemplateCatalog(') + && !str_contains($selectLine, 'loadGlobalTemplates(') + && !str_contains($selectLine, "byId('vm-template').value") + && !str_contains($selectOffer, 'resetInstallChoices()') + && !str_contains($selectOffer, 'renderTemplateCatalog(') + && !str_contains($selectOffer, 'loadGlobalTemplates(') + && !str_contains($selectOffer, "byId('vm-template').value"), + 'Changing regions, lines or offers must preserve the global image catalog and selected image.'); $catalogRendererStart = strpos($runtimeDeployScript, 'function renderTemplateCatalog(inputId)'); $catalogRendererEnd = $catalogRendererStart === false ? false : strpos($runtimeDeployScript, 'async function initializeSession(', $catalogRendererStart); @@ -340,23 +368,23 @@ $cardVersionRule = strpos($baseStyles, $flatVersionRule = strpos($baseStyles, '.template-version-option{min-height:44px;padding:11px 4px;border:0;'); $assert(str_contains($mobileDeploymentStyles, - '.plan-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;') + '.offer-option{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:auto auto;gap:12px 8px;min-height:108px;') && str_contains($mobileDeploymentStyles, - '.plan-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}') + '.offer-option-name{grid-column:1/3;grid-row:1;align-self:center;font-size:14px}') && str_contains($mobileDeploymentStyles, - '.plan-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;') + '.offer-option-price{display:block;grid-column:3/5;grid-row:1;align-self:center;justify-self:end;padding-right:30px;') && str_contains($mobileDeploymentStyles, - '.plan-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}') + '.offer-option-value{display:grid;grid-row:2;gap:4px;white-space:normal}') && str_contains($mobileDeploymentStyles, - '.plan-option>:nth-child(2){grid-column:1}.plan-option>:nth-child(3){grid-column:2}.plan-option>:nth-child(4){grid-column:3}.plan-option>:nth-child(5){grid-column:4}') + '.offer-option>:nth-child(2){grid-column:1}.offer-option>:nth-child(3){grid-column:2}.offer-option>:nth-child(4){grid-column:3}.offer-option>:nth-child(5){grid-column:4}') && str_contains($mobileDeploymentStyles, - '.plan-option[aria-pressed="true"]{box-shadow:none}') + '.offer-option[aria-pressed="true"]{box-shadow:none}') && !str_contains($mobileDeploymentStyles, 'box-shadow:inset 4px 0 0') && str_contains($mobileDeploymentStyles, - '.plan-option-price::before{display:none;content:none}') + '.offer-option-price::before{display:none;content:none}') && !str_contains($mobileDeploymentStyles, - '.plan-option{grid-template-columns:repeat(2,minmax(0,1fr))'), - 'Mobile deployment plans must use a compact two-row comparison layout without replacing semantic plan buttons.'); + '.offer-option{grid-template-columns:repeat(2,minmax(0,1fr))'), + 'Mobile deployment offers must use a compact two-row comparison layout without replacing semantic offer buttons.'); $assert(str_contains($baseStyles, '.template-catalog{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));align-items:start;') && str_contains($baseStyles, @@ -493,15 +521,16 @@ $availabilityEnd = $availabilityStart === false ? false : strpos($runtimeDeployScript, 'function strongPassword(', $availabilityStart); $availability = $availabilityStart === false || $availabilityEnd === false ? '' : substr($runtimeDeployScript, $availabilityStart, $availabilityEnd - $availabilityStart); -$assert(str_contains($availability, 'const validHost = plan') +$assert(str_contains($availability, 'const offer = saleOffers()') && str_contains($availability, "const validMedia = Boolean(byId('vm-template')?.value)") && !str_contains($availability, 'state.resources'), - 'Deployment submission must require a matching region/plan and selected global image.'); + 'Deployment submission must require a matching region/line/offer and selected global image.'); $assert(str_contains($baseStyles, '.deployment-step') && str_contains($baseStyles, '.region-option') - && str_contains($baseStyles, '.plan-option') + && str_contains($baseStyles, '.line-option') + && str_contains($baseStyles, '.offer-option') && str_contains($baseStyles, '.user-iso-row'), - 'Region-first deployment and personal ISO pages must retain VM-panel styling.'); + 'Region/line/offer deployment and personal ISO pages must retain VM-panel styling.'); $assert(!str_contains($cloudTemplate, '购买并开通') && !str_contains($sharedSidebar, '我的虚拟机'), 'Retired VM sales labels remain'); $assert(!str_contains($shopFormScript, 'data.hosts') && !str_contains($shopFormScript, "'host_id'")