diff --git a/web/app/Services/Cloud/CloudDeploymentPageService.php b/web/app/Services/Cloud/CloudDeploymentPageService.php index 8bf5b607..501c7d5c 100644 --- a/web/app/Services/Cloud/CloudDeploymentPageService.php +++ b/web/app/Services/Cloud/CloudDeploymentPageService.php @@ -36,7 +36,6 @@ final class CloudDeploymentPageService ->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') @@ -51,14 +50,33 @@ final class CloudDeploymentPageService ->orderByDesc('offer.sort')->orderBy('offer.id') ->get([ 'offer.id as offer_id', 'offer.name as offer_name', - 'offer.price as offer_price', + 'offer.price as offer_price', 'offer.stock as offer_stock', 'plan.cpu_cores', 'plan.memory_mib', 'plan.bandwidth_mbps', 'plan.disk_gib', 'plan.validity_days', 'plan.traffic_quota_bytes', + 'pool.id as internal_pool_id', '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', ]); + $capacityKey = static fn ($row): string => implode(':', [ + (int) $row->internal_pool_id, + (int) $row->cpu_cores, + (int) $row->memory_mib, + (int) $row->disk_gib, + ]); + $capacityRequests = []; + foreach ($rows as $row) { + $capacityRequests[$capacityKey($row)] = [ + 'pool_id' => (int) $row->internal_pool_id, + 'cpu_cores' => (int) $row->cpu_cores, + 'memory_mib' => (int) $row->memory_mib, + 'disk_gib' => (int) $row->disk_gib, + ]; + } + $capacity = CloudPlacementService::poolCapacityAvailability( + $capacityRequests + ); $regions = []; $lines = []; $offers = []; @@ -84,6 +102,7 @@ final class CloudDeploymentPageService } $trafficBytes = max(0, (int) $row->traffic_quota_bytes); $trafficGiB = intdiv($trafficBytes, self::GIB); + $offerCapacityKey = $capacityKey($row); $offers[] = [ 'id' => (int) $row->offer_id, 'name' => trim((string) $row->offer_name), @@ -99,6 +118,8 @@ final class CloudDeploymentPageService 'traffic_quota_bytes' => $trafficBytes, 'traffic_gib' => $trafficGiB, 'traffic_tib' => self::formatDecimalUnit($trafficGiB, 1024, 10), + 'sellable' => (int) $row->offer_stock !== 0 + && ($capacity[$offerCapacityKey] ?? false), ]; } diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index e08a24c2..b0eabefe 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -83,6 +83,14 @@ final class CloudOrderService || (!CloudNetworkLineFeature::enabled() && !(bool) $line->is_default)) { throw new CloudError('该销售方案的地区、线路或资源池暂不可用', 409); } + if (!CloudPlacementService::isPoolCapacityAvailable( + (int) $pool->id, + (int) $plan->cpu_cores, + (int) $plan->memory_mib, + (int) $plan->disk_gib + )) { + throw new CloudError('该销售方案当前没有足够的可用资源或公网 IP', 409); + } $price = CloudMoney::cents($offer->price); $payload = ['source' => $source, 'name' => $name, 'vcpu' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib, diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index f54ed006..5fcb2236 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -28,6 +28,85 @@ final class CloudPlacementService private const GIB = 1073741824; private const ACTIVE_RESERVATIONS = ['held', 'uncertain']; + /** + * Advisory capacity check for an already-authorized active pool chain. + * + * Catalog construction has already joined and filtered the offer, plan, + * pool, line and region. Keeping this method resource-only avoids loading + * those models once per public offer while sharing the scheduler's exact + * host, reservation and address predicates. + */ + public static function isPoolCapacityAvailable(int $poolId, int $cpuCores, + int $memoryMib, int $diskGib): bool + { + $availability = self::poolCapacityAvailability(['single' => [ + 'pool_id' => $poolId, + 'cpu_cores' => $cpuCores, + 'memory_mib' => $memoryMib, + 'disk_gib' => $diskGib, + ]]); + return $availability['single'] ?? false; + } + + /** + * Batch advisory availability without locks or resource reservation. + * + * @param array $requests + * @return array + */ + public static function poolCapacityAvailability(array $requests): array + { + $availability = []; + $byPool = []; + foreach ($requests as $key => $resources) { + $availability[$key] = false; + if (!is_array($resources)) { + continue; + } + $poolId = (int) ($resources['pool_id'] ?? 0); + $normalized = [ + 'cpu_cores' => (int) ($resources['cpu_cores'] ?? 0), + 'memory_mib' => (int) ($resources['memory_mib'] ?? 0), + 'disk_gib' => (int) ($resources['disk_gib'] ?? 0), + ]; + if ($poolId < 1 || min($normalized) < 1) { + continue; + } + $byPool[$poolId][$key] = $normalized; + } + + foreach ($byPool as $poolId => $poolRequests) { + $candidateRows = self::candidateHostRows((int) $poolId); + if ($candidateRows->isEmpty()) { + continue; + } + $pendingByHost = self::pendingUsageByHost($candidateRows); + $availableIpHosts = array_fill_keys( + CloudPublicIp::query()->whereIn('host_id', + $candidateRows->pluck('id')->all()) + ->where('state', 'available')->distinct() + ->pluck('host_id')->map( + static fn ($id): int => (int) $id + )->all(), + true + ); + foreach ($poolRequests as $key => $resources) { + foreach ($candidateRows as $candidate) { + $hostId = (int) $candidate->id; + if (isset($availableIpHosts[$hostId]) + && self::hasCapacity($candidate, $candidate, + $pendingByHost[$hostId] ?? self::emptyUsage(), + $resources)) { + $availability[$key] = true; + break; + } + } + } + } + return $availability; + } + /** * Select a host and reserve one concrete public IP exactly once. * @@ -81,94 +160,12 @@ final class CloudPlacementService throw new CloudError('当前未开放线路选择,该销售方案暂不可购买', 409); } - $freshAfter = time() - self::freshnessSeconds(); - $candidateRows = CloudHost::join( - 'cloud_host_capacity_policies as capacity_policy', - 'capacity_policy.host_id', '=', 'cloud_hosts.id' - )->join( - 'cloud_host_capacity_snapshots as capacity_snapshot', - 'capacity_snapshot.host_id', '=', 'cloud_hosts.id' - )->where('cloud_hosts.resource_pool_id', (int) $pool->id) - ->where('cloud_hosts.enabled', 1) - ->where('cloud_hosts.scheduler_state', 'active') - ->where('cloud_hosts.health_state', 'healthy') - ->where('capacity_snapshot.sync_state', 'fresh') - ->where('capacity_snapshot.last_attempt_at', '>=', $freshAfter) - ->where('capacity_policy.configured_cpu_cores', '>', 0) - ->where('capacity_policy.configured_memory_mib', '>', 0) - ->where('capacity_policy.configured_disk_gib', '>', 0) - ->get([ - 'cloud_hosts.id', - 'capacity_policy.configured_cpu_cores', - 'capacity_policy.configured_memory_mib', - 'capacity_policy.configured_disk_gib', - 'capacity_policy.safety_cpu_cores', - 'capacity_policy.safety_memory_mib', - 'capacity_policy.safety_disk_gib', - 'capacity_policy.max_instances', - 'capacity_snapshot.cpu_total_cores', - 'capacity_snapshot.cpu_allocated_cores', - 'capacity_snapshot.memory_total_mib', - 'capacity_snapshot.memory_allocated_mib', - 'capacity_snapshot.storage_total_bytes', - 'capacity_snapshot.storage_allocated_bytes', - 'capacity_snapshot.instance_total_count', - 'capacity_snapshot.last_attempt_at', - ]); - $candidateIds = $candidateRows->pluck('id') - ->map(static fn ($id): int => (int) $id)->all(); - $pendingByHost = []; - if ($candidateIds !== []) { - foreach (CloudResourceReservation::query() - ->from('cloud_resource_reservations as reservation') - ->join('cloud_host_capacity_snapshots as observed', - 'observed.host_id', '=', 'reservation.host_id') - ->whereIn('reservation.host_id', $candidateIds) - ->where(function ($query): void { - $query->whereIn('reservation.state', self::ACTIVE_RESERVATIONS) - ->orWhere(function ($recent): void { - $recent->where('reservation.state', 'committed') - ->whereColumn('reservation.updated_at', '>=', - 'observed.last_attempt_at'); - }); - })->selectRaw( - 'reservation.host_id, COUNT(*) AS instance_count, ' - . 'COALESCE(SUM(reservation.cpu_cores),0) AS cpu_sum, ' - . 'COALESCE(SUM(reservation.memory_mib),0) AS memory_sum, ' - . 'COALESCE(SUM(reservation.disk_gib),0) AS disk_sum' - )->groupBy('reservation.host_id')->get() as $pending) { - $pendingByHost[(int) $pending->host_id] = $pending; - } - } + $candidateRows = self::candidateHostRows((int) $pool->id); + $pendingByHost = self::pendingUsageByHost($candidateRows); $candidates = $candidateRows->map(static function ($row) use ($pendingByHost): array { - $pending = $pendingByHost[(int) $row->id] ?? null; - $cpuTotal = max(1, min((int) $row->cpu_total_cores, - (int) $row->configured_cpu_cores) - - (int) $row->safety_cpu_cores); - $memoryTotal = max(1, min((int) $row->memory_total_mib, - (int) $row->configured_memory_mib) - - (int) $row->safety_memory_mib); - $storageTotal = max(1, min((int) $row->storage_total_bytes, - (int) $row->configured_disk_gib * self::GIB) - - ((int) $row->safety_disk_gib * self::GIB)); - $instanceScore = (int) $row->max_instances > 0 - ? ((int) $row->instance_total_count - + (int) ($pending->instance_count ?? 0)) - / (int) $row->max_instances - : 0.0; - return [ - 'id' => (int) $row->id, - 'score' => max( - ((int) $row->cpu_allocated_cores - + (int) ($pending->cpu_sum ?? 0)) / $cpuTotal, - ((int) $row->memory_allocated_mib - + (int) ($pending->memory_sum ?? 0)) / $memoryTotal, - ((int) $row->storage_allocated_bytes - + ((int) ($pending->disk_sum ?? 0) * self::GIB)) - / $storageTotal, - $instanceScore - ), - ]; + $pending = $pendingByHost[(int) $row->id] ?? self::emptyUsage(); + return ['id' => (int) $row->id, + 'score' => self::capacityScore($row, $row, $pending)]; })->sort(static fn (array $left, array $right): int => ($left['score'] <=> $right['score']) ?: ($left['id'] <=> $right['id']) )->values()->all(); @@ -435,51 +432,14 @@ final class CloudPlacementService ->orderBy('id')->lockForUpdate()->get([ 'id', 'state', 'cpu_cores', 'memory_mib', 'disk_gib', 'updated_at', ]); - $pending = [ - 'instance_count' => 0, - 'cpu_sum' => 0, - 'memory_sum' => 0, - 'disk_sum' => 0, - ]; - foreach ($reservationRows as $row) { - // Timestamps have one-second precision. Treat an equal second - // conservatively as not yet observed; temporary double-counting is - // safer than oversubscription. - if ((string) $row->state === 'committed' - && (int) $row->updated_at < (int) $snapshot->last_attempt_at) { - continue; - } - $pending['instance_count']++; - $pending['cpu_sum'] += (int) $row->cpu_cores; - $pending['memory_sum'] += (int) $row->memory_mib; - $pending['disk_sum'] += (int) $row->disk_gib; - } - - $cpuLimit = max(0, min((int) $policy->configured_cpu_cores, - (int) $snapshot->cpu_total_cores) - (int) $policy->safety_cpu_cores); - $memoryLimit = max(0, min((int) $policy->configured_memory_mib, - (int) $snapshot->memory_total_mib) - (int) $policy->safety_memory_mib); - $configuredDisk = (int) $policy->configured_disk_gib * self::GIB; - $safetyDisk = (int) $policy->safety_disk_gib * self::GIB; - $diskLimit = max(0, min($configuredDisk, - (int) $snapshot->storage_total_bytes) - $safetyDisk); - $usedCpu = (int) $snapshot->cpu_allocated_cores + $pending['cpu_sum']; - $usedMemory = (int) $snapshot->memory_allocated_mib - + $pending['memory_sum']; - $usedDisk = (int) $snapshot->storage_allocated_bytes - + ($pending['disk_sum'] * self::GIB); - $instances = (int) $snapshot->instance_total_count - + $pending['instance_count']; - if ($usedCpu + $resources['cpu_cores'] > $cpuLimit - || $usedMemory + $resources['memory_mib'] > $memoryLimit - || $usedDisk + ($resources['disk_gib'] * self::GIB) > $diskLimit - || ((int) $policy->max_instances > 0 - && $instances + 1 > (int) $policy->max_instances)) { + $pending = self::reservationUsage( + $reservationRows, (int) $snapshot->last_attempt_at + ); + if (!self::hasCapacity($policy, $snapshot, $pending, $resources)) { return null; } - $ip = CloudPublicIp::where('host_id', $hostId)->where('state', 'available') - ->orderBy('id')->lockForUpdate()->first(); + $ip = self::availablePublicIpQuery($hostId)->lockForUpdate()->first(); if ($ip === null) { return null; } @@ -613,6 +573,173 @@ final class CloudPlacementService return [$host, $reservation]; } + private static function candidateHostRows(int $poolId) + { + $freshAfter = time() - self::freshnessSeconds(); + return CloudHost::query()->join( + 'cloud_host_capacity_policies as capacity_policy', + 'capacity_policy.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_host_capacity_snapshots as capacity_snapshot', + 'capacity_snapshot.host_id', '=', 'cloud_hosts.id' + )->where('cloud_hosts.resource_pool_id', $poolId) + ->where('cloud_hosts.enabled', 1) + ->where('cloud_hosts.scheduler_state', 'active') + ->where('cloud_hosts.health_state', 'healthy') + ->where('capacity_snapshot.sync_state', 'fresh') + ->where('capacity_snapshot.last_attempt_at', '>=', $freshAfter) + ->where('capacity_policy.configured_cpu_cores', '>', 0) + ->where('capacity_policy.configured_memory_mib', '>', 0) + ->where('capacity_policy.configured_disk_gib', '>', 0) + ->get([ + 'cloud_hosts.id', + 'capacity_policy.configured_cpu_cores', + 'capacity_policy.configured_memory_mib', + 'capacity_policy.configured_disk_gib', + 'capacity_policy.safety_cpu_cores', + 'capacity_policy.safety_memory_mib', + 'capacity_policy.safety_disk_gib', + 'capacity_policy.max_instances', + 'capacity_snapshot.cpu_total_cores', + 'capacity_snapshot.cpu_allocated_cores', + 'capacity_snapshot.memory_total_mib', + 'capacity_snapshot.memory_allocated_mib', + 'capacity_snapshot.storage_total_bytes', + 'capacity_snapshot.storage_allocated_bytes', + 'capacity_snapshot.instance_total_count', + 'capacity_snapshot.last_attempt_at', + ]); + } + + private static function pendingUsageByHost($candidateRows): array + { + $observedAt = []; + foreach ($candidateRows as $candidate) { + $observedAt[(int) $candidate->id] = (int) $candidate->last_attempt_at; + } + $candidateIds = array_keys($observedAt); + if ($candidateIds === []) { + return []; + } + $minimumObservedAt = min($observedAt); + $usage = []; + $rows = CloudResourceReservation::query() + ->whereIn('host_id', $candidateIds) + ->where(function ($query) use ($minimumObservedAt): void { + $query->whereIn('state', self::ACTIVE_RESERVATIONS) + ->orWhere(function ($recent) use ($minimumObservedAt): void { + $recent->where('state', 'committed') + ->where('updated_at', '>=', $minimumObservedAt); + }); + })->get([ + 'host_id', 'state', 'cpu_cores', 'memory_mib', 'disk_gib', + 'updated_at', + ]); + foreach ($rows as $row) { + $hostId = (int) $row->host_id; + if ((string) $row->state === 'committed' + && (int) $row->updated_at < $observedAt[$hostId]) { + continue; + } + $usage[$hostId] ??= self::emptyUsage(); + $usage[$hostId]['instance_count']++; + $usage[$hostId]['cpu_sum'] += (int) $row->cpu_cores; + $usage[$hostId]['memory_sum'] += (int) $row->memory_mib; + $usage[$hostId]['disk_sum'] += (int) $row->disk_gib; + } + return $usage; + } + + private static function reservationUsage($reservationRows, + int $lastAttemptAt): array + { + $usage = self::emptyUsage(); + foreach ($reservationRows as $row) { + // Timestamps have one-second precision. Treat an equal second as + // not yet observed; temporary double-counting is safer than + // oversubscription. + if ((string) $row->state === 'committed' + && (int) $row->updated_at < $lastAttemptAt) { + continue; + } + $usage['instance_count']++; + $usage['cpu_sum'] += (int) $row->cpu_cores; + $usage['memory_sum'] += (int) $row->memory_mib; + $usage['disk_sum'] += (int) $row->disk_gib; + } + return $usage; + } + + private static function emptyUsage(): array + { + return [ + 'instance_count' => 0, + 'cpu_sum' => 0, + 'memory_sum' => 0, + 'disk_sum' => 0, + ]; + } + + private static function capacityState($policy, $snapshot, + array $usage): array + { + $cpuLimit = max(0, min((int) $policy->configured_cpu_cores, + (int) $snapshot->cpu_total_cores) - (int) $policy->safety_cpu_cores); + $memoryLimit = max(0, min((int) $policy->configured_memory_mib, + (int) $snapshot->memory_total_mib) - (int) $policy->safety_memory_mib); + $configuredDisk = (int) $policy->configured_disk_gib * self::GIB; + $safetyDisk = (int) $policy->safety_disk_gib * self::GIB; + $diskLimit = max(0, min($configuredDisk, + (int) $snapshot->storage_total_bytes) - $safetyDisk); + return [ + 'cpu_limit' => $cpuLimit, + 'memory_limit' => $memoryLimit, + 'disk_limit' => $diskLimit, + 'cpu_used' => (int) $snapshot->cpu_allocated_cores + + $usage['cpu_sum'], + 'memory_used' => (int) $snapshot->memory_allocated_mib + + $usage['memory_sum'], + 'disk_used' => (int) $snapshot->storage_allocated_bytes + + ($usage['disk_sum'] * self::GIB), + 'instances' => (int) $snapshot->instance_total_count + + $usage['instance_count'], + 'max_instances' => (int) $policy->max_instances, + ]; + } + + private static function hasCapacity($policy, $snapshot, array $usage, + array $resources): bool + { + $state = self::capacityState($policy, $snapshot, $usage); + return $state['cpu_used'] + $resources['cpu_cores'] <= $state['cpu_limit'] + && $state['memory_used'] + $resources['memory_mib'] + <= $state['memory_limit'] + && $state['disk_used'] + ($resources['disk_gib'] * self::GIB) + <= $state['disk_limit'] + && ($state['max_instances'] < 1 + || $state['instances'] + 1 <= $state['max_instances']); + } + + private static function capacityScore($policy, $snapshot, + array $usage): float + { + $state = self::capacityState($policy, $snapshot, $usage); + $instanceScore = $state['max_instances'] > 0 + ? $state['instances'] / $state['max_instances'] : 0.0; + return max( + $state['cpu_used'] / max(1, $state['cpu_limit']), + $state['memory_used'] / max(1, $state['memory_limit']), + $state['disk_used'] / max(1, $state['disk_limit']), + $instanceScore + ); + } + + private static function availablePublicIpQuery(int $hostId) + { + return CloudPublicIp::query()->where('host_id', $hostId) + ->where('state', 'available')->orderBy('id'); + } + private static function freshnessSeconds(): int { $value = filter_var(Config::get('cloud_capacity_fresh_seconds', 120), diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 7dd77784..7a75144e 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -430,6 +430,7 @@ function saleOffers(regionId = state.selectedRegionId, lineId = state.selectedLi && String(offer?.line_id ?? '') === String(lineId) && String(offer?.currency || '').toUpperCase() === 'USD'); } +function isOfferSellable(offer) { return offer?.sellable === true; } function defaultSaleLine(lines) { return lines.find(line => line.isDefault) || lines[0] || null; } function applySaleCatalog(catalog) { state.regions = bootstrapItems(catalog, 'regions'); @@ -456,7 +457,7 @@ function setDeploymentStepEnabled(id, enabled) { function updateCreateAvailability() { 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 || !offer || !validMedia; + if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(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) { @@ -536,12 +537,17 @@ function renderLinePicker() { } function renderOfferPicker() { const container = byId('vm-offer-picker'); - const selectedOfferId = byId('vm-offer').value; + const offerInput = byId('vm-offer'); + let selectedOfferId = offerInput.value; const offers = saleOffers(); if (!offers.length) { container.replaceChildren(makeElement('p', 'template-catalog-empty', '当前选择暂无可用实例规格。')); return; } + if (!offers.some(offer => String(offer.id) === selectedOfferId && isOfferSellable(offer))) { + offerInput.value = ''; + selectedOfferId = ''; + } const header = makeElement('div', 'offer-table-head'); ['名称', 'CPU', '内存', '硬盘', '每期流量', '价格'].forEach(label => header.append(makeElement('span', '', label))); const rows = offers.map(offer => { @@ -549,19 +555,27 @@ function renderOfferPicker() { const memory = formatMemoryGiB(offer.memory_mib); const traffic = formatTrafficTiB(offer.traffic_tib); const price = formatUsd(offer.price); + const sellable = isOfferSellable(offer); + const name = makeElement('strong', 'offer-option-name', offer.name); + if (!sellable) name.append(makeElement('span', 'offer-option-status', '暂时售罄')); button.type = 'button'; 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.classList.toggle('is-sold-out', !sellable); + button.disabled = !sellable; + button.setAttribute('aria-disabled', String(!sellable)); + button.setAttribute('aria-pressed', String(sellable && selectedOfferId === String(offer.id))); + button.setAttribute('aria-label', sellable + ? `选择实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price}` + : `实例规格 ${offer.name},${offer.cpu_cores} vCPU,内存 ${memory},硬盘 ${offer.disk_gib} GB,每期流量 ${traffic},价格 ${price},暂时售罄`); button.append( - makeElement('strong', 'offer-option-name', offer.name), + 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 selectOffer(String(offer.id))); + if (sellable) button.addEventListener('click', () => void selectOffer(String(offer.id))); return button; }); container.replaceChildren(header, ...rows); @@ -602,7 +616,7 @@ async function selectLine(lineId) { async function selectOffer(offerId) { if (state.mutationBusy) return; const offer = saleOffers().find(item => String(item.id) === String(offerId)); - if (!offer) return; + if (!isOfferSellable(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))); @@ -724,6 +738,7 @@ async function buy(event) { 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', '地区、线路与实例规格不匹配,请重新选择。'); + if (!isOfferSellable(selectedOffer)) return showError('create-error', '该实例规格暂时售罄,请选择其他规格。'); const purchaseSummary = `${formatUsd(selectedOffer.price)},${offerBillingLabel(selectedOffer)}`; if (!confirm(`确认创建此实例?将先生成 ${purchaseSummary} 的开通账单,支付完成后才会开始创建。`)) return; state.mutationBusy = true; diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index 0055a522..e1a45f60 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -230,8 +230,13 @@ tbody tr:hover{background:#fcfefe} .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-name{display:flex;align-items:center;gap:7px;flex-wrap:wrap} .offer-option-price{color:#0d929d;font-size:13px} .offer-option-value{min-width:0;font-size:11px;font-weight:700;white-space:nowrap} +.offer-option.is-sold-out{cursor:not-allowed;opacity:1;background:#f8fafb;color:#8b99a6} +.offer-option.is-sold-out:hover{background:#f8fafb} +.offer-option.is-sold-out .offer-option-name,.offer-option.is-sold-out .offer-option-price{color:#697b8c} +.offer-option-status{display:inline-flex;align-items:center;min-height:20px;padding:2px 7px;border-radius:999px;background:#edf1f4;color:#6f7e8c;font-size:9px;font-weight:800;line-height:1;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), @@ -277,5 +282,5 @@ body.vu-body .ssh-key-picker-manage:hover { .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,.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%}} +@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.is-sold-out::after{display:none}.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.is-sold-out .offer-option-price{padding-right:0}.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 8e808c9a..74a2125a 100644 --- a/web/resources/views/venix/cloud/pages/deploy.tpl +++ b/web/resources/views/venix/cloud/pages/deploy.tpl @@ -46,8 +46,8 @@ {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} -