Compare commits

..

6 Commits

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import { useState } from "react"; import { useEffect, useState } from "react";
import type { ChangeEvent } from "react"; import type { ChangeEvent } from "react";
import type { FormEvent } from "react"; import type { FormEvent } from "react";
import { formatDateTime } from "@/lib/dates"; import { formatDateTime } from "@/lib/dates";
@@ -55,6 +55,15 @@ type Domain = {
updated_at: string; updated_at: string;
}; };
type DomainSortKey =
| "domain"
| "status"
| "hosting"
| "created"
| "aliases"
| "last_seen"
| "actions";
type Props = { type Props = {
instances: Instance[]; instances: Instance[];
subscriptions: Subscription[]; subscriptions: Subscription[];
@@ -160,6 +169,23 @@ function getDomainHref(domainName: string) {
return `https://${normalized}`; return `https://${normalized}`;
} }
function getLatestTimestamp(values: Array<string | null | undefined>) {
let latest: string | null = null;
let latestMs = Number.NEGATIVE_INFINITY;
for (const value of values) {
if (!value) continue;
const ms = new Date(value).getTime();
if (Number.isNaN(ms)) continue;
if (ms > latestMs) {
latestMs = ms;
latest = value;
}
}
return latest;
}
export function DashboardControls({ export function DashboardControls({
instances, instances,
subscriptions, subscriptions,
@@ -167,6 +193,7 @@ export function DashboardControls({
autoSyncByInstance, autoSyncByInstance,
healthEventsByInstance, healthEventsByInstance,
}: Props) { }: Props) {
const hasInstances = instances.length > 0;
const autoSyncFrequencyOptions = [15, 30, 60, 180, 360, 1440]; const autoSyncFrequencyOptions = [15, 30, 60, 180, 360, 1440];
const [instanceName, setInstanceName] = useState(""); const [instanceName, setInstanceName] = useState("");
const [baseUrl, setBaseUrl] = useState(""); const [baseUrl, setBaseUrl] = useState("");
@@ -180,8 +207,78 @@ export function DashboardControls({
); );
const [domainSearch, setDomainSearch] = useState(""); const [domainSearch, setDomainSearch] = useState("");
const [domainStatus, setDomainStatus] = useState("all"); const [domainStatus, setDomainStatus] = useState("all");
const [domainSort, setDomainSort] = useState<{
key: DomainSortKey;
direction: "asc" | "desc";
}>({ key: "domain", direction: "asc" });
const [message, setMessage] = useState<string | null>(null); const [message, setMessage] = useState<string | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [isConnectPanelOpen, setIsConnectPanelOpen] = useState(!hasInstances);
const [isInstancesPanelOpen, setIsInstancesPanelOpen] = useState(true);
useEffect(() => {
if (!hasInstances) {
setIsConnectPanelOpen(true);
return;
}
const savedState = window.localStorage.getItem(
"dashboard_connect_panel_open",
);
if (savedState === "true") {
setIsConnectPanelOpen(true);
return;
}
if (savedState === "false") {
setIsConnectPanelOpen(false);
return;
}
setIsConnectPanelOpen(false);
}, [hasInstances]);
useEffect(() => {
if (!hasInstances) return;
window.localStorage.setItem(
"dashboard_connect_panel_open",
isConnectPanelOpen ? "true" : "false",
);
}, [hasInstances, isConnectPanelOpen]);
useEffect(() => {
if (!hasInstances) {
setIsInstancesPanelOpen(true);
return;
}
const savedState = window.localStorage.getItem(
"dashboard_instances_panel_open",
);
if (savedState === "true") {
setIsInstancesPanelOpen(true);
return;
}
if (savedState === "false") {
setIsInstancesPanelOpen(false);
return;
}
setIsInstancesPanelOpen(true);
}, [hasInstances]);
useEffect(() => {
if (!hasInstances) return;
window.localStorage.setItem(
"dashboard_instances_panel_open",
isInstancesPanelOpen ? "true" : "false",
);
}, [hasInstances, isInstancesPanelOpen]);
const healthCounts = instances.reduce( const healthCounts = instances.reduce(
(acc, instance) => { (acc, instance) => {
@@ -211,6 +308,136 @@ export function DashboardControls({
return statusMatches && searchMatches; return statusMatches && searchMatches;
}); });
const sortedDomains = filteredDomains
.map((domain, index) => ({ domain, index }))
.sort((a, b) => {
function compareNullable<T>(
left: T | null | undefined,
right: T | null | undefined,
compare: (leftValue: T, rightValue: T) => number,
) {
const leftMissing = left == null;
const rightMissing = right == null;
if (leftMissing && rightMissing) return 0;
if (leftMissing) return 1;
if (rightMissing) return -1;
return compare(left, right);
}
function compareStrings(
left: string | null | undefined,
right: string | null | undefined,
) {
return compareNullable(left, right, (l, r) =>
l.localeCompare(r, undefined, { sensitivity: "base" }),
);
}
function compareNumbers(
left: number | null | undefined,
right: number | null | undefined,
) {
return compareNullable(left, right, (l, r) => l - r);
}
function toTime(value: string | null | undefined) {
if (!value) return null;
const time = new Date(value).getTime();
return Number.isNaN(time) ? null : time;
}
const leftDomain = a.domain;
const rightDomain = b.domain;
let comparison = 0;
if (domainSort.key === "domain") {
comparison = compareStrings(
leftDomain.domain_name,
rightDomain.domain_name,
);
} else if (domainSort.key === "status") {
comparison = compareStrings(
formatDomainStatusLabel(leftDomain.status),
formatDomainStatusLabel(rightDomain.status),
);
} else if (domainSort.key === "hosting") {
comparison = compareStrings(
leftDomain.hosting_type,
rightDomain.hosting_type,
);
} else if (domainSort.key === "created") {
comparison = compareNumbers(
toTime(leftDomain.source_created_at),
toTime(rightDomain.source_created_at),
);
} else if (domainSort.key === "aliases") {
comparison = compareNumbers(
leftDomain.aliases_count,
rightDomain.aliases_count,
);
} else if (domainSort.key === "last_seen") {
comparison = compareNumbers(
toTime(leftDomain.updated_at),
toTime(rightDomain.updated_at),
);
} else if (domainSort.key === "actions") {
comparison = compareNumbers(
leftDomain.subscription_id ? 1 : 0,
rightDomain.subscription_id ? 1 : 0,
);
}
if (comparison === 0) {
comparison = a.index - b.index;
}
return domainSort.direction === "asc" ? comparison : comparison * -1;
})
.map((entry) => entry.domain);
function toggleDomainSort(key: DomainSortKey) {
setDomainSort((current) => {
if (current.key === key) {
return {
key,
direction: current.direction === "asc" ? "desc" : "asc",
};
}
return { key, direction: "asc" };
});
}
function getSortIndicator(key: DomainSortKey) {
if (domainSort.key !== key) return "↕";
return domainSort.direction === "asc" ? "↑" : "↓";
}
const instanceHealthSummary = instances.reduce(
(acc, instance) => {
const status = (instance.health_status ?? "unknown").toLowerCase();
if (status === "ok") acc.ok += 1;
else if (status === "degraded") acc.degraded += 1;
else if (status === "down") acc.down += 1;
else acc.unknown += 1;
return acc;
},
{ ok: 0, degraded: 0, down: 0, unknown: 0 },
);
const autoSyncEnabledCount = instances.filter(
(instance) => instance.auto_sync_enabled,
).length;
const latestInstanceSyncAt = getLatestTimestamp(
instances.map((instance) => instance.last_sync_at),
);
const latestInstanceHealthCheckAt = getLatestTimestamp(
instances.map((instance) => instance.health_last_checked_at),
);
async function runRequest(url: string, body?: unknown) { async function runRequest(url: string, body?: unknown) {
const response = await fetch(url, { const response = await fetch(url, {
method: "POST", method: "POST",
@@ -416,11 +643,32 @@ export function DashboardControls({
</div> </div>
<div className="grid gap-4 lg:grid-cols-2"> <div className="grid gap-4 lg:grid-cols-2">
<form <div className="rounded-xl border border-slate-200 bg-white p-4">
onSubmit={onCreateInstance} <div className="flex items-center justify-between gap-3">
className="space-y-3 rounded-xl border border-slate-200 bg-white p-4" <h2 className="text-lg font-semibold">
{hasInstances
? "Connect another Plesk instance"
: "Connect Plesk Instance"}
</h2>
{hasInstances ? (
<button
type="button"
onClick={() => setIsConnectPanelOpen((open) => !open)}
className="rounded border border-slate-300 px-3 py-1.5 text-xs font-medium text-slate-700"
> >
<h2 className="text-lg font-semibold">Connect Plesk Instance</h2> {isConnectPanelOpen ? "Hide" : "Add instance"}
</button>
) : null}
</div>
{!isConnectPanelOpen && hasInstances ? (
<p className="mt-2 text-sm text-slate-500">
Add another server when needed.
</p>
) : null}
{isConnectPanelOpen ? (
<form onSubmit={onCreateInstance} className="mt-3 space-y-3">
<input <input
required required
value={instanceName} value={instanceName}
@@ -489,10 +737,49 @@ export function DashboardControls({
Save & Validate Save & Validate
</button> </button>
</form> </form>
) : null}
</div>
<div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4"> <div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4">
<div className="flex items-center justify-between gap-3">
<h2 className="text-lg font-semibold">Plesk Instances</h2> <h2 className="text-lg font-semibold">Plesk Instances</h2>
{hasInstances ? (
<button
type="button"
onClick={() => setIsInstancesPanelOpen((open) => !open)}
className="rounded border border-slate-300 px-3 py-1.5 text-xs font-medium text-slate-700"
>
{isInstancesPanelOpen ? "Hide" : "Show"}
</button>
) : null}
</div>
{!isInstancesPanelOpen && hasInstances ? (
<div className="rounded border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-700">
<p className="font-medium text-slate-900">
{instances.length} instance{instances.length === 1 ? "" : "s"}
</p>
<p className="mt-1">
Health OK: {instanceHealthSummary.ok}, Degraded:{" "}
{instanceHealthSummary.degraded}, Down:{" "}
{instanceHealthSummary.down}, Unknown:{" "}
{instanceHealthSummary.unknown}
</p>
<p className="mt-1">
Auto-sync enabled on {autoSyncEnabledCount} instance
{autoSyncEnabledCount === 1 ? "" : "s"}
</p>
<p className="mt-1">
Last sync: {formatDateTime(latestInstanceSyncAt)}
</p>
<p className="mt-1">
Last health check: {formatDateTime(latestInstanceHealthCheckAt)}
</p>
</div>
) : null}
{isInstancesPanelOpen ? (
<>
<div className="space-y-2"> <div className="space-y-2">
{instances.length === 0 ? ( {instances.length === 0 ? (
<p className="text-sm text-slate-500"> <p className="text-sm text-slate-500">
@@ -519,7 +806,8 @@ export function DashboardControls({
: "bg-rose-100 text-rose-700" : "bg-rose-100 text-rose-700"
}`} }`}
> >
Auto-sync {autoSyncByInstance[instance.id].status} Auto-sync{" "}
{autoSyncByInstance[instance.id].status}
</span> </span>
) : null} ) : null}
<p className="text-sm font-semibold text-slate-900"> <p className="text-sm font-semibold text-slate-900">
@@ -537,7 +825,9 @@ export function DashboardControls({
<p className="text-xs text-slate-500"> <p className="text-xs text-slate-500">
Health:{" "} Health:{" "}
<span <span
title={instance.health_last_error ?? undefined} title={
instance.health_last_error ?? undefined
}
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${health.className}`} className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${health.className}`}
> >
{health.label} {health.label}
@@ -545,7 +835,9 @@ export function DashboardControls({
</p> </p>
<p className="text-xs text-slate-500"> <p className="text-xs text-slate-500">
Health last checked:{" "} Health last checked:{" "}
{formatDateTime(instance.health_last_checked_at)} {formatDateTime(
instance.health_last_checked_at,
)}
</p> </p>
<p className="text-xs text-slate-500"> <p className="text-xs text-slate-500">
Health latency:{" "} Health latency:{" "}
@@ -566,7 +858,8 @@ export function DashboardControls({
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${ className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
instance.last_sync_status === "success" instance.last_sync_status === "success"
? "bg-emerald-100 text-emerald-700" ? "bg-emerald-100 text-emerald-700"
: instance.last_sync_status === "failed" || : instance.last_sync_status ===
"failed" ||
instance.last_sync_status === "error" instance.last_sync_status === "error"
? "bg-rose-100 text-rose-700" ? "bg-rose-100 text-rose-700"
: "bg-slate-100 text-slate-600" : "bg-slate-100 text-slate-600"
@@ -606,8 +899,9 @@ export function DashboardControls({
<p className="text-xs text-slate-500"> <p className="text-xs text-slate-500">
Lock status:{" "} Lock status:{" "}
{instance.auto_sync_lock_until && {instance.auto_sync_lock_until &&
new Date(instance.auto_sync_lock_until).getTime() > new Date(
Date.now() instance.auto_sync_lock_until,
).getTime() > Date.now()
? "Sync in progress" ? "Sync in progress"
: "Idle"} : "Idle"}
</p> </p>
@@ -629,10 +923,14 @@ export function DashboardControls({
Last sync error: {instance.last_sync_error} Last sync error: {instance.last_sync_error}
</p> </p>
) : null} ) : null}
{autoSyncByInstance[instance.id]?.error_message ? ( {autoSyncByInstance[instance.id]
?.error_message ? (
<p className="mt-1 text-xs text-rose-600"> <p className="mt-1 text-xs text-rose-600">
Auto-sync error:{" "} Auto-sync error:{" "}
{autoSyncByInstance[instance.id].error_message} {
autoSyncByInstance[instance.id]
.error_message
}
</p> </p>
) : null} ) : null}
{instance.health_last_error ? ( {instance.health_last_error ? (
@@ -652,11 +950,14 @@ export function DashboardControls({
<input <input
type="checkbox" type="checkbox"
checked={instance.auto_sync_enabled} checked={instance.auto_sync_enabled}
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange={(
e: ChangeEvent<HTMLInputElement>,
) =>
onUpdateAutoSync(instance.id, { onUpdateAutoSync(instance.id, {
auto_sync_enabled: e.target.checked, auto_sync_enabled: e.target.checked,
auto_sync_frequency_minutes: auto_sync_frequency_minutes:
instance.auto_sync_frequency_minutes ?? 60, instance.auto_sync_frequency_minutes ??
60,
}) })
} }
disabled={loading} disabled={loading}
@@ -668,7 +969,8 @@ export function DashboardControls({
)} )}
onChange={(e: ChangeEvent<HTMLSelectElement>) => onChange={(e: ChangeEvent<HTMLSelectElement>) =>
onUpdateAutoSync(instance.id, { onUpdateAutoSync(instance.id, {
auto_sync_enabled: instance.auto_sync_enabled, auto_sync_enabled:
instance.auto_sync_enabled,
auto_sync_frequency_minutes: Number( auto_sync_frequency_minutes: Number(
e.target.value, e.target.value,
), ),
@@ -779,7 +1081,9 @@ export function DashboardControls({
<td className="px-2 py-1"> <td className="px-2 py-1">
{formatDateTime(event.created_at)} {formatDateTime(event.created_at)}
</td> </td>
<td className="px-2 py-1">{event.action}</td> <td className="px-2 py-1">
{event.action}
</td>
<td className="px-2 py-1"> <td className="px-2 py-1">
{mapHealthResult(event.action)} {mapHealthResult(event.action)}
</td> </td>
@@ -814,7 +1118,9 @@ export function DashboardControls({
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium">Subscription Action</label> <label className="text-sm font-medium">
Subscription Action
</label>
<select <select
value={actionSubId} value={actionSubId}
onChange={(e: ChangeEvent<HTMLSelectElement>) => onChange={(e: ChangeEvent<HTMLSelectElement>) =>
@@ -864,7 +1170,11 @@ export function DashboardControls({
</button> </button>
</div> </div>
{message ? <p className="text-sm text-slate-600">{message}</p> : null} {message ? (
<p className="text-sm text-slate-600">{message}</p>
) : null}
</>
) : null}
</div> </div>
<div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4 lg:col-span-2"> <div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4 lg:col-span-2">
@@ -903,24 +1213,143 @@ export function DashboardControls({
<table className="min-w-full text-left text-sm"> <table className="min-w-full text-left text-sm">
<thead> <thead>
<tr className="border-b border-slate-200 text-xs uppercase text-slate-500"> <tr className="border-b border-slate-200 text-xs uppercase text-slate-500">
<th className="px-2 py-2">Domain</th> <th className="px-2 py-2">
<th className="px-2 py-2">Subscription Status</th> <button
<th className="px-2 py-2">Hosting</th> type="button"
<th className="px-2 py-2">Created</th> onClick={() => toggleDomainSort("domain")}
<th className="px-2 py-2">Aliases</th> className="inline-flex items-center gap-1"
<th className="px-2 py-2">Last seen</th> >
<th className="px-2 py-2">Actions</th> Domain
<span
className={
domainSort.key === "domain"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("domain")}
</span>
</button>
</th>
<th className="px-2 py-2">
<button
type="button"
onClick={() => toggleDomainSort("status")}
className="inline-flex items-center gap-1"
>
Subscription Status
<span
className={
domainSort.key === "status"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("status")}
</span>
</button>
</th>
<th className="px-2 py-2">
<button
type="button"
onClick={() => toggleDomainSort("hosting")}
className="inline-flex items-center gap-1"
>
Hosting
<span
className={
domainSort.key === "hosting"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("hosting")}
</span>
</button>
</th>
<th className="px-2 py-2">
<button
type="button"
onClick={() => toggleDomainSort("created")}
className="inline-flex items-center gap-1"
>
Created
<span
className={
domainSort.key === "created"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("created")}
</span>
</button>
</th>
<th className="px-2 py-2">
<button
type="button"
onClick={() => toggleDomainSort("aliases")}
className="inline-flex items-center gap-1"
>
Aliases
<span
className={
domainSort.key === "aliases"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("aliases")}
</span>
</button>
</th>
<th className="px-2 py-2">
<button
type="button"
onClick={() => toggleDomainSort("last_seen")}
className="inline-flex items-center gap-1"
>
Last seen
<span
className={
domainSort.key === "last_seen"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("last_seen")}
</span>
</button>
</th>
<th className="px-2 py-2">
<button
type="button"
onClick={() => toggleDomainSort("actions")}
className="inline-flex items-center gap-1"
>
Actions
<span
className={
domainSort.key === "actions"
? "text-brand-700"
: "text-slate-400"
}
>
{getSortIndicator("actions")}
</span>
</button>
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{filteredDomains.length === 0 ? ( {sortedDomains.length === 0 ? (
<tr> <tr>
<td className="px-2 py-3 text-slate-500" colSpan={7}> <td className="px-2 py-3 text-slate-500" colSpan={7}>
No domains found. No domains found.
</td> </td>
</tr> </tr>
) : ( ) : (
filteredDomains.map((domain) => ( sortedDomains.map((domain) => (
<tr key={domain.id} className="border-b border-slate-100"> <tr key={domain.id} className="border-b border-slate-100">
<td className="px-2 py-2 font-medium text-slate-900"> <td className="px-2 py-2 font-medium text-slate-900">
<a <a