diff --git a/web/app/Services/Cloud/CloudTrafficPoolReadModel.php b/web/app/Services/Cloud/CloudTrafficPoolReadModel.php index 8d4184a9..414635e9 100644 --- a/web/app/Services/Cloud/CloudTrafficPoolReadModel.php +++ b/web/app/Services/Cloud/CloudTrafficPoolReadModel.php @@ -5,6 +5,7 @@ namespace App\Services\Cloud; use App\Models\CloudInstance; use App\Models\CloudInstanceNetworkPolicyState; use App\Models\CloudInstanceNetworkRestriction; +use App\Models\CloudNetworkLine; use App\Models\CloudServicePeriod; use App\Models\CloudTrafficEntitlement; use App\Models\CloudTrafficPoolGroup; @@ -117,19 +118,31 @@ final class CloudTrafficPoolReadModel ); } $networkStates = self::networkStates($instancesByGroup, $poolStates); + $regionScopes = self::regionScopes($visibleGroupIds); $items = []; foreach ($groups as $group) { $groupId = (int) $group->id; - $items[] = self::poolDto( + $item = self::poolDto( $group, $instancesByGroup[$groupId] ?? [], $networkStates[$groupId] ?? 'clear', $snapshots[$userId . ':' . $groupId], isset($pendingGroups[$groupId]) ); + $item['region_scope'] = self::publicRegionScope( + $regionScopes[$groupId] ?? self::unassignedRegionScope() + ); + $items[] = $item; } - return ['items' => $items, 'generated_at' => $now]; + $regionGroups = self::regionGroups($items, $regionScopes); + return [ + 'items' => $items, + 'region_groups' => $regionGroups, + 'region_count' => count($regionGroups), + 'pool_count' => count($items), + 'generated_at' => $now, + ]; } /** Resolve the exact accounting vocabulary used by one instance detail. */ @@ -348,6 +361,259 @@ final class CloudTrafficPoolReadModel return $result; } + /** + * Resolve every visible commercial group to one display scope in one + * query. A cross-region pool remains one pool: duplicating it beneath + * each region would duplicate the same accounting projection visually. + * + * @return array> + */ + private static function regionScopes(array $groupIds): array + { + if ($groupIds === []) { + return []; + } + $rows = CloudNetworkLine::query() + ->leftJoin('cloud_regions as traffic_region', + 'traffic_region.id', '=', 'cloud_network_lines.region_id') + ->whereIn('cloud_network_lines.traffic_pool_group_id', $groupIds) + ->orderBy('traffic_region.sort')->orderBy('traffic_region.id') + ->orderBy('cloud_network_lines.sort') + ->orderBy('cloud_network_lines.id') + ->get([ + 'cloud_network_lines.traffic_pool_group_id as group_id', + 'cloud_network_lines.region_id as line_region_id', + 'traffic_region.id as region_id', + 'traffic_region.code as region_code', + 'traffic_region.name as region_name', + 'traffic_region.sort as region_sort', + ]); + $regionsByGroup = []; + $unresolved = []; + foreach ($rows as $row) { + $groupId = (int) $row->group_id; + $regionId = (int) ($row->region_id ?? 0); + if ($regionId < 1 || (int) ($row->line_region_id ?? 0) < 1) { + $unresolved[$groupId] = true; + continue; + } + $regionsByGroup[$groupId][$regionId] = [ + 'id' => $regionId, + 'code' => (string) $row->region_code, + 'name' => (string) $row->region_name, + 'sort' => (int) $row->region_sort, + ]; + } + + $scopes = []; + foreach ($groupIds as $groupId) { + $groupId = (int) $groupId; + $regions = array_values($regionsByGroup[$groupId] ?? []); + usort($regions, static fn (array $left, array $right): int => + [$left['sort'], $left['id']] <=> [$right['sort'], $right['id']] + ); + if (isset($unresolved[$groupId]) || $regions === []) { + $scope = self::unassignedRegionScope(); + $scope['regions'] = $regions; + $scopes[$groupId] = $scope; + continue; + } + if (count($regions) > 1) { + $scopes[$groupId] = [ + 'key' => 'region:cross', + 'kind' => 'cross_region', + 'region' => null, + 'regions' => $regions, + 'name' => '跨地区线路组', + 'description' => '涉及 ' . implode('、', array_column( + $regions, 'name' + )), + '_sort' => PHP_INT_MAX - 1, + '_region_id' => PHP_INT_MAX - 1, + ]; + continue; + } + $region = $regions[0]; + $scopes[$groupId] = [ + 'key' => 'region:' . $region['code'], + 'kind' => 'region', + 'region' => $region, + 'regions' => $regions, + 'name' => $region['name'], + 'description' => '按线路独立核算共享额度', + '_sort' => $region['sort'], + '_region_id' => $region['id'], + ]; + } + return $scopes; + } + + /** @return array */ + private static function unassignedRegionScope(): array + { + return [ + 'key' => 'region:unassigned', + 'kind' => 'unassigned', + 'region' => null, + 'regions' => [], + 'name' => '地区待配置', + 'description' => '线路尚未绑定有效地区', + '_sort' => PHP_INT_MAX, + '_region_id' => PHP_INT_MAX, + ]; + } + + /** @return array */ + private static function publicRegionScope(array $scope): array + { + $regions = []; + foreach ($scope['regions'] ?? [] as $region) { + $regions[] = [ + 'code' => (string) ($region['code'] ?? ''), + 'name' => (string) ($region['name'] ?? '未知地区'), + ]; + } + $region = $scope['region'] ?? null; + return [ + 'kind' => (string) $scope['kind'], + 'region' => is_array($region) ? [ + 'code' => (string) ($region['code'] ?? ''), + 'name' => (string) ($region['name'] ?? ''), + ] : null, + 'regions' => $regions, + ]; + } + + /** @return list> */ + private static function regionGroups(array $items, array $scopes): array + { + $decorated = []; + foreach ($items as $item) { + $groupId = (int) ($item['group_id'] ?? 0); + $scope = $scopes[$groupId] ?? self::unassignedRegionScope(); + $decorated[] = [ + 'sort' => (int) $scope['_sort'], + 'region_id' => (int) $scope['_region_id'], + 'group_id' => $groupId, + 'scope' => $scope, + 'item' => $item, + ]; + } + usort($decorated, static fn (array $left, array $right): int => + [$left['sort'], $left['region_id'], $left['group_id']] + <=> [$right['sort'], $right['region_id'], $right['group_id']] + ); + + $groups = []; + foreach ($decorated as $row) { + $scope = $row['scope']; + $key = (string) $scope['key']; + if (!isset($groups[$key])) { + $groups[$key] = [ + 'key' => $key, + 'kind' => (string) $scope['kind'], + 'name' => (string) $scope['name'], + 'description' => (string) $scope['description'], + 'regions' => [], + '_regions' => [], + 'pool_count' => 0, + 'instance_count' => 0, + 'summary_state' => (string) $scope['kind'] === 'unassigned' + ? 'attention' : 'available', + 'requires_attention' => + (string) $scope['kind'] === 'unassigned', + 'default_open' => false, + 'items' => [], + ]; + } + foreach ($scope['regions'] ?? [] as $region) { + $regionId = (int) ($region['id'] ?? 0); + if ($regionId > 0) { + $groups[$key]['_regions'][$regionId] = $region; + } + } + $item = $row['item']; + $groups[$key]['items'][] = $item; + $groups[$key]['pool_count']++; + $groups[$key]['instance_count'] += count($item['instances'] ?? []); + $candidate = self::regionPoolState($item); + if (self::regionStatePriority($candidate) + > self::regionStatePriority($groups[$key]['summary_state'])) { + $groups[$key]['summary_state'] = $candidate; + } + $groups[$key]['requires_attention'] = + $groups[$key]['summary_state'] !== 'available'; + } + + $groups = array_values($groups); + foreach ($groups as &$group) { + $regions = array_values($group['_regions']); + usort($regions, static fn (array $left, array $right): int => + [$left['sort'], $left['id']] <=> [$right['sort'], $right['id']] + ); + $scope = ['kind' => $group['kind'], 'region' => null, + 'regions' => $regions]; + $group['regions'] = self::publicRegionScope($scope)['regions']; + if ($group['kind'] === 'cross_region') { + $group['description'] = '涉及 ' . implode('、', array_column( + $group['regions'], 'name' + )); + } + unset($group['_regions']); + } + unset($group); + $hasAttention = false; + foreach ($groups as $group) { + $hasAttention = $hasAttention + || (bool) $group['requires_attention']; + } + foreach ($groups as $index => &$group) { + $group['default_open'] = count($groups) === 1 + || ($hasAttention + ? (bool) $group['requires_attention'] + : $index === 0); + } + unset($group); + return $groups; + } + + private static function regionPoolState(array $pool): string + { + $state = (string) ($pool['state'] ?? ''); + $network = (string) ($pool['network_restriction_state'] ?? ''); + if (!in_array($state, + ['available', 'exhausted', 'attention', 'preparing'], true) + || !in_array($network, + ['clear', 'applying', 'restricted', 'attention'], true)) { + return 'attention'; + } + if ($state === 'attention' || $network === 'attention') { + return 'attention'; + } + if ($network === 'restricted') { + return 'restricted'; + } + if ($state === 'exhausted') { + return 'exhausted'; + } + if ($network === 'applying') { + return 'applying'; + } + return $state === 'preparing' ? 'preparing' : 'available'; + } + + private static function regionStatePriority(string $state): int + { + return match ($state) { + 'attention' => 5, + 'restricted' => 4, + 'exhausted' => 3, + 'applying' => 2, + 'preparing' => 1, + default => 0, + }; + } + /** @return array */ private static function networkStates( array $instancesByGroup, diff --git a/web/app/Services/Cloud/CloudUserPageView.php b/web/app/Services/Cloud/CloudUserPageView.php index 24d7d26a..193f4408 100644 --- a/web/app/Services/Cloud/CloudUserPageView.php +++ b/web/app/Services/Cloud/CloudUserPageView.php @@ -75,105 +75,159 @@ final class CloudUserPageView public static function trafficPools(array $payload): array { - $items = []; - foreach ($payload['items'] ?? [] as $pool) { - $projectionReady = ($pool['projection_ready'] ?? false) === true; + $regions = []; + foreach ($payload['region_groups'] ?? [] as $region) { [$stateLabel, $stateClass] = self::state( - (string) ($pool['state'] ?? ''), + (string) ($region['summary_state'] ?? ''), [ - 'available' => ['可用', 'running'], - 'exhausted' => ['已用尽', 'stopped'], - 'attention' => ['需要核查', 'stopped'], + 'available' => ['状态正常', 'running'], 'preparing' => ['额度准备中', 'warning'], - ] - ); - [$networkLabel, $networkClass] = self::state( - (string) ($pool['network_restriction_state'] ?? ''), - [ - 'clear' => ['网络正常', 'running'], 'applying' => ['网络策略应用中', 'warning'], - 'restricted' => ['已因共享流量耗尽断网', 'stopped'], - 'attention' => ['网络策略需要人工核查', 'stopped'], + 'exhausted' => ['存在已用尽流量池', 'stopped'], + 'restricted' => ['存在断网实例', 'stopped'], + 'attention' => ['需要核查', 'stopped'], ] ); - $instances = []; - foreach ($pool['instances'] ?? [] as $instance) { - [$instanceNetworkLabel, $instanceNetworkClass] = self::state( - (string) ($instance['network_status'] ?? ''), - [ - 'active' => ['网络正常', 'running'], - 'blocking' => ['正在停用网络', 'warning'], - 'blocked_traffic' => ['共享流量用尽,已断网', 'stopped'], - 'blocked_expired' => ['服务到期,已断网', 'stopped'], - 'restoring' => ['正在恢复网络', 'warning'], - 'restore_pending' => ['等待恢复网络', 'warning'], - ] - ); - $instances[] = [ - 'id' => (string) ($instance['id'] ?? ''), - 'name' => self::text( - $instance['name'] ?? '', - '实例 #' . (string) ($instance['id'] ?? '') - ), - 'used_display' => self::bytes( - $instance['traffic_used_bytes'] ?? null - ), - 'period_quota_display' => self::bytes( - $instance['period_traffic_quota_bytes'] ?? null - ), - 'download_display' => self::bytes( - $instance['traffic_download_bytes'] ?? null - ), - 'upload_display' => self::bytes( - $instance['traffic_upload_bytes'] ?? null - ), - 'expires_display' => self::date( - $instance['service_expires_at'] ?? null - ), - 'network_label' => $instanceNetworkLabel, - 'network_class' => $instanceNetworkClass, - ]; + $items = []; + foreach ($region['items'] ?? [] as $pool) { + $items[] = self::trafficPool($pool); } - $items[] = [ - 'group_id' => (int) ($pool['group_id'] ?? 0), - 'name' => self::text($pool['name'] ?? '', '共享流量池'), + $regions[] = [ + 'key' => self::text($region['key'] ?? '', 'region:unknown'), + 'kind' => self::text($region['kind'] ?? '', 'unassigned'), + 'name' => self::text($region['name'] ?? '', '地区待配置'), + 'description' => self::text( + $region['description'] ?? '', + '按线路独立核算共享额度' + ), + 'pool_count' => max(0, (int) ($region['pool_count'] ?? 0)), + 'instance_count' => max( + 0, + (int) ($region['instance_count'] ?? 0) + ), 'state_label' => $stateLabel, 'state_class' => $stateClass, - 'network_label' => $networkLabel, - 'network_class' => $networkClass, - 'entitlement_display' => $projectionReady ? self::bytes( - $pool['active_entitlement_bytes'] ?? null - ) : '正在准备', - 'consumed_display' => $projectionReady ? self::bytes( - $pool['active_consumed_bytes'] ?? null - ) : '正在准备', - 'available_display' => $projectionReady ? self::bytes( - $pool['available_bytes'] ?? null - ) : '正在准备', - 'overage_display' => $projectionReady ? self::bytes( - $pool['overage_bytes'] ?? null - ) : '正在准备', - 'next_expiry_display' => !$projectionReady - ? '额度准备中' - : (empty($pool['next_expiry_at']) - ? '暂无即将到期额度' - : self::date($pool['next_expiry_at'])), - 'next_expiry_bytes_display' => self::bytes( - $pool['next_expiry_bytes'] ?? null + 'requires_attention' => + ($region['requires_attention'] ?? false) === true, + 'default_open' => ($region['default_open'] ?? false) === true, + 'items' => $items, + ]; + } + return [ + 'regions' => $regions, + 'region_count' => max(0, (int) ($payload['region_count'] ?? 0)), + 'pool_count' => max(0, (int) ($payload['pool_count'] ?? 0)), + ]; + } + + /** @return array */ + private static function trafficPool(array $pool): array + { + $projectionReady = ($pool['projection_ready'] ?? false) === true; + [$stateLabel, $stateClass] = self::state( + (string) ($pool['state'] ?? ''), + [ + 'available' => ['可用', 'running'], + 'exhausted' => ['已用尽', 'stopped'], + 'attention' => ['需要核查', 'stopped'], + 'preparing' => ['额度准备中', 'warning'], + ] + ); + [$networkLabel, $networkClass] = self::state( + (string) ($pool['network_restriction_state'] ?? ''), + [ + 'clear' => ['网络正常', 'running'], + 'applying' => ['网络策略应用中', 'warning'], + 'restricted' => ['已因共享流量耗尽断网', 'stopped'], + 'attention' => ['网络策略需要人工核查', 'stopped'], + ] + ); + $instances = []; + foreach ($pool['instances'] ?? [] as $instance) { + [$instanceNetworkLabel, $instanceNetworkClass] = self::state( + (string) ($instance['network_status'] ?? ''), + [ + 'active' => ['网络正常', 'running'], + 'blocking' => ['正在停用网络', 'warning'], + 'blocked_traffic' => ['共享流量用尽,已断网', 'stopped'], + 'blocked_expired' => ['服务到期,已断网', 'stopped'], + 'restoring' => ['正在恢复网络', 'warning'], + 'restore_pending' => ['等待恢复网络', 'warning'], + ] + ); + $instances[] = [ + 'id' => (string) ($instance['id'] ?? ''), + 'name' => self::text( + $instance['name'] ?? '', + '实例 #' . (string) ($instance['id'] ?? '') + ), + 'used_display' => self::bytes( + $instance['traffic_used_bytes'] ?? null ), - 'next_expiry_note' => $projectionReady - ? '届时作废 ' . self::bytes( - $pool['next_expiry_bytes'] ?? null - ) : '账本投影尚未生成', - 'last_observed_display' => !$projectionReady - ? '等待首次核算' - : (empty($pool['last_observed_at']) - ? '暂未完成采样' - : self::date($pool['last_observed_at'])), - 'instances' => $instances, + 'period_quota_display' => self::bytes( + $instance['period_traffic_quota_bytes'] ?? null + ), + 'download_display' => self::bytes( + $instance['traffic_download_bytes'] ?? null + ), + 'upload_display' => self::bytes( + $instance['traffic_upload_bytes'] ?? null + ), + 'expires_display' => self::date( + $instance['service_expires_at'] ?? null + ), + 'network_label' => $instanceNetworkLabel, + 'network_class' => $instanceNetworkClass, ]; } - return ['items' => $items, 'count' => count($items)]; + $scope = $pool['region_scope'] ?? []; + $scopeNames = array_map( + static fn (array $region): string => (string) ($region['name'] ?? ''), + array_values(array_filter( + is_array($scope['regions'] ?? null) ? $scope['regions'] : [], + 'is_array' + )) + ); + $scopeKind = (string) ($scope['kind'] ?? ''); + $scopeNote = $scopeKind === 'cross_region' + ? '涉及 ' . implode('、', array_filter($scopeNames)) + : ($scopeKind === 'unassigned' ? '地区信息待核查' : ''); + return [ + 'group_id' => (int) ($pool['group_id'] ?? 0), + 'name' => self::text($pool['name'] ?? '', '共享流量池'), + 'scope_note' => $scopeNote, + 'state_label' => $stateLabel, + 'state_class' => $stateClass, + 'network_label' => $networkLabel, + 'network_class' => $networkClass, + 'entitlement_display' => $projectionReady ? self::bytes( + $pool['active_entitlement_bytes'] ?? null + ) : '正在准备', + 'consumed_display' => $projectionReady ? self::bytes( + $pool['active_consumed_bytes'] ?? null + ) : '正在准备', + 'available_display' => $projectionReady ? self::bytes( + $pool['available_bytes'] ?? null + ) : '正在准备', + 'overage_display' => $projectionReady ? self::bytes( + $pool['overage_bytes'] ?? null + ) : '正在准备', + 'next_expiry_display' => !$projectionReady + ? '额度准备中' + : (empty($pool['next_expiry_at']) + ? '暂无即将到期额度' + : self::date($pool['next_expiry_at'])), + 'next_expiry_note' => $projectionReady + ? '届时作废 ' . self::bytes( + $pool['next_expiry_bytes'] ?? null + ) : '账本投影尚未生成', + 'last_observed_display' => !$projectionReady + ? '等待首次核算' + : (empty($pool['last_observed_at']) + ? '暂未完成采样' + : self::date($pool['last_observed_at'])), + 'instances' => $instances, + ]; } public static function vpcs(array $payload, array $query): array diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index e9dd50ea..0b12a3cf 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -305,6 +305,24 @@ body.vu-body .ssh-key-picker-manage:hover { .cloud-traffic-panel>.panel-heading{padding:20px 22px;border-bottom:1px solid #e8eef2} .cloud-traffic-panel>#cloud-traffic-status{margin:18px 22px 0} .cloud-traffic-list{display:grid;gap:16px;padding:20px 22px} +.cloud-traffic-region{min-width:0;border:1px solid #dbe6eb;border-radius:14px;background:#f8fbfc;overflow:hidden} +.cloud-traffic-region-summary{display:flex;align-items:center;justify-content:space-between;gap:20px;min-height:72px;padding:14px 18px;background:#fff;cursor:pointer;list-style:none;user-select:none} +.cloud-traffic-region-summary::-webkit-details-marker{display:none} +.cloud-traffic-region-summary::marker{content:""} +.cloud-traffic-region-summary:hover{background:#fbfefe} +.cloud-traffic-region-summary:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:-3px} +.cloud-traffic-region[open]>.cloud-traffic-region-summary{border-bottom:1px solid #e3ebef;background:#fbfefe} +.cloud-traffic-region-identity{display:flex;align-items:center;gap:12px;min-width:0} +.cloud-traffic-region-icon{display:grid;place-items:center;flex:0 0 38px;width:38px;height:38px;border-radius:11px;background:#eaf7f8;color:#178e98;font-size:18px} +.cloud-traffic-region-title{display:grid;gap:4px;min-width:0} +.cloud-traffic-region-title strong{color:#2c465a;font-size:14px;overflow-wrap:anywhere} +.cloud-traffic-region-title small{color:#8496a4;font-size:10px;line-height:1.45;overflow-wrap:anywhere} +.cloud-traffic-region-meta{display:flex;align-items:center;justify-content:flex-end;gap:11px;flex:none} +.cloud-traffic-region-counts{display:flex;align-items:center;gap:9px;color:#718594;font-size:10px;white-space:nowrap} +.cloud-traffic-region-counts>span+span{padding-left:9px;border-left:1px solid #dce5e9} +.cloud-traffic-region-arrow{display:grid;place-items:center;width:26px;height:26px;color:#738997;font-size:18px;transition:transform .18s ease} +.cloud-traffic-region[open] .cloud-traffic-region-arrow{transform:rotate(180deg)} +.cloud-traffic-region-body{display:grid;gap:14px;padding:16px;background:#f7fafb} .cloud-traffic-card{display:grid;gap:18px;min-width:0;padding:19px;border:1px solid #dfe8ed;border-radius:12px;background:#fff} .cloud-traffic-card-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:18px} .cloud-traffic-card-heading>div:first-child{display:flex;align-items:center;gap:12px;min-width:0} @@ -339,7 +357,7 @@ body.vu-body .ssh-key-picker-manage:hover { .cloud-traffic-empty>span:last-child{font-size:10px;line-height:1.6} @media(max-width:1100px){.cloud-traffic-instance{grid-template-columns:1fr}.cloud-traffic-instance dl{grid-template-columns:repeat(2,minmax(0,1fr))}} @media(max-width:820px){.cloud-traffic-facts{grid-template-columns:repeat(2,minmax(0,1fr))}} -@media(max-width:510px){.cloud-traffic-panel>.panel-heading,.cloud-traffic-list{padding-inline:16px}.cloud-traffic-card{padding:15px}.cloud-traffic-card-heading{align-items:flex-start;flex-direction:column}.cloud-traffic-state-group{justify-content:flex-start}.cloud-traffic-facts{grid-template-columns:1fr 1fr}.cloud-traffic-instance{padding:12px}.cloud-traffic-instance dl{grid-template-columns:1fr}.cloud-traffic-instance dl>div{display:flex;align-items:center;justify-content:space-between;gap:10px}.cloud-traffic-instance dd{text-align:right}} +@media(max-width:510px){.cloud-traffic-panel>.panel-heading,.cloud-traffic-list{padding-inline:16px}.cloud-traffic-panel>.panel-heading{align-items:flex-start}.cloud-traffic-panel>.panel-heading>.state-pill{white-space:normal}.cloud-traffic-region-summary{align-items:stretch;flex-direction:column;gap:11px;min-height:88px;padding:14px}.cloud-traffic-region-meta{justify-content:space-between;width:100%;gap:8px}.cloud-traffic-region-counts{gap:7px}.cloud-traffic-region-counts>span+span{padding-left:7px}.cloud-traffic-region-meta>.state-pill{margin-left:auto;white-space:normal;text-align:center}.cloud-traffic-region-arrow{flex:0 0 26px}.cloud-traffic-region-body{gap:12px;padding:12px}.cloud-traffic-card{padding:15px}.cloud-traffic-card-heading{align-items:flex-start;flex-direction:column}.cloud-traffic-state-group{justify-content:flex-start}.cloud-traffic-facts{grid-template-columns:1fr 1fr}.cloud-traffic-instance{padding:12px}.cloud-traffic-instance dl{grid-template-columns:1fr}.cloud-traffic-instance dl>div{display:flex;align-items:center;justify-content:space-between;gap:10px}.cloud-traffic-instance dd{text-align:right}} /* VPC list, creation and member views share the existing user shell. */ #cloud-vpcs-workspace { color:#304a5d; min-width:0; scroll-margin-top:100px; } diff --git a/web/public/cloud/traffic.js b/web/public/cloud/traffic.js index 1b9ef9a7..262c144a 100644 --- a/web/public/cloud/traffic.js +++ b/web/public/cloud/traffic.js @@ -11,7 +11,10 @@ const { api, byId, initializeSession, readBootstrap, showError, } = await import(versionedModuleUrl('./runtime.js')); -const state = { items: [], loading: false, controller: null }; +const state = { + regions: [], regionCount: 0, poolCount: 0, + loading: false, controller: null, +}; function element(tag, className = '', content) { const node = document.createElement(tag); @@ -62,6 +65,17 @@ function restrictionState(value) { })[String(value || '')] || ['网络状态未知', 'other']; } +function regionState(value) { + return ({ + available: ['状态正常', 'running'], + preparing: ['额度准备中', 'warning'], + applying: ['网络策略应用中', 'warning'], + exhausted: ['存在已用尽流量池', 'stopped'], + restricted: ['存在断网实例', 'stopped'], + attention: ['需要核查', 'stopped'], + })[String(value || '')] || ['状态未知', 'other']; +} + function instanceNetwork(value) { return ({ active: ['网络正常', 'running'], blocking: ['正在停用网络', 'warning'], @@ -110,59 +124,131 @@ function renderInstances(pool, section) { section.append(heading, list); } +function poolScopeNote(pool) { + const scope = pool?.region_scope; + if (scope?.kind === 'unassigned') return '地区信息待核查'; + if (scope?.kind !== 'cross_region') return ''; + const names = []; + for (const region of Array.isArray(scope.regions) ? scope.regions : []) { + const name = String(region?.name || '').trim(); + if (name && !names.includes(name)) names.push(name); + } + return names.length ? `涉及 ${names.join('、')}` : '跨地区线路组'; +} + +function renderPool(pool) { + const projectionReady = pool.projection_ready === true; + const card = element('article', 'cloud-traffic-card'); + const heading = element('header', 'cloud-traffic-card-heading'); + const identity = document.createElement('div'); + const title = document.createElement('div'); + const note = poolScopeNote(pool); + title.append(element('h3', '', pool.name || '共享流量池'), + element('p', '', `${note ? `${note} · ` : ''}共享额度按最早到期批次优先消耗`)); + identity.append(poolIcon(), title); + const states = element('div', 'cloud-traffic-state-group'); + const [stateLabel, stateClass] = poolState(pool.state); + const [networkLabel, networkClass] = restrictionState(pool.network_restriction_state); + states.append(element('span', `state-pill ${stateClass}`, stateLabel), + element('span', `state-pill ${networkClass}`, networkLabel)); + heading.append(identity, states); + const facts = element('dl', 'cloud-traffic-facts'); + const pending = '正在准备'; + facts.append(fact('当前有效额度', projectionReady + ? formatBytes(pool.active_entitlement_bytes) : pending), + fact('有效额度已消耗', projectionReady + ? formatBytes(pool.active_consumed_bytes) : pending), + fact('当前可用余额', projectionReady + ? formatBytes(pool.available_bytes) : pending), + fact('采样超额债务', projectionReady + ? formatBytes(pool.overage_bytes) : pending), + fact('下一批额度到期', projectionReady + ? formatDate(pool.next_expiry_at, '暂无即将到期额度') : '额度准备中', + projectionReady ? `届时作废 ${formatBytes(pool.next_expiry_bytes)}` : '账本投影尚未生成'), + fact('最近可信采样', projectionReady + ? formatDate(pool.last_observed_at, '暂未完成采样') : '等待首次核算')); + const instances = element('section', 'cloud-traffic-instances'); + instances.setAttribute('aria-label', `${pool.name || '共享流量池'} 中的当前实例`); + renderInstances(pool, instances); + card.append(heading, facts, instances); + return card; +} + +function existingRegionState(list) { + const result = new Map(); + for (const details of list.querySelectorAll( + 'details.cloud-traffic-region[data-region-key]', + )) { + result.set(details.getAttribute('data-region-key'), { + open: details.open === true, + requiresAttention: details.getAttribute('data-requires-attention') === '1', + }); + } + return result; +} + +function renderRegion(region, previousState) { + const key = String(region.key || 'region:unknown'); + const details = element('details', 'cloud-traffic-region'); + details.setAttribute('data-region-key', key); + const requiresAttention = region.requires_attention === true; + details.setAttribute('data-requires-attention', requiresAttention ? '1' : '0'); + const previous = previousState.get(key); + details.open = previous + ? (requiresAttention && !previous.requiresAttention ? true : previous.open) + : region.default_open === true; + const summary = element('summary', 'cloud-traffic-region-summary'); + const identity = element('span', 'cloud-traffic-region-identity'); + const icon = element('span', 'cloud-traffic-region-icon'); + const marker = element('i', 'mdi mdi-map-marker-radius'); + marker.setAttribute('aria-hidden', 'true'); + icon.append(marker); + const title = element('span', 'cloud-traffic-region-title'); + title.append(element('strong', '', region.name || '地区待配置'), + element('small', '', region.description || '按线路独立核算共享额度')); + identity.append(icon, title); + const meta = element('span', 'cloud-traffic-region-meta'); + const counts = element('span', 'cloud-traffic-region-counts'); + counts.append(element('span', '', `${Number(region.pool_count) || 0} 个流量池`), + element('span', '', `${Number(region.instance_count) || 0} 台实例`)); + const [statusLabel, statusClass] = regionState(region.summary_state); + const arrow = element('span', 'cloud-traffic-region-arrow', '⌄'); + arrow.setAttribute('aria-hidden', 'true'); + meta.append(counts, element('span', `state-pill ${statusClass}`, statusLabel), arrow); + summary.append(identity, meta); + const body = element('div', 'cloud-traffic-region-body'); + for (const pool of Array.isArray(region.items) ? region.items : []) { + if (pool && typeof pool === 'object') body.append(renderPool(pool)); + } + details.append(summary, body); + return details; +} + function render() { const list = byId('cloud-traffic-list'); + const previousState = existingRegionState(list); list.replaceChildren(); - if (!state.items.length) { + if (!state.regions.length) { const empty = element('div', 'cloud-traffic-empty'); empty.append(poolIcon(), element('strong', '', '当前没有已启用的共享流量池'), element('span', '', '管理员完成影子核算验收并启用后,将在这里显示共享额度。')); list.append(empty); } - for (const pool of state.items) { - const projectionReady = pool.projection_ready === true; - const card = element('article', 'cloud-traffic-card'); - const heading = element('header', 'cloud-traffic-card-heading'); - const identity = document.createElement('div'); - const title = document.createElement('div'); - title.append(element('h3', '', pool.name || '共享流量池'), - element('p', '', '共享额度按最早到期批次优先消耗')); - identity.append(poolIcon(), title); - const states = element('div', 'cloud-traffic-state-group'); - const [stateLabel, stateClass] = poolState(pool.state); - const [networkLabel, networkClass] = restrictionState(pool.network_restriction_state); - states.append(element('span', `state-pill ${stateClass}`, stateLabel), - element('span', `state-pill ${networkClass}`, networkLabel)); - heading.append(identity, states); - const facts = element('dl', 'cloud-traffic-facts'); - const pending = '正在准备'; - facts.append(fact('当前有效额度', projectionReady - ? formatBytes(pool.active_entitlement_bytes) : pending), - fact('有效额度已消耗', projectionReady - ? formatBytes(pool.active_consumed_bytes) : pending), - fact('当前可用余额', projectionReady - ? formatBytes(pool.available_bytes) : pending), - fact('采样超额债务', projectionReady - ? formatBytes(pool.overage_bytes) : pending), - fact('下一批额度到期', projectionReady - ? formatDate(pool.next_expiry_at, '暂无即将到期额度') : '额度准备中', - projectionReady ? `届时作废 ${formatBytes(pool.next_expiry_bytes)}` : '账本投影尚未生成'), - fact('最近可信采样', projectionReady - ? formatDate(pool.last_observed_at, '暂未完成采样') : '等待首次核算')); - const instances = element('section', 'cloud-traffic-instances'); - instances.setAttribute('aria-label', `${pool.name || '共享流量池'} 中的当前实例`); - renderInstances(pool, instances); - card.append(heading, facts, instances); - list.append(card); + for (const region of state.regions) { + list.append(renderRegion(region, previousState)); } - byId('cloud-traffic-count').textContent = `${state.items.length} 个`; + byId('cloud-traffic-count').textContent = + `${state.regionCount} 个地区分组 · ${state.poolCount} 个流量池`; byId('cloud-traffic-refresh').disabled = state.loading; } function applyPayload(payload) { - const values = Array.isArray(payload?.items) ? payload.items : []; - state.items = values.filter(item => item && typeof item === 'object' - && Number.isInteger(Number(item.group_id)) && Number(item.group_id) > 0); + const values = Array.isArray(payload?.region_groups) ? payload.region_groups : []; + state.regions = values.filter(region => region && typeof region === 'object' + && typeof region.key === 'string' && region.key !== '' + && Array.isArray(region.items)); + state.regionCount = Math.max(0, Number(payload?.region_count) || 0); + state.poolCount = Math.max(0, Number(payload?.pool_count) || 0); render(); } diff --git a/web/resources/views/venix/cloud/pages/traffic.tpl b/web/resources/views/venix/cloud/pages/traffic.tpl index 45e5e332..b3cb75c2 100644 --- a/web/resources/views/venix/cloud/pages/traffic.tpl +++ b/web/resources/views/venix/cloud/pages/traffic.tpl @@ -1,20 +1,54 @@
-
SHARED TRAFFIC

流量池

按线路查看当前有效的共享流量额度、到期批次和实例采样。

+
SHARED TRAFFIC

流量池

按地区和线路查看当前有效的共享流量额度、到期批次和实例采样。

额度按服务周期到期同一线路内的实例共享有效额度,并按最早到期优先消耗;实例到期时只作废该周期尚未使用的额度。
-

当前共享流量池

只显示已经进入强制执行的线路分组;“本周期总额度”是该实例当前服务周期贡献给共享池的总额度,“本实例已用”和 RX / TX 为当前周期采样,均不代表独占余额。

{$cloud_traffic_view.count|default:0|escape:'html'} 个
+
+

当前共享流量池

只显示已经进入强制执行的线路分组;地区用于整理线路,不会合并不同线路的额度;“本周期总额度”是该实例当前服务周期贡献给共享池的总额度。

+ {$cloud_traffic_view.region_count|default:0|escape:'html'} 个地区分组 · {$cloud_traffic_view.pool_count|default:0|escape:'html'} 个流量池 +
- {foreach $cloud_traffic_view.items|default:[] as $pool} -
-

{$pool.name|escape:'html'}

共享额度按最早到期批次优先消耗

{$pool.state_label|escape:'html'}{$pool.network_label|escape:'html'}
-
当前有效额度
{$pool.entitlement_display|escape:'html'}
有效额度已消耗
{$pool.consumed_display|escape:'html'}
当前可用余额
{$pool.available_display|escape:'html'}
采样超额债务
{$pool.overage_display|escape:'html'}
下一批额度到期
{$pool.next_expiry_display|escape:'html'}{$pool.next_expiry_note|escape:'html'}
最近可信采样
{$pool.last_observed_display|escape:'html'}
-

当前实例采样

{$pool.instances|@count|escape:'html'} 台
-
- {foreachelse}
当前没有已启用的共享流量池管理员完成影子核算验收并启用后,将在这里显示共享额度。
{/foreach} + {foreach $cloud_traffic_view.regions|default:[] as $region} +
+ + + + {$region.name|escape:'html'}{$region.description|escape:'html'} + + + {$region.pool_count|escape:'html'} 个流量池{$region.instance_count|escape:'html'} 台实例 + {$region.state_label|escape:'html'} + + + +
+ {foreach $region.items as $pool} +
+
+

{$pool.name|escape:'html'}

{if $pool.scope_note}{$pool.scope_note|escape:'html'} · {/if}共享额度按最早到期批次优先消耗

+
{$pool.state_label|escape:'html'}{$pool.network_label|escape:'html'}
+
+
当前有效额度
{$pool.entitlement_display|escape:'html'}
有效额度已消耗
{$pool.consumed_display|escape:'html'}
当前可用余额
{$pool.available_display|escape:'html'}
采样超额债务
{$pool.overage_display|escape:'html'}
下一批额度到期
{$pool.next_expiry_display|escape:'html'}{$pool.next_expiry_note|escape:'html'}
最近可信采样
{$pool.last_observed_display|escape:'html'}
+
+

当前实例采样

{$pool.instances|@count|escape:'html'} 台
+ +
+
+ {/foreach} +
+
+ {foreachelse} +
当前没有已启用的共享流量池管理员完成影子核算验收并启用后,将在这里显示共享额度。
+ {/foreach}
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 3101dbd4..4f86d516 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='2026110103' scope='global'} +{assign var=venix_asset_version value='2026110104' scope='global'} diff --git a/web/tests/CloudTrafficPoolRegionBehaviorTest.mjs b/web/tests/CloudTrafficPoolRegionBehaviorTest.mjs new file mode 100644 index 00000000..13a3034a --- /dev/null +++ b/web/tests/CloudTrafficPoolRegionBehaviorTest.mjs @@ -0,0 +1,162 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import vm from 'node:vm'; + +const moduleSource = await readFile( + new URL('../public/cloud/traffic.js', import.meta.url), + 'utf8', +); +const source = `const state = ${moduleSource.split('const state = ')[1]}` + .replace('export async function initialize()', 'async function initialize()'); + +class Node { + constructor(tag) { + Object.assign(this, { + tagName: tag.toUpperCase(), children: [], attributes: new Map(), + className: '', text: '', hidden: false, disabled: false, open: false, + }); + } + + set textContent(value) { this.text = String(value); this.replaceChildren(); } + get textContent() { + return this.text + this.children.map(child => child.textContent).join(''); + } + + append(...children) { + for (const child of children) { + child.parent = this; + this.children.push(child); + } + } + + replaceChildren(...children) { + this.children = []; + this.append(...children); + } + + setAttribute(name, value) { this.attributes.set(name, String(value)); } + getAttribute(name) { return this.attributes.get(name) ?? null; } + + querySelectorAll(selector) { + const matches = node => selector + === 'details.cloud-traffic-region[data-region-key]' + && node.tagName === 'DETAILS' + && node.className.split(/\s+/).includes('cloud-traffic-region') + && node.attributes.has('data-region-key'); + return this.children.flatMap(child => [ + ...(matches(child) ? [child] : []), + ...child.querySelectorAll(selector), + ]); + } +} + +const nodes = new Map([ + ['cloud-traffic-list', new Node('div')], + ['cloud-traffic-count', new Node('span')], + ['cloud-traffic-refresh', new Node('button')], +]); +const document = { createElement: tag => new Node(tag) }; +const context = vm.createContext({ + document, + window: { addEventListener() {} }, + URL, + AbortController, + console, + byId: id => nodes.get(id), + api: async () => { throw new Error('Unexpected request'); }, + initializeSession: async () => true, + readBootstrap: () => ({}), + showError() {}, +}); +vm.runInContext(`${source}\nglobalThis.traffic = { applyPayload };`, context, { + filename: 'traffic.js', +}); + +const pool = (id, name = `线路 ${id}`) => ({ + group_id: id, + name, + projection_ready: true, + state: 'available', + network_restriction_state: 'clear', + active_entitlement_bytes: 1024, + active_consumed_bytes: 0, + available_bytes: 1024, + overage_bytes: 0, + next_expiry_at: null, + next_expiry_bytes: 0, + last_observed_at: null, + instances: [], + region_scope: { kind: 'region', regions: [{ code: 'hkg', name: '香港' }] }, +}); +const region = (key, overrides = {}) => ({ + key, + kind: 'region', + name: key === 'region:hkg' ? '香港' : '新加坡', + description: '按线路独立核算共享额度', + pool_count: 1, + instance_count: 0, + summary_state: 'available', + requires_attention: false, + default_open: false, + items: [pool(key === 'region:hkg' ? 1 : 2)], + ...overrides, +}); +const payload = regions => ({ + region_groups: regions, + region_count: regions.length, + pool_count: regions.length, +}); +const details = () => nodes.get('cloud-traffic-list') + .querySelectorAll('details.cloud-traffic-region[data-region-key]'); + +context.traffic.applyPayload(payload([ + region('region:hkg', { default_open: true }), + region('region:sgp'), +])); +assert.deepEqual(details().map(item => item.open), [true, false], + 'Server default-open projection was not applied.'); +assert.equal(nodes.get('cloud-traffic-count').textContent, + '2 个地区分组 · 2 个流量池'); + +details()[0].open = false; +details()[1].open = true; +context.traffic.applyPayload(payload([ + region('region:hkg', { default_open: true }), + region('region:sgp'), +])); +assert.deepEqual(details().map(item => item.open), [false, true], + 'Refresh did not retain both expanded and collapsed user choices.'); + +context.traffic.applyPayload(payload([ + region('region:hkg', { + summary_state: 'attention', requires_attention: true, default_open: true, + }), + region('region:sgp'), +])); +assert.deepEqual(details().map(item => item.open), [true, true], + 'A region that changed from healthy to attention remained hidden.'); +details()[0].open = false; +context.traffic.applyPayload(payload([ + region('region:hkg', { + summary_state: 'attention', requires_attention: true, default_open: true, + }), + region('region:sgp'), +])); +assert.deepEqual(details().map(item => item.open), [false, true], + 'A user-collapsed attention region reopened on every refresh.'); + +context.traffic.applyPayload(payload([ + region('region:hkg', { + summary_state: 'attention', requires_attention: true, default_open: true, + }), + region('region:sgp'), + region('region:unassigned', { + kind: 'unassigned', name: '地区待配置', + summary_state: 'attention', requires_attention: true, default_open: true, + items: [pool(3)], + }), +])); +assert.deepEqual(details().map(item => item.open), [false, true, true], + 'A newly appearing attention region did not use its server default.'); + +console.log('Cloud traffic-pool region behavior checks passed.'); diff --git a/web/tests/CloudTrafficPoolUserReadModelTest.php b/web/tests/CloudTrafficPoolUserReadModelTest.php index f501ea5f..81be54d1 100644 --- a/web/tests/CloudTrafficPoolUserReadModelTest.php +++ b/web/tests/CloudTrafficPoolUserReadModelTest.php @@ -46,6 +46,28 @@ $schema->create('cloud_traffic_pool_groups', static function (Blueprint $table): $table->integer('created_at'); $table->integer('updated_at'); }); +$schema->create('cloud_regions', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('code')->unique(); + $table->string('name'); + $table->string('country_code'); + $table->string('status'); + $table->integer('sort')->default(0); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_network_lines', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('region_id'); + $table->integer('traffic_pool_group_id')->nullable(); + $table->string('code'); + $table->string('name'); + $table->boolean('is_default')->default(false); + $table->string('status'); + $table->integer('sort')->default(0); + $table->integer('created_at'); + $table->integer('updated_at'); +}); $schema->create('cloud_traffic_pools', static function (Blueprint $table): void { $table->increments('id'); $table->integer('user_id'); @@ -152,6 +174,38 @@ foreach ([ ]; } Capsule::table('cloud_traffic_pool_groups')->insert($groups); +Capsule::table('cloud_regions')->insert([ + ['id' => 10, 'code' => 'hkg', 'name' => '香港', + 'country_code' => 'HK', 'status' => 'active', 'sort' => 10, + 'created_at' => $now, 'updated_at' => $now], + ['id' => 20, 'code' => 'sgp', 'name' => '新加坡', + 'country_code' => 'SG', 'status' => 'active', 'sort' => 10, + 'created_at' => $now, 'updated_at' => $now], + ['id' => 30, 'code' => 'tyo', 'name' => '东京', + 'country_code' => 'JP', 'status' => 'active', 'sort' => 30, + 'created_at' => $now, 'updated_at' => $now], +]); +$lines = []; +foreach ([ + [1, 10, 1, 'hkg-a', '香港线路 A'], + [2, 10, 1, 'hkg-a2', '香港线路 A2'], + [3, 10, 2, 'hkg-shadow', '香港影子线路'], + [4, 20, 3, 'sgp-c', '新加坡线路 C'], + [5, 20, 5, 'sgp-e', '新加坡线路 E'], + [6, 10, 6, 'hkg-f', '香港跨区线路'], + [7, 20, 6, 'sgp-f', '新加坡跨区线路'], + [8, 20, 7, 'sgp-g', '新加坡线路 G'], + [9, 30, 3, 'tyo-c', '东京线路 C'], +] as [$id, $regionId, $groupId, $code, $name]) { + $lines[] = [ + 'id' => $id, 'region_id' => $regionId, + 'traffic_pool_group_id' => $groupId, + 'code' => $code, 'name' => $name, 'is_default' => 0, + 'status' => 'active', 'sort' => $id, + 'created_at' => $now, 'updated_at' => $now, + ]; +} +Capsule::table('cloud_network_lines')->insert($lines); Capsule::table('cloud_traffic_pools')->insert([ ['id' => 11, 'user_id' => 1, 'traffic_pool_group_id' => 1, 'state' => 'available', 'available_bytes' => 1100, @@ -181,6 +235,14 @@ Capsule::table('cloud_traffic_pools')->insert([ 'state' => 'available', 'available_bytes' => 0, 'overage_bytes' => 0, 'version' => 2, 'last_sequence' => 0, 'created_at' => $now, 'updated_at' => $now], + ['id' => 31, 'user_id' => 3, 'traffic_pool_group_id' => 1, + 'state' => 'available', 'available_bytes' => 100, + 'overage_bytes' => 0, 'version' => 1, 'last_sequence' => 0, + 'created_at' => $now, 'updated_at' => $now], + ['id' => 33, 'user_id' => 3, 'traffic_pool_group_id' => 5, + 'state' => 'available', 'available_bytes' => 100, + 'overage_bytes' => 0, 'version' => 1, 'last_sequence' => 0, + 'created_at' => $now, 'updated_at' => $now], ]); $instances = [ @@ -230,6 +292,8 @@ $entitlements = [ [6, 21, 2, 3, 103, 9999, 0, $now + 900, 'active'], [7, 16, 1, 97, 197, 500, 0, $now + 600, 'active'], [8, 17, 1, 96, 196, 400, 100, $now - 1, 'expired'], + [9, 31, 3, 301, 301, 100, 0, $now + 900, 'active'], + [10, 33, 3, 303, 303, 100, 0, $now + 900, 'active'], ]; foreach ($entitlements as [$id, $poolId, $userId, $instanceId, $periodId, $granted, $consumed, $endsAt, $state]) { @@ -281,6 +345,60 @@ Capsule::table('cloud_instance_network_policy_states')->insert([ $payload = CloudTrafficPoolReadModel::forUser(1, $now); $assert(array_column($payload['items'], 'group_id') === [1, 3, 4, 5, 6], 'User projection exposed shadow or foreign pools, or lost an entitlement-only pool.'); +$regionGroups = $payload['region_groups']; +$assert(array_column($regionGroups, 'key') === [ + 'region:hkg', 'region:sgp', 'region:cross', 'region:unassigned', + ] && $payload['region_count'] === 4 && $payload['pool_count'] === 5, + 'Traffic pools were not grouped in stable region order.'); +$regionPoolIds = []; +foreach ($regionGroups as $regionGroup) { + foreach ($regionGroup['items'] as $item) { + $regionPoolIds[] = $item['group_id']; + } +} +sort($regionPoolIds, SORT_NUMERIC); +$assert($regionPoolIds === [1, 3, 4, 5, 6], + 'A region scope duplicated or lost one canonical traffic pool.'); +$assert(array_column($regionGroups[0]['items'], 'group_id') === [1] + && $regionGroups[0]['pool_count'] === 1 + && $regionGroups[0]['instance_count'] === 1, + 'Same-region pools or instance counts were projected incorrectly.'); +$assert(array_column($regionGroups[1]['items'], 'group_id') === [5] + && $regionGroups[1]['instance_count'] === 1, + 'The second region lost its pool or instance summary.'); +$assert(array_column($regionGroups[2]['regions'], 'name') === [ + '香港', '新加坡', '东京', + ] && array_column($regionGroups[2]['items'], 'group_id') === [3, 6], + 'A cross-region pool was duplicated or its ordered region context was lost.'); +$assert($regionGroups[3]['kind'] === 'unassigned' + && array_column($regionGroups[3]['items'], 'group_id') === [4] + && $regionGroups[3]['summary_state'] === 'attention', + 'A pool without a valid region was hidden instead of marked for attention.'); +$assert(count(array_filter($regionGroups, + static fn (array $group): bool => $group['default_open'] === true)) === 3, + 'Attention, restricted or preparing regions were not opened by default.'); +$singleRegion = CloudTrafficPoolReadModel::forUser(2, $now); +$assert($singleRegion['region_count'] === 1 + && $singleRegion['region_groups'][0]['key'] === 'region:hkg' + && $singleRegion['region_groups'][0]['default_open'] === true, + 'A single healthy region should be open by default.'); +Capsule::table('cloud_traffic_pools')->where('id', 21)->update([ + 'state' => 'unexpected_state', +]); +$unknownState = CloudTrafficPoolReadModel::forUser(2, $now); +$assert($unknownState['region_groups'][0]['summary_state'] === 'attention' + && $unknownState['region_groups'][0]['default_open'] === true, + 'An unknown pool state was presented as a healthy collapsed region.'); +Capsule::table('cloud_traffic_pools')->where('id', 21)->update([ + 'state' => 'available', +]); +$healthyRegions = CloudTrafficPoolReadModel::forUser(3, $now); +$assert(array_column($healthyRegions['region_groups'], 'key') === [ + 'region:hkg', 'region:sgp', + ] && array_column( + $healthyRegions['region_groups'], 'default_open' + ) === [true, false], + 'Multiple healthy regions should open only the first region by default.'); $assertNoInternalFields($payload, 'User traffic-pool DTO exposed an internal identifier'); diff --git a/web/tests/CloudTrafficPoolUserUiContractTest.php b/web/tests/CloudTrafficPoolUserUiContractTest.php index 82a2cb49..571c50da 100644 --- a/web/tests/CloudTrafficPoolUserUiContractTest.php +++ b/web/tests/CloudTrafficPoolUserUiContractTest.php @@ -45,7 +45,11 @@ $assert(str_contains($readModel, && str_contains($readModel, "'projection_ready' => \$projectionReady") && str_contains($readModel, "'state' => \$projectionReady") && str_contains($readModel, - "'network_restriction_state' => \$networkState"), + "'network_restriction_state' => \$networkState") + && str_contains($readModel, 'private static function regionScopes(') + && str_contains($readModel, "'region_groups' => \$regionGroups") + && str_contains($readModel, "'key' => 'region:cross'") + && str_contains($readModel, "'key' => 'region:unassigned'"), 'User traffic pools must be owner-scoped, enforced-only and derived from the canonical accounting projection.'); $assert(str_contains($readModel, @@ -89,6 +93,13 @@ $assert(str_contains($sidebar, 'href="/user/cloud/traffic"') && str_contains($template, '{$instance.period_quota_display|escape:') && str_contains($template, '当前服务周期贡献给共享池的总额度') && str_contains($template, '本实例已用') + && str_contains($template, 'details class="cloud-traffic-region"') + && str_contains($template, 'data-region-key=') + && str_contains($template, 'data-requires-attention=') + && str_contains($template, 'cloud-traffic-region-summary') + && str_contains($template, '{$region.pool_count|escape:') + && str_contains($template, '{$region.instance_count|escape:') + && str_contains($template, '{if $region.default_open} open{/if}') && str_contains($template, '只显示已经进入强制执行的线路分组'), 'The user traffic-pool page lacks SSR first paint, navigation or clear shared-vs-instance copy.'); @@ -99,6 +110,12 @@ $assert(str_contains($script, && !str_contains($script, "method: 'DELETE'") && !str_contains($script, '.reduce(') && !str_contains($script, '.innerHTML') + && str_contains($script, 'payload?.region_groups') + && str_contains($script, 'function existingRegionState(') + && str_contains($script, 'const result = new Map()') + && str_contains($script, "requiresAttention: details.getAttribute('data-requires-attention') === '1'") + && str_contains($script, 'requiresAttention && !previous.requiresAttention') + && str_contains($script, 'region.default_open === true') && str_contains($script, 'pool.active_entitlement_bytes') && str_contains($script, 'pool.active_consumed_bytes') && str_contains($script, 'pool.available_bytes') @@ -116,6 +133,11 @@ $assert(str_contains($view, 'function trafficPools(') && str_contains($detail, '本实例本期下载(RX)') && str_contains($detail, '本实例本期上传(TX)') && str_contains($styles, '.cloud-traffic-facts') + && str_contains($styles, '.cloud-traffic-region-summary') + && str_contains($styles, + '.cloud-traffic-region-summary::-webkit-details-marker') + && str_contains($styles, + '.cloud-traffic-region[open] .cloud-traffic-region-arrow') && str_contains($styles, '.cloud-traffic-instance') && str_contains($styles, '.cloud-traffic-instance dl{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr))')