diff --git a/web/app/Controllers/AdminController.php b/web/app/Controllers/AdminController.php index fbcb4467..c0f968dd 100644 --- a/web/app/Controllers/AdminController.php +++ b/web/app/Controllers/AdminController.php @@ -12,6 +12,7 @@ use App\Services\AdminDataMasker; use App\Services\Auth; use App\Utils\Tools; use App\Services\Analytics; +use App\Services\Cloud\CloudAdminOverviewService; use App\Utils\SafeDatatables as Datatables; use App\Utils\DatatablesHelper; @@ -28,17 +29,19 @@ class AdminController extends UserController public function index($request, $response, $args) { - $sts = new Analytics(); - - //每日数据 - $days = []; - - for ($i = 7; $i >= 1; $i--) { - $day = date("Y-m-d", strtotime("-$i days")); - $days[] = $day; + $overviewError = ''; + try { + $overview = CloudAdminOverviewService::snapshot(); + } catch (\Throwable $exception) { + error_log('Admin overview snapshot failed: ' . $exception->getMessage()); + $overview = CloudAdminOverviewService::unavailable(); + $overviewError = '运营数据暂时无法读取,请确认已执行 cloudInit 并检查业务数据库。'; } - return $this->view()->assign(['sts' => $sts, 'days' => $days])->display('admin/index.tpl'); + return $this->view()->assign([ + 'overview' => $overview, + 'overview_error' => $overviewError, + ])->display('admin/index.tpl'); } diff --git a/web/app/Services/Cloud/CloudAdminOverviewService.php b/web/app/Services/Cloud/CloudAdminOverviewService.php new file mode 100644 index 00000000..da6bed9a --- /dev/null +++ b/web/app/Services/Cloud/CloudAdminOverviewService.php @@ -0,0 +1,441 @@ + true, + 'generated_at' => self::formatTimestamp($now, 'Y-m-d H:i:s'), + 'hosts' => $hosts, + 'instances' => $instances, + 'jobs' => $jobs, + 'revenue' => $revenue, + 'receivables' => $receivables, + 'users' => $users, + 'tickets' => $tickets, + 'top_plans' => $topPlans, + 'health' => [ + 'hosts_percent' => self::percentage($hosts['enabled'], $hosts['total']), + 'service_percent' => self::percentage( + $instances['service_normal'], + $instances['managed'] + ), + 'network_percent' => self::percentage( + $instances['network_normal'], + $instances['managed'] + ), + ], + 'attention_total' => $jobs['uncertain'] + $jobs['failed_24h'] + + $instances['network_attention'] + $receivables['overdue_count'] + + $tickets['open'], + ]; + } + + public static function unavailable(): array + { + $window = self::timeWindow(); + $trend = []; + foreach ($window['trend'] as $day) { + $trend[] = self::trendItem($day['start'], '0.00', 0, 0); + } + + return [ + 'available' => false, + 'generated_at' => self::formatTimestamp($window['now'], 'Y-m-d H:i:s'), + 'hosts' => ['total' => 0, 'enabled' => 0], + 'instances' => [ + 'managed' => 0, 'billable' => 0, 'customer_count' => 0, + 'service_normal' => 0, 'service_attention' => 0, + 'network_normal' => 0, 'network_attention' => 0, + 'expiring_7d' => 0, 'grace' => 0, + ], + 'jobs' => [ + 'queued' => 0, 'running' => 0, 'active' => 0, 'uncertain' => 0, + 'failed_24h' => 0, 'today_total' => 0, + 'today_succeeded' => 0, 'today_failed' => 0, + ], + 'revenue' => [ + 'today' => '0.00', 'yesterday' => '0.00', + 'month' => '0.00', 'today_count' => 0, + 'trend_total' => '0.00', 'trend_count' => 0, + 'trend' => $trend, + ], + 'receivables' => [ + 'count' => 0, 'amount' => '0.00', 'overdue_count' => 0, + 'overdue_amount' => '0.00', 'renewal_count' => 0, + ], + 'users' => ['total' => 0, 'enabled' => 0, 'new_today' => 0], + 'tickets' => ['open' => 0], + 'top_plans' => [], + 'health' => [ + 'hosts_percent' => 0, + 'service_percent' => 0, + 'network_percent' => 0, + ], + 'attention_total' => 0, + ]; + } + + private static function hosts(): array + { + $row = CloudHost::query()->selectRaw( + 'COUNT(*) AS total, ' + . 'SUM(CASE WHEN enabled = 1 THEN 1 ELSE 0 END) AS enabled_count' + )->first(); + + return [ + 'total' => (int) ($row?->total ?? 0), + 'enabled' => (int) ($row?->enabled_count ?? 0), + ]; + } + + private static function instances(int $now, int $weekEnd): array + { + $row = CloudInstance::where('status', '<>', 'deleted')->selectRaw( + "COUNT(*) AS managed, " + . "SUM(CASE WHEN service_status <> 'exempt' THEN 1 ELSE 0 END) AS billable, " + . 'COUNT(DISTINCT user_id) AS customer_count, ' + . "SUM(CASE WHEN status = 'active' AND (service_status = 'exempt' " + . "OR (service_status = 'active' AND expires_at IS NOT NULL " + . "AND expires_at > {$now})) THEN 1 ELSE 0 END) AS service_normal, " + . "SUM(CASE WHEN status = 'active' AND network_status = 'active' " + . 'THEN 1 ELSE 0 END) AS network_normal, ' + . "SUM(CASE WHEN status = 'active' AND service_status <> 'exempt' " + . "AND expires_at > {$now} AND expires_at <= {$weekEnd} THEN 1 ELSE 0 END) " + . 'AS expiring_7d, ' + . "SUM(CASE WHEN status = 'active' AND service_status <> 'exempt' " + . "AND expires_at IS NOT NULL AND expires_at <= {$now} " + . "AND service_status NOT IN ('purge_stopping','purge_stop_failed'," + . "'purge_deleting','purge_failed') THEN 1 ELSE 0 END) AS grace_count" + )->first(); + + $managed = (int) ($row?->managed ?? 0); + $serviceNormal = (int) ($row?->service_normal ?? 0); + $networkNormal = (int) ($row?->network_normal ?? 0); + + return [ + 'managed' => $managed, + 'billable' => (int) ($row?->billable ?? 0), + 'customer_count' => (int) ($row?->customer_count ?? 0), + 'service_normal' => $serviceNormal, + 'service_attention' => max(0, $managed - $serviceNormal), + 'network_normal' => $networkNormal, + 'network_attention' => max(0, $managed - $networkNormal), + 'expiring_7d' => (int) ($row?->expiring_7d ?? 0), + 'grace' => (int) ($row?->grace_count ?? 0), + ]; + } + + private static function jobs(int $now, int $todayStart, int $tomorrow): array + { + $dayAgo = $now - self::DAY; + $row = CloudJob::where('kind', 'create') + ->whereNotNull('order_id') + ->where(function ($query) use ($dayAgo) { + $query->whereIn('status', ['queued', 'running', 'uncertain']) + ->orWhere(function ($failed) use ($dayAgo) { + $failed->where('status', 'failed') + ->where('updated_at', '>=', $dayAgo); + }); + })->selectRaw( + "SUM(CASE WHEN status = 'queued' THEN 1 ELSE 0 END) AS queued_count, " + . "SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END) AS running_count, " + . "SUM(CASE WHEN status = 'uncertain' THEN 1 ELSE 0 END) AS uncertain_count, " + . "SUM(CASE WHEN status = 'failed' AND updated_at >= {$dayAgo} " + . 'THEN 1 ELSE 0 END) AS failed_24h' + )->first(); + + $today = CloudJob::where('kind', 'create') + ->whereNotNull('order_id') + ->where(function ($query) use ($todayStart, $tomorrow) { + $query->where(function ($created) use ($todayStart, $tomorrow) { + $created->where('created_at', '>=', $todayStart) + ->where('created_at', '<', $tomorrow); + })->orWhere(function ($completed) use ($todayStart, $tomorrow) { + $completed->whereIn('status', ['succeeded', 'failed']) + ->where('updated_at', '>=', $todayStart) + ->where('updated_at', '<', $tomorrow); + }); + }) + ->selectRaw( + "SUM(CASE WHEN created_at >= {$todayStart} AND created_at < {$tomorrow} " + . "THEN 1 ELSE 0 END) AS total, " + . "SUM(CASE WHEN status = 'succeeded' AND updated_at >= {$todayStart} " + . "AND updated_at < {$tomorrow} THEN 1 ELSE 0 END) AS succeeded, " + . "SUM(CASE WHEN status = 'failed' AND updated_at >= {$todayStart} " + . "AND updated_at < {$tomorrow} THEN 1 ELSE 0 END) AS failed" + )->first(); + + $queued = (int) ($row?->queued_count ?? 0); + $running = (int) ($row?->running_count ?? 0); + return [ + 'queued' => $queued, + 'running' => $running, + 'active' => $queued + $running, + 'uncertain' => (int) ($row?->uncertain_count ?? 0), + 'failed_24h' => (int) ($row?->failed_24h ?? 0), + 'today_total' => (int) ($today?->total ?? 0), + 'today_succeeded' => (int) ($today?->succeeded ?? 0), + 'today_failed' => (int) ($today?->failed ?? 0), + ]; + } + + private static function revenue(array $window): array + { + $monthStart = $window['month']; + $yesterdayStart = $window['yesterday']; + $todayStart = $window['today']; + $tomorrow = $window['tomorrow']; + $trendStart = $window['trend'][0]['start']; + $windowStart = min($monthStart, $trendStart, $yesterdayStart); + $select = [ + 'COALESCE(SUM(CASE WHEN paid_at >= ? AND paid_at < ? ' + . 'THEN amount ELSE 0 END), 0) AS today_amount', + 'SUM(CASE WHEN paid_at >= ? AND paid_at < ? THEN 1 ELSE 0 END) ' + . 'AS today_count', + 'COALESCE(SUM(CASE WHEN paid_at >= ? AND paid_at < ? ' + . 'THEN amount ELSE 0 END), 0) AS yesterday_amount', + 'COALESCE(SUM(CASE WHEN paid_at >= ? AND paid_at < ? ' + . 'THEN amount ELSE 0 END), 0) AS month_amount', + ]; + $bindings = [ + $todayStart, $tomorrow, + $todayStart, $tomorrow, + $yesterdayStart, $todayStart, + $monthStart, $tomorrow, + ]; + $days = []; + foreach ($window['trend'] as $index => $day) { + $start = $day['start']; + $end = $day['end']; + $select[] = "COALESCE(SUM(CASE WHEN paid_at >= ? AND paid_at < ? " + . "THEN amount ELSE 0 END), 0) AS day_{$index}_amount"; + $select[] = "SUM(CASE WHEN paid_at >= ? AND paid_at < ? " + . "THEN 1 ELSE 0 END) AS day_{$index}_count"; + array_push($bindings, $start, $end, $start, $end); + $days[] = $start; + } + + $row = CloudInvoice::where('status', 'paid') + ->whereNotNull('paid_at') + ->where('paid_at', '>=', $windowStart) + ->where('paid_at', '<', $tomorrow) + ->selectRaw(implode(', ', $select), $bindings) + ->first(); + + $rawTrend = []; + $maximum = 0.0; + $trendTotal = 0.0; + $trendCount = 0; + foreach ($days as $index => $start) { + $amount = self::money($row?->{'day_' . $index . '_amount'} ?? '0'); + $count = (int) ($row?->{'day_' . $index . '_count'} ?? 0); + $maximum = max($maximum, (float) $amount); + $trendTotal += (float) $amount; + $trendCount += $count; + $rawTrend[] = [$start, $amount, $count]; + } + $trend = array_map(static function (array $item) use ($maximum): array { + $percent = $maximum > 0 ? (int) round((float) $item[1] / $maximum * 100) : 0; + return self::trendItem($item[0], $item[1], $item[2], $percent); + }, $rawTrend); + + return [ + 'today' => self::money($row?->today_amount ?? '0'), + 'yesterday' => self::money($row?->yesterday_amount ?? '0'), + 'month' => self::money($row?->month_amount ?? '0'), + 'today_count' => (int) ($row?->today_count ?? 0), + 'trend_total' => self::money($trendTotal), + 'trend_count' => $trendCount, + 'trend' => $trend, + ]; + } + + private static function receivables(int $now): array + { + $liveTarget = "(purpose <> 'renewal' OR EXISTS (" + . 'SELECT 1 FROM cloud_instances AS overview_instance ' + . 'WHERE overview_instance.id = cloud_invoices.instance_id ' + . 'AND overview_instance.user_id = cloud_invoices.user_id ' + . "AND overview_instance.status <> 'deleted'))"; + $row = CloudInvoice::whereIn('status', ['open', 'overdue']) + ->whereRaw($liveTarget) + ->selectRaw( + 'COUNT(*) AS invoice_count, COALESCE(SUM(amount), 0) AS amount, ' + . "SUM(CASE WHEN status = 'overdue' OR due_at <= {$now} " + . 'THEN 1 ELSE 0 END) AS overdue_count, ' + . "COALESCE(SUM(CASE WHEN status = 'overdue' OR due_at <= {$now} " + . 'THEN amount ELSE 0 END), 0) AS overdue_amount, ' + . "SUM(CASE WHEN purpose = 'renewal' THEN 1 ELSE 0 END) AS renewal_count" + )->first(); + + return [ + 'count' => (int) ($row?->invoice_count ?? 0), + 'amount' => self::money($row?->amount ?? '0'), + 'overdue_count' => (int) ($row?->overdue_count ?? 0), + 'overdue_amount' => self::money($row?->overdue_amount ?? '0'), + 'renewal_count' => (int) ($row?->renewal_count ?? 0), + ]; + } + + private static function users(int $todayStart, int $tomorrow): array + { + $from = self::formatTimestamp($todayStart, 'Y-m-d H:i:s'); + $to = self::formatTimestamp($tomorrow, 'Y-m-d H:i:s'); + $row = User::where('is_admin', 0)->selectRaw( + 'COUNT(*) AS total, ' + . 'SUM(CASE WHEN enable = 1 THEN 1 ELSE 0 END) AS enabled_count, ' + . 'SUM(CASE WHEN reg_date >= ? AND reg_date < ? THEN 1 ELSE 0 END) ' + . 'AS new_today', + [$from, $to] + )->first(); + + return [ + 'total' => (int) ($row?->total ?? 0), + 'enabled' => (int) ($row?->enabled_count ?? 0), + 'new_today' => (int) ($row?->new_today ?? 0), + ]; + } + + private static function tickets(): array + { + return [ + 'open' => (int) Ticket::where('rootid', 0)->where('status', 1)->count(), + ]; + } + + private static function topPlans(int $monthStart, int $tomorrow): array + { + $rows = CloudInvoice::where('cloud_invoices.status', 'paid') + ->where('cloud_invoices.purpose', 'provision') + ->where('cloud_invoices.paid_at', '>=', $monthStart) + ->where('cloud_invoices.paid_at', '<', $tomorrow) + ->leftJoin('shop', 'shop.id', '=', 'cloud_invoices.plan_id') + ->groupBy('cloud_invoices.plan_id', 'shop.name') + ->orderByDesc('invoice_count') + ->orderByDesc('paid_amount') + ->limit(5) + ->selectRaw( + 'cloud_invoices.plan_id, shop.name, COUNT(*) AS invoice_count, ' + . 'COALESCE(SUM(cloud_invoices.amount), 0) AS paid_amount' + )->get(); + + return array_map(static function ($row): array { + $planId = $row->plan_id === null ? '' : (string) $row->plan_id; + $name = trim((string) ($row->name ?? '')); + if ($name === '') { + $name = $planId === '' ? '未记录套餐' : '已下架套餐 #' . $planId; + } + return [ + 'name' => $name, + 'count' => (int) ($row->invoice_count ?? 0), + 'amount' => self::money($row->paid_amount ?? '0'), + ]; + }, $rows->all()); + } + + private static function trendItem(int $start, string $amount, int $count, + int $percent): array + { + $weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; + return [ + 'date' => self::formatTimestamp($start, 'Y-m-d'), + 'label' => self::formatTimestamp($start, 'm/d'), + 'weekday' => $weekdays[(int) self::formatTimestamp($start, 'w')], + 'amount' => $amount, + 'count' => $count, + 'percent' => max(0, min(100, $percent)), + ]; + } + + private static function money($value): string + { + return number_format((float) $value, 2, '.', ''); + } + + private static function percentage(int $value, int $total): float + { + if ($total <= 0) { + return 0.0; + } + return round(min(100, max(0, $value / $total * 100)), 1); + } + + /** Calendar boundaries are derived in the configured timezone, including DST days. */ + private static function timeWindow(): array + { + $timezone = self::timezone(); + $now = new DateTimeImmutable('now', $timezone); + $today = $now->setTime(0, 0, 0); + $trend = []; + for ($offset = self::TREND_DAYS - 1; $offset >= 0; $offset--) { + $start = $today->modify('-' . $offset . ' days'); + $trend[] = [ + 'start' => $start->getTimestamp(), + 'end' => $start->modify('+1 day')->getTimestamp(), + ]; + } + + return [ + 'now' => $now->getTimestamp(), + 'today' => $today->getTimestamp(), + 'tomorrow' => $today->modify('+1 day')->getTimestamp(), + 'yesterday' => $today->modify('-1 day')->getTimestamp(), + 'month' => $today->modify('first day of this month')->getTimestamp(), + 'week_end' => $now->modify('+7 days')->getTimestamp(), + 'trend' => $trend, + ]; + } + + private static function timezone(): DateTimeZone + { + try { + return new DateTimeZone( + (string) Config::get('timeZone', date_default_timezone_get()) + ); + } catch (\Throwable $exception) { + return new DateTimeZone(date_default_timezone_get() ?: 'UTC'); + } + } + + private static function formatTimestamp(int $timestamp, string $format): string + { + return (new DateTimeImmutable('@' . $timestamp)) + ->setTimezone(self::timezone()) + ->format($format); + } +} diff --git a/web/public/cloud/admin-overview.css b/web/public/cloud/admin-overview.css new file mode 100644 index 00000000..5f09389c --- /dev/null +++ b/web/public/cloud/admin-overview.css @@ -0,0 +1,961 @@ +.admin-overview { + --vo-ink: #10243d; + --vo-muted: #5c6f83; + --vo-soft: #f5f8fb; + --vo-line: #dce5ee; + --vo-brand: #0a8f78; + --vo-brand-soft: #e7f7f2; + --vo-warning: #a96108; + --vo-warning-soft: #fff4df; + --vo-danger: #bd3847; + --vo-danger-soft: #fdecef; + display: grid; + gap: 16px; + width: 100%; + max-width: 1540px; + min-width: 0; + margin-inline: auto; + padding: 20px 0 32px; + color: var(--vo-ink); +} + +.admin-overview *, +.admin-overview *::before, +.admin-overview *::after { + box-sizing: border-box; +} + +.vo-page-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 24px; + padding: 4px 0 6px; +} + +.vo-page-head > div:first-child { + min-width: 0; +} + +.vo-page-head h1 { + margin: 0; + color: var(--vo-ink); + font-size: clamp(25px, 2.2vw, 32px); + font-weight: 850; + letter-spacing: -0.035em; + line-height: 1.15; +} + +.vo-page-head p { + max-width: 680px; + margin: 8px 0 0; + color: var(--vo-muted); + font-size: 14px; + line-height: 1.6; +} + +.vo-page-actions { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + flex: 0 0 auto; +} + +.vo-snapshot { + min-height: 44px; + display: inline-flex; + align-items: center; + gap: 8px; + padding: 0 14px; + border: 1px solid var(--vo-line); + border-radius: 8px; + color: #52677d; + background: #fff; + font-size: 12px; + font-weight: 750; + white-space: nowrap; +} + +.vo-snapshot i { + color: var(--vo-brand); + font-size: 18px; +} + +.vo-snapshot.is-error { + border-color: #f1cbd0; + color: #8f2b38; + background: #fff8f9; +} + +.vo-snapshot.is-error i { + color: var(--vo-danger); +} + +.vo-refresh { + min-height: 44px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; + border-color: var(--vo-line); + color: #314a64; + font-weight: 750; +} + +.vo-alert { + min-height: 48px; + display: flex; + align-items: center; + gap: 10px; + padding: 12px 14px; + border: 1px solid #f0c7cd; + border-radius: 8px; + color: #8d2936; + background: #fff7f8; + font-size: 14px; + font-weight: 700; +} + +.vo-alert i { + flex: 0 0 auto; + font-size: 20px; +} + +.vo-kpi-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 12px; +} + +.vo-kpi { + position: relative; + min-width: 0; + min-height: 184px; + display: flex; + flex-direction: column; + padding: 19px 20px 16px; + overflow: hidden; + border: 1px solid var(--vo-line); + border-radius: 8px; + background: #fff; +} + +.vo-kpi::before { + position: absolute; + inset: 0 0 auto; + height: 3px; + content: ""; + background: var(--vo-brand); +} + +.vo-kpi.has-warning::before { + background: #dfa145; +} + +.vo-kpi-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + color: var(--vo-muted); + font-size: 13px; + font-weight: 800; +} + +.vo-kpi-head h2 { + margin: 0; + color: inherit; + font: inherit; + letter-spacing: inherit; +} + +.vo-kpi-head i { + width: 38px; + height: 38px; + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + border-radius: 8px; + color: #087460; + background: var(--vo-brand-soft); + font-size: 21px; +} + +.vo-kpi.has-warning .vo-kpi-head i { + color: var(--vo-warning); + background: var(--vo-warning-soft); +} + +.vo-kpi > strong { + display: block; + margin-top: 10px; + color: var(--vo-ink); + font-size: clamp(29px, 2.4vw, 36px); + font-weight: 850; + font-variant-numeric: tabular-nums; + letter-spacing: -0.04em; + line-height: 1.08; +} + +.vo-kpi > strong small { + margin-right: 2px; + color: #476078; + font-size: 17px; + font-weight: 800; +} + +.vo-kpi > p { + min-height: 39px; + margin: 8px 0 10px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 650; + line-height: 1.55; +} + +.vo-kpi > a { + min-height: 44px; + display: inline-flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin: auto -8px -8px; + padding: 0 8px; + border-radius: 6px; + color: #087460; + font-size: 13px; + font-weight: 800; + text-decoration: none; +} + +.vo-kpi > a i { + font-size: 19px; +} + +.vo-primary-grid, +.vo-secondary-grid { + display: grid; + gap: 16px; + min-width: 0; +} + +.vo-primary-grid { + grid-template-columns: minmax(0, 1.7fr) minmax(320px, 0.8fr); +} + +.vo-secondary-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.vo-panel { + min-width: 0; + padding: 20px; + border: 1px solid var(--vo-line); + border-radius: 8px; + background: #fff; +} + +.vo-panel-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 18px; +} + +.vo-panel-head > div:first-child { + min-width: 0; +} + +.vo-panel-head h2 { + margin: 0; + color: var(--vo-ink); + font-size: 18px; + font-weight: 850; + letter-spacing: -0.02em; +} + +.vo-panel-head p { + margin: 5px 0 0; + color: var(--vo-muted); + font-size: 12px; + font-weight: 600; + line-height: 1.55; +} + +.vo-panel-summary { + flex: 0 0 auto; + text-align: right; +} + +.vo-panel-summary strong { + display: block; + color: var(--vo-ink); + font-size: 21px; + font-weight: 850; + font-variant-numeric: tabular-nums; +} + +.vo-panel-summary span { + display: block; + margin-top: 2px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 700; +} + +.vo-trend { + display: grid; + gap: 12px; +} + +.vo-trend-row { + display: grid; + grid-template-columns: 74px minmax(90px, 1fr) 112px; + align-items: center; + gap: 14px; + min-width: 0; +} + +.vo-trend-date, +.vo-trend-value { + min-width: 0; +} + +.vo-trend-date strong, +.vo-trend-value strong { + display: block; + color: #27415c; + font-size: 12px; + font-weight: 800; + line-height: 1.25; +} + +.vo-trend-date span, +.vo-trend-value span { + display: block; + margin-top: 2px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 650; + line-height: 1.25; +} + +.vo-trend-value { + overflow-wrap: anywhere; + text-align: right; + font-variant-numeric: tabular-nums; +} + +.vo-trend-track { + height: 9px; + overflow: hidden; + border-radius: 999px; + background: #eaf0f5; +} + +.vo-trend-track span { + width: calc(var(--value) * 1%); + min-width: calc(min(var(--value), 1) * 5px); + height: 100%; + display: block; + border-radius: inherit; + background: #27a98d; +} + +.vo-panel-foot { + min-height: 44px; + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 14px; + margin-top: 12px; + padding-top: 12px; + border-top: 1px solid #e8eef4; + color: var(--vo-muted); + font-size: 12px; + font-weight: 700; +} + +.vo-panel-foot a, +.vo-head-link { + min-height: 44px; + display: inline-flex; + align-items: center; + justify-content: center; + padding: 0 6px; + border-radius: 6px; + color: #087460; + font-size: 12px; + font-weight: 800; + text-decoration: none; +} + +.vo-attention-count { + min-width: 38px; + height: 38px; + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + border-radius: 999px; + color: #547086; + background: #edf2f6; + font-size: 14px; + font-weight: 850; + font-variant-numeric: tabular-nums; +} + +.vo-attention-count.has-items { + color: #9a3420; + background: #ffeadf; +} + +.vo-attention-list { + display: grid; + gap: 7px; +} + +.vo-attention-list a { + min-height: 66px; + display: grid; + grid-template-columns: 38px minmax(0, 1fr) auto; + align-items: center; + gap: 11px; + padding: 9px 10px; + border: 1px solid transparent; + border-radius: 7px; + color: inherit; + background: #f8fafc; + text-decoration: none; +} + +.vo-attention-list > a > i { + width: 38px; + height: 38px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 7px; + color: #36708e; + background: #e8f2f7; + font-size: 20px; +} + +.vo-attention-list > a > i.is-warning { + color: var(--vo-warning); + background: var(--vo-warning-soft); +} + +.vo-attention-list > a > i.is-danger { + color: var(--vo-danger); + background: var(--vo-danger-soft); +} + +.vo-attention-list span, +.vo-shortcuts span { + min-width: 0; +} + +.vo-attention-list strong, +.vo-attention-list small { + display: block; +} + +.vo-attention-list strong { + color: #213b55; + font-size: 12px; + font-weight: 800; +} + +.vo-attention-list small { + margin-top: 2px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 600; + line-height: 1.35; +} + +.vo-attention-list em { + min-width: 29px; + color: var(--vo-ink); + font-size: 15px; + font-style: normal; + font-weight: 850; + font-variant-numeric: tabular-nums; + text-align: right; +} + +.vo-health-list { + display: grid; + gap: 19px; +} + +.vo-health-item > div { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + margin-bottom: 8px; + color: #536b82; + font-size: 12px; + font-weight: 750; +} + +.vo-health-item strong { + color: var(--vo-ink); + font-size: 13px; + font-weight: 850; + font-variant-numeric: tabular-nums; +} + +.vo-health-track { + height: 8px; + display: block; + overflow: hidden; + border-radius: 999px; + background: #e9eff4; +} + +.vo-health-track i { + width: calc(var(--value) * 1%); + height: 100%; + display: block; + border-radius: inherit; + background: #28a98d; +} + +.vo-definition { + display: grid; + grid-template-columns: 24px minmax(0, 1fr); + gap: 8px; + margin-top: 20px; + padding: 11px 12px; + border-radius: 7px; + color: #526b80; + background: #f1f6f8; + font-size: 12px; + font-weight: 650; + line-height: 1.5; +} + +.vo-definition i { + color: #25866f; + font-size: 18px; +} + +.vo-flow-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.vo-flow-grid > div { + min-width: 0; + padding: 15px 16px; + border: 1px solid #e5ecf2; + border-radius: 7px; + background: #f8fafc; +} + +.vo-flow-grid span, +.vo-flow-grid strong, +.vo-flow-grid small { + display: block; +} + +.vo-flow-grid span { + color: var(--vo-muted); + font-size: 12px; + font-weight: 750; +} + +.vo-flow-grid strong { + margin-top: 5px; + color: var(--vo-ink); + font-size: 25px; + font-weight: 850; + font-variant-numeric: tabular-nums; + letter-spacing: -0.03em; +} + +.vo-flow-grid small { + margin-top: 5px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 650; + line-height: 1.4; +} + +.vo-plan-list { + display: grid; +} + +.vo-plan-row { + min-height: 48px; + display: grid; + grid-template-columns: 30px minmax(0, 1fr) 58px 92px; + align-items: center; + gap: 10px; + border-bottom: 1px solid #e8eef4; + color: var(--vo-muted); + font-size: 12px; + font-weight: 700; +} + +.vo-plan-row:last-child { + border-bottom: 0; +} + +.vo-plan-rank { + width: 26px; + height: 26px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 6px; + color: #087460; + background: var(--vo-brand-soft); + font-size: 12px; + font-weight: 850; +} + +.vo-plan-row strong { + min-width: 0; + color: #263f58; + font-size: 13px; + font-weight: 800; + line-height: 1.4; + overflow-wrap: anywhere; +} + +.vo-plan-count, +.vo-plan-amount { + min-width: 0; +} + +.vo-plan-row em { + color: var(--vo-ink); + font-style: normal; + font-weight: 850; + font-variant-numeric: tabular-nums; + text-align: right; + overflow-wrap: anywhere; +} + +.vo-empty { + min-height: 154px; + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + gap: 8px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 700; + text-align: center; +} + +.vo-empty i { + color: #9eb0bf; + font-size: 28px; +} + +.vo-shortcuts { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.vo-shortcuts a { + min-height: 72px; + display: grid; + grid-template-columns: 38px minmax(0, 1fr); + align-items: center; + gap: 11px; + padding: 12px; + border: 1px solid #e3eaf1; + border-radius: 7px; + color: inherit; + background: #f8fafc; + text-decoration: none; +} + +.vo-shortcuts > a > i { + width: 38px; + height: 38px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 7px; + color: #087460; + background: var(--vo-brand-soft); + font-size: 20px; +} + +.vo-shortcuts strong, +.vo-shortcuts small { + display: block; +} + +.vo-shortcuts strong { + color: #253e57; + font-size: 12px; + font-weight: 800; +} + +.vo-shortcuts small { + margin-top: 3px; + color: var(--vo-muted); + font-size: 12px; + font-weight: 650; + line-height: 1.35; +} + +.vo-method-note { + min-width: 0; + display: grid; + grid-template-columns: 34px minmax(0, 1fr); + gap: 11px; + padding: 14px 16px; + border: 1px solid #d9e7e3; + border-radius: 8px; + color: #49657a; + background: #f2f8f6; +} + +.vo-method-note > i { + width: 34px; + height: 34px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 7px; + color: #087460; + background: #dff2ec; + font-size: 19px; +} + +.vo-method-note p, +.vo-method-note strong, +.vo-method-note span { + display: block; + margin: 0; +} + +.vo-method-note strong { + color: #274c46; + font-size: 12px; + font-weight: 850; +} + +.vo-method-note span { + margin-top: 3px; + font-size: 12px; + font-weight: 650; + line-height: 1.55; +} + +.admin-overview a { + transition: border-color 160ms ease, background-color 160ms ease, color 160ms ease; +} + +.admin-overview a:hover { + color: #056955; +} + +.vo-kpi > a:hover, +.vo-panel-foot a:hover, +.vo-head-link:hover { + background: #eff8f5; +} + +.vo-attention-list a:hover, +.vo-shortcuts a:hover { + border-color: #b9ddd3; + background: #f1f8f6; +} + +.vo-attention-list a:active, +.vo-shortcuts a:active, +.vo-kpi > a:active, +.vo-panel-foot a:active, +.vo-head-link:active { + background: #e5f3ef; +} + +.admin-overview a:focus-visible { + outline: 2px solid #0a7865; + outline-offset: 2px; +} + +@media (max-width: 1260px) { + .vo-kpi-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .vo-primary-grid { + grid-template-columns: minmax(0, 1.45fr) minmax(300px, 0.8fr); + } +} + +@media (max-width: 991px) { + .admin-overview { + padding-top: 16px; + } + + .vo-primary-grid, + .vo-secondary-grid { + grid-template-columns: 1fr; + } +} + +@media (max-width: 720px) { + .vo-page-head { + align-items: stretch; + flex-direction: column; + gap: 14px; + } + + .vo-page-actions { + width: 100%; + align-items: stretch; + } + + .vo-snapshot { + min-width: 0; + flex: 1 1 auto; + white-space: normal; + } + + .vo-refresh { + flex: 0 0 auto; + } + + .vo-kpi-grid { + grid-template-columns: 1fr; + } + + .vo-kpi { + min-height: 0; + } + + .vo-panel-head { + gap: 10px; + } + + .vo-trend-row { + grid-template-columns: 60px minmax(52px, 1fr) minmax(84px, auto); + gap: 9px; + } + + .vo-trend-value strong { + font-size: 12px; + } + + .vo-flow-grid, + .vo-shortcuts { + grid-template-columns: 1fr 1fr; + } +} + +@media (max-width: 480px) { + .admin-overview { + gap: 12px; + } + + .vo-page-actions { + flex-direction: column; + } + + .vo-snapshot, + .vo-refresh { + width: 100%; + justify-content: center; + } + + .vo-kpi, + .vo-panel { + padding: 16px; + } + + .vo-panel-head { + align-items: flex-start; + flex-direction: column; + } + + .vo-panel-summary { + text-align: left; + } + + .vo-attention-panel .vo-panel-head { + flex-direction: row; + } + + .vo-trend-row { + grid-template-columns: 52px minmax(42px, 1fr) minmax(78px, 96px); + gap: 8px; + } + + .vo-trend-date strong { + font-size: 12px; + } + + .vo-panel-foot { + align-items: flex-start; + flex-direction: column; + gap: 0; + } + + .vo-attention-list a { + grid-template-columns: 34px minmax(0, 1fr) auto; + padding-inline: 7px; + } + + .vo-attention-list > a > i { + width: 34px; + height: 34px; + } + + .vo-flow-grid, + .vo-shortcuts { + grid-template-columns: 1fr; + } + + .vo-plan-row { + grid-template-columns: 28px minmax(0, 1fr) minmax(72px, auto); + grid-template-rows: auto auto; + padding: 8px 0; + } + + .vo-plan-rank { + grid-column: 1; + grid-row: 1 / 3; + } + + .vo-plan-row strong { + grid-column: 2; + grid-row: 1; + } + + .vo-plan-count { + grid-column: 2; + grid-row: 2; + } + + .vo-plan-amount { + grid-column: 3; + grid-row: 1 / 3; + } +} + +@media (prefers-reduced-motion: reduce) { + .admin-overview *, + .admin-overview *::before, + .admin-overview *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + } +} diff --git a/web/resources/views/venix/admin/index.tpl b/web/resources/views/venix/admin/index.tpl index 1cf723b5..baf3600d 100644 --- a/web/resources/views/venix/admin/index.tpl +++ b/web/resources/views/venix/admin/index.tpl @@ -1,5 +1,238 @@ -{assign var=admin_title value='管理概览'}{assign var=admin_active value='index'}{include file='admin/static_header.tpl'} -

管理概览

管理账户、云资源、商品、支付、公告和工单。

-

注册账户

{$sts->getTotalUser()}

用户列表

商品与账单

云服务器套餐

商品管理 · 账单系统

服务支持

工单系统

工单与 Telegram 通知
-
宿主机与虚拟机

维护宿主机连接配置,并查看已纳管的虚拟机资源。

管理宿主机
+{assign var=admin_title value='系统概览'} +{assign var=admin_active value='index'} +{assign var=admin_extra_css_href value='/cloud/admin-overview.css'} +{include file='admin/static_header.tpl'} + +
+
+
+

系统概览

+

集中查看实例交付、账单实收和需要人工介入的运营事项。

+
+
+ + + {if $overview.available}数据库快照{else}快照不可用{/if} · {$overview.generated_at|escape:'html'} + + + 刷新数据 + +
+
+ + {if $overview_error != ''} + + {/if} + +
+
+
+

在管实例

+ +
+ {$overview.instances.managed} +

服务状态正常 {$overview.instances.service_normal} 台 · 覆盖 {$overview.instances.customer_count} 位客户

+ 查看实例目录 +
+ +
+
+

本月有效实收

+ +
+ ${$overview.revenue.month|escape:'html'} +

今日 ${$overview.revenue.today|escape:'html'} · {$overview.revenue.today_count} 笔当前有效账单

+ 进入账单系统 +
+ +
+
+

开通中任务

+ +
+ {$overview.jobs.active} +

待核对开通 {$overview.jobs.uncertain} 项 · 近 24 小时开通失败 {$overview.jobs.failed_24h} 项

+ 查看开通任务 +
+ +
+
+

7 天内到期

+ +
+ {$overview.instances.expiring_7d} +

已到期或宽限期 {$overview.instances.grace} 台 · 待收续费账单 {$overview.receivables.renewal_count} 张

+ 处理实例续期 +
+
+ +
+
+
+
+

近 7 日有效实收

+

只统计当前仍为已支付状态的账单,按实际支付时间归入日期。

+
+
+ ${$overview.revenue.trend_total|escape:'html'} + {$overview.revenue.trend_count} 笔账单 +
+
+
+ {foreach $overview.revenue.trend as $day} +
+
+ {$day.weekday|escape:'html'} + {$day.label|escape:'html'} +
+ +
+ ${$day.amount|escape:'html'} + {$day.count} 笔 +
+
+ {/foreach} +
+ +
+ +
+
+
+

需要处理

+

优先展示会影响交付、网络或回款的事项。

+
+ {$overview.attention_total} +
+ +
+
+ +
+
+
+
+

资源状态

+

基于业务库中的配置与生命周期状态,不推断真实开关机状态。

+
+ 宿主机设置 +
+
+
+
已启用宿主机配置{$overview.hosts.enabled} / {$overview.hosts.total}
+ +
+
+
实例服务状态正常{$overview.instances.service_normal} / {$overview.instances.managed}
+ +
+
+
实例网络状态正常{$overview.instances.network_normal} / {$overview.instances.managed}
+ +
+
+
+ + “已启用”仅表示宿主机配置允许调度;真实连通性仍以宿主机管理页和任务结果为准。 +
+
+ +
+
+
+

今日业务流转

+

注册、支付、实例交付和待收账单分开统计。

+
+ 查看账单 +
+
+
新增客户{$overview.users.new_today}客户总数 {$overview.users.total}
+
完成开通{$overview.jobs.today_succeeded}今日创建任务 {$overview.jobs.today_total}
+
有效支付{$overview.revenue.today_count}${$overview.revenue.today|escape:'html'}
+
待收账单{$overview.receivables.count}${$overview.receivables.amount|escape:'html'}
+
+
+
+ +
+
+
+
+

本月开通套餐

+

按当前有效的已支付开通账单排序。

+
+ 套餐管理 +
+
+ {foreach $overview.top_plans as $plan} +
+ {$plan@iteration} + {$plan.name|escape:'html'} + {$plan.count} 笔 + ${$plan.amount|escape:'html'} +
+ {foreachelse} +
+ + 本月暂时没有有效的已支付开通账单 +
+ {/foreach} +
+
+ + +
+ + +
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/static_header.tpl b/web/resources/views/venix/admin/static_header.tpl index 240e73a5..34f4f1a0 100644 --- a/web/resources/views/venix/admin/static_header.tpl +++ b/web/resources/views/venix/admin/static_header.tpl @@ -10,6 +10,7 @@ + {if isset($admin_extra_css_href)}{/if} {if isset($admin_extra_css)}{$admin_extra_css}{/if} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 9da4e88b..273c0ba8 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -1,5 +1,8 @@ -- Fresh-install cloud business tables. PHP is the sole writer of these records. +ALTER TABLE ticket ADD INDEX IF NOT EXISTS + ticket_overview_root_status (rootid, status); + CREATE TABLE IF NOT EXISTS cloud_hosts ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(80) NOT NULL, @@ -154,7 +157,8 @@ CREATE TABLE IF NOT EXISTS cloud_invoices ( KEY cloud_invoice_period (instance_id, renews_expires_at, status), UNIQUE KEY uniq_cloud_invoice_renewal (renewal_id), KEY cloud_invoice_owner (user_id, status, due_at), - KEY cloud_invoice_due (status, due_at, id) + KEY cloud_invoice_due (status, due_at, id), + KEY cloud_invoice_overview_paid (status, paid_at, purpose, plan_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Releases created before void invoices became replaceable used a unique -- period key. Keep void rows as an audit trail while permitting one corrected @@ -182,6 +186,8 @@ ALTER TABLE cloud_invoices ADD INDEX IF NOT EXISTS cloud_invoice_admin_user (user_id, created_at, id); ALTER TABLE cloud_invoices ADD INDEX IF NOT EXISTS cloud_invoice_admin_method (paid_via, created_at, id); +ALTER TABLE cloud_invoices ADD INDEX IF NOT EXISTS + cloud_invoice_overview_paid (status, paid_at, purpose, plan_id); ALTER TABLE cloud_orders ADD INDEX IF NOT EXISTS cloud_order_admin_created (created_at, id); ALTER TABLE cloud_orders ADD INDEX IF NOT EXISTS @@ -250,8 +256,14 @@ CREATE TABLE IF NOT EXISTS cloud_jobs ( UNIQUE KEY uniq_cloud_provision_order (order_id), KEY cloud_job_poll (status, available_at, lease_until), KEY cloud_job_instance_state (instance_id, status, id), + KEY cloud_job_overview_status_updated (status, updated_at), + KEY cloud_job_overview_kind_created (kind, created_at), KEY cloud_job_owner (user_id, id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +ALTER TABLE cloud_jobs ADD INDEX IF NOT EXISTS + cloud_job_overview_status_updated (status, updated_at); +ALTER TABLE cloud_jobs ADD INDEX IF NOT EXISTS + cloud_job_overview_kind_created (kind, created_at); CREATE TABLE IF NOT EXISTS cloud_ssh_keys ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, diff --git a/web/sql/ss.sql b/web/sql/ss.sql index 0c2e6378..edd83ef8 100644 --- a/web/sql/ss.sql +++ b/web/sql/ss.sql @@ -439,7 +439,8 @@ ALTER TABLE `ss_password_reset` ADD PRIMARY KEY (`id`); ALTER TABLE `ticket` - ADD PRIMARY KEY (`id`); + ADD PRIMARY KEY (`id`), + ADD KEY `ticket_overview_root_status` (`rootid`,`status`); ALTER TABLE `user` ADD PRIMARY KEY (`id`), diff --git a/web/tests/AdminOverviewContractTest.php b/web/tests/AdminOverviewContractTest.php new file mode 100644 index 00000000..ad995cb9 --- /dev/null +++ b/web/tests/AdminOverviewContractTest.php @@ -0,0 +1,93 @@ + \$overviewError"), + 'Administrator landing page must render a database snapshot with a safe fallback.'); + +$assert(str_contains($service, 'CloudInvoice') + && str_contains($service, 'CloudInstance') + && str_contains($service, 'CloudJob') + && str_contains($service, 'CloudHost') + && !str_contains($service, 'App\\Models\\Code') + && !str_contains($service, 'Bought') + && !str_contains($service, 'CloudEngineClient') + && !str_contains($service, 'CloudEngineSession'), + 'Overview metrics must use cloud business tables without legacy ledgers or engine calls.'); + +$assert(str_contains($service, "where('status', 'paid')") + && str_contains($service, "whereNotNull('paid_at')") + && str_contains($service, "where('status', '<>', 'deleted')") + && str_contains($service, "where('kind', 'create')") + && str_contains($service, "whereNotNull('order_id')") + && str_contains($service, "whereIn('status', ['queued', 'running', 'uncertain'])") + && str_contains($service, "status = 'failed' AND updated_at") + && str_contains($service, "status = 'active' AND (service_status = 'exempt'") + && str_contains($service, 'updated_at >= {$todayStart}') + && str_contains($service, "modify('+1 day')"), + 'Financial, instance and job overview boundaries are incomplete.'); + +$assert(str_contains($service, "foreach (\$window['trend'] as \$index => \$day)") + && substr_count($service, 'CloudInvoice::where') <= 3, + 'Revenue trend must use bounded aggregate queries rather than one query per day.'); + +$assert(str_contains($schema, 'cloud_invoice_overview_paid (status, paid_at, purpose, plan_id)') + && str_contains($schema, 'cloud_job_overview_status_updated (status, updated_at)') + && str_contains($schema, 'cloud_job_overview_kind_created (kind, created_at)') + && str_contains($schema, 'ticket_overview_root_status (rootid, status)') + && str_contains($baseSchema, '`ticket_overview_root_status` (`rootid`,`status`)'), + 'Overview range queries must have bounded operational indexes.'); + +$assert(str_contains($template, '
') + && str_contains($template, "admin_extra_css_href value='/cloud/admin-overview.css'") + && str_contains($template, '数据库快照') + && str_contains($template, '已启用宿主机配置') + && str_contains($template, '不推断真实开关机状态') + && str_contains($template, '退款后会从历史有效实收中移除') + && substr_count($template, '
span:nth-of-type(2)') + && !str_contains($styles, 'min-width: 1120px'), + 'Overview responsive, touch and keyboard accessibility contracts are incomplete.'); + +echo 'Administrator operational overview contracts passed.' . PHP_EOL; diff --git a/web/tests/AdminOverviewServiceTest.php b/web/tests/AdminOverviewServiceTest.php new file mode 100644 index 00000000..51328590 --- /dev/null +++ b/web/tests/AdminOverviewServiceTest.php @@ -0,0 +1,183 @@ + 'Asia/Shanghai']; + +$capsule = new Capsule(); +$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->getConnection('default')->getSchemaBuilder(); + +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->boolean('enabled'); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->string('status'); + $table->string('service_status'); + $table->string('network_status'); + $table->integer('expires_at')->nullable(); +}); +$schema->create('cloud_jobs', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('order_id')->nullable(); + $table->string('kind'); + $table->string('status'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_invoices', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('purpose'); + $table->integer('instance_id')->nullable(); + $table->integer('user_id'); + $table->integer('plan_id')->nullable(); + $table->integer('due_at'); + $table->string('amount'); + $table->string('status'); + $table->integer('paid_at')->nullable(); +}); +$schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); + $table->boolean('is_admin'); + $table->boolean('enable'); + $table->dateTime('reg_date'); +}); +$schema->create('ticket', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('rootid'); + $table->integer('status'); +}); +$schema->create('shop', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('name'); +}); + +$now = time(); +$today = strtotime('today', $now); +$month = strtotime(date('Y-m-01 00:00:00', $now)); +$yesterday = $today - 86400; + +Capsule::table('cloud_hosts')->insert([ + ['id' => 1, 'enabled' => 1], + ['id' => 2, 'enabled' => 0], +]); +Capsule::table('cloud_instances')->insert([ + ['id' => 1, 'user_id' => 1, 'status' => 'active', 'service_status' => 'active', + 'network_status' => 'active', 'expires_at' => $now + 3 * 86400], + ['id' => 2, 'user_id' => 2, 'status' => 'active', 'service_status' => 'exempt', + 'network_status' => 'active', 'expires_at' => null], + ['id' => 3, 'user_id' => 1, 'status' => 'active', 'service_status' => 'active', + 'network_status' => 'blocked_traffic', 'expires_at' => $now - 3600], + ['id' => 4, 'user_id' => 2, 'status' => 'deleted', 'service_status' => 'active', + 'network_status' => 'active', 'expires_at' => $now + 86400], + ['id' => 5, 'user_id' => 2, 'status' => 'delete_failed', 'service_status' => 'purge_failed', + 'network_status' => 'active', 'expires_at' => $now - 3600], +]); +Capsule::table('cloud_jobs')->insert([ + ['order_id' => 1, 'kind' => 'create', 'status' => 'queued', + 'created_at' => $today + 10, 'updated_at' => $now], + ['order_id' => null, 'kind' => 'reinstall', 'status' => 'running', + 'created_at' => $today + 20, 'updated_at' => $now], + ['order_id' => 2, 'kind' => 'create', 'status' => 'uncertain', + 'created_at' => $today + 30, 'updated_at' => $now], + ['order_id' => 3, 'kind' => 'create', 'status' => 'failed', + 'created_at' => $today + 40, 'updated_at' => $now], + ['order_id' => 4, 'kind' => 'create', 'status' => 'succeeded', + 'created_at' => $today + 50, 'updated_at' => $now], + ['order_id' => 5, 'kind' => 'create', 'status' => 'succeeded', 'created_at' => $today - 3600, + 'updated_at' => $now], + ['order_id' => 6, 'kind' => 'create', 'status' => 'failed', 'created_at' => $today - 172800, + 'updated_at' => $now - 90000], +]); +Capsule::table('shop')->insert(['id' => 1, 'name' => '2c4g']); +Capsule::table('cloud_invoices')->insert([ + ['purpose' => 'provision', 'instance_id' => 1, 'user_id' => 1, 'plan_id' => 1, + 'due_at' => $today, 'amount' => '10.00', 'status' => 'paid', 'paid_at' => $today + 100], + ['purpose' => 'renewal', 'instance_id' => 1, 'user_id' => 1, 'plan_id' => 1, + 'due_at' => $yesterday, 'amount' => '20.00', 'status' => 'paid', 'paid_at' => $yesterday + 100], + ['purpose' => 'renewal', 'instance_id' => 1, 'user_id' => 1, 'plan_id' => 1, + 'due_at' => $month, 'amount' => '30.00', 'status' => 'paid', 'paid_at' => $month + 100], + ['purpose' => 'provision', 'instance_id' => 1, 'user_id' => 1, 'plan_id' => 1, + 'due_at' => $today, 'amount' => '100.00', 'status' => 'refunded', 'paid_at' => $today + 200], + ['purpose' => 'renewal', 'instance_id' => 1, 'user_id' => 1, 'plan_id' => 1, + 'due_at' => $now + 1000, 'amount' => '5.00', 'status' => 'open', 'paid_at' => null], + ['purpose' => 'renewal', 'instance_id' => 3, 'user_id' => 1, 'plan_id' => 1, + 'due_at' => $now - 1000, 'amount' => '6.00', 'status' => 'open', 'paid_at' => null], + ['purpose' => 'renewal', 'instance_id' => 4, 'user_id' => 2, 'plan_id' => 1, + 'due_at' => $now - 1000, 'amount' => '9.00', 'status' => 'overdue', 'paid_at' => null], + ['purpose' => 'provision', 'instance_id' => null, 'user_id' => 2, 'plan_id' => 1, + 'due_at' => $now + 1000, 'amount' => '7.00', 'status' => 'open', 'paid_at' => null], +]); +Capsule::table('user')->insert([ + ['id' => 1, 'is_admin' => 0, 'enable' => 1, + 'reg_date' => date('Y-m-d H:i:s', $today + 100)], + ['id' => 2, 'is_admin' => 0, 'enable' => 0, + 'reg_date' => date('Y-m-d H:i:s', $today - 86400)], + ['id' => 3, 'is_admin' => 1, 'enable' => 1, + 'reg_date' => date('Y-m-d H:i:s', $today + 200)], +]); +Capsule::table('ticket')->insert([ + ['id' => 1, 'rootid' => 0, 'status' => 1], + ['id' => 2, 'rootid' => 0, 'status' => 0], + ['id' => 3, 'rootid' => 1, 'status' => 1], +]); + +Capsule::connection('default')->enableQueryLog(); +$overview = CloudAdminOverviewService::snapshot(); +$queries = count(Capsule::connection('default')->getQueryLog()); + +$assert = static function ($condition, string $message): void { + if (!$condition) { + throw new RuntimeException($message); + } +}; + +$assert($overview['hosts'] === ['total' => 2, 'enabled' => 1], + 'Host enabled/configured aggregation is incorrect.'); +$assert($overview['instances']['managed'] === 4 + && $overview['instances']['billable'] === 3 + && $overview['instances']['service_normal'] === 2 + && $overview['instances']['network_normal'] === 2 + && $overview['instances']['expiring_7d'] === 1 + && $overview['instances']['grace'] === 1, + 'Instance lifecycle aggregation is incorrect.'); +$assert($overview['jobs']['active'] === 1 + && $overview['jobs']['uncertain'] === 1 + && $overview['jobs']['failed_24h'] === 1 + && $overview['jobs']['today_total'] === 4 + && $overview['jobs']['today_succeeded'] === 2 + && $overview['jobs']['today_failed'] === 1, + 'Job aggregation must use terminal time and exclude lifecycle-only work.'); +$assert($overview['instances']['service_normal'] + $overview['instances']['grace'] <= 4, + 'Expired instances must not be counted as both service-normal and in grace.'); +$assert($overview['revenue']['today'] === '10.00' + && $overview['revenue']['yesterday'] === '20.00' + && $overview['revenue']['today_count'] === 1, + 'Revenue must use paid_at and exclude refunded invoices.'); +$assert($overview['receivables']['count'] === 3 + && $overview['receivables']['amount'] === '18.00' + && $overview['receivables']['overdue_count'] === 1 + && $overview['receivables']['overdue_amount'] === '6.00', + 'Receivables must exclude orphan renewal invoices for deleted instances.'); +$assert($overview['users'] === ['total' => 2, 'enabled' => 1, 'new_today' => 1] + && $overview['tickets']['open'] === 1, + 'Customer or open-ticket aggregation is incorrect.'); +$assert(count($overview['top_plans']) === 1 + && $overview['top_plans'][0]['name'] === '2c4g' + && $overview['top_plans'][0]['count'] === 1 + && $overview['top_plans'][0]['amount'] === '10.00', + 'Top plans must use current paid provisioning invoices only.'); +$assert($queries <= 9, + 'Overview introduced an unbounded query pattern: ' . $queries . ' queries.'); + +echo 'Administrator overview database behavior passed with ' . $queries . " queries.\n";