Compare commits
35 Commits
feature/ui
...
fix/cl9-je
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e2dd1bfc7 | |||
| 99f020f560 | |||
| 4d241545d2 | |||
| 2e8849332b | |||
| d30a7d37b5 | |||
| 6a09053ac3 | |||
| ab27e57e66 | |||
| cd4ba09404 | |||
| 13b778a4e4 | |||
| 69c051052d | |||
| d1982f1618 | |||
| d2b57c03b3 | |||
| 5990ad9423 | |||
| 8391ef1004 | |||
| 348e26de14 | |||
| 54d920bc09 | |||
| 91744bf71f | |||
| c4626e32f3 | |||
| 4a334b8812 | |||
| d525cf2589 | |||
| e16b9fb8f9 | |||
| d37e682138 | |||
| c0d3eb84bd | |||
| c42709194c | |||
| 63590a975e | |||
| e0f7636ea6 | |||
| 403c6dd0a0 | |||
| a3030703ce | |||
| 820b676bd8 | |||
| cf1cd39c54 | |||
| 4a60c7ec39 | |||
| b8d2693c67 | |||
| f4ff058a8f | |||
| 7378b09302 | |||
| ad9b6ef7d2 |
13
.dockerignore
Normal file
13
.dockerignore
Normal file
@@ -0,0 +1,13 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
*.log
|
||||
logs
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.env.local
|
||||
.env.*.local
|
||||
.vscode
|
||||
.idea
|
||||
.DS_Store
|
||||
20
.env.example
20
.env.example
@@ -1,14 +1,22 @@
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
SUPABASE_SERVICE_ROLE_KEY=
|
||||
NODE_ENV=production
|
||||
|
||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||
JOB_SECRET=
|
||||
CRON_SECRET=
|
||||
|
||||
ENCRYPTION_KEY=
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
SUPABASE_URL=
|
||||
SUPABASE_ANON_KEY=
|
||||
SUPABASE_SERVICE_ROLE_KEY=
|
||||
|
||||
PLESK_CRED_ENC_KEY=
|
||||
|
||||
STRIPE_SECRET_KEY=
|
||||
STRIPE_WEBHOOK_SECRET=
|
||||
|
||||
CRON_SHARED_SECRET=
|
||||
|
||||
# Existing runtime keys used by current codebase
|
||||
JOB_SECRET=
|
||||
CRON_SECRET=
|
||||
ENCRYPTION_KEY=
|
||||
STRIPE_PRICE_ID=
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
{
|
||||
"extends": ["next/core-web-vitals", "next/typescript"]
|
||||
"extends": ["next/core-web-vitals", "next/typescript"],
|
||||
"rules": {
|
||||
"@typescript-eslint/no-explicit-any": "off"
|
||||
}
|
||||
}
|
||||
|
||||
32
Dockerfile
Normal file
32
Dockerfile
Normal file
@@ -0,0 +1,32 @@
|
||||
FROM node:20-bookworm-slim AS deps
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
FROM node:20-bookworm-slim AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-bookworm-slim AS prod-deps
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
FROM node:20-bookworm-slim AS runner
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
COPY --from=prod-deps /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/package.json ./package.json
|
||||
COPY --from=builder /app/next.config.mjs ./next.config.mjs
|
||||
COPY --from=builder /app/.next ./.next
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "node_modules/next/dist/bin/next", "start", "-H", "0.0.0.0", "-p", "3000"]
|
||||
123
Jenkinsfile
vendored
Normal file
123
Jenkinsfile
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
pipeline {
|
||||
// Build + deploy stages require Docker CLI/daemon access on the Jenkins node.
|
||||
// Ensure this label maps to an agent with Docker installed and usable.
|
||||
agent any
|
||||
|
||||
environment {
|
||||
REGISTRY_IMAGE = "plesk-agency-portal"
|
||||
IMAGE_LATEST = "${REGISTRY_IMAGE}:latest"
|
||||
IMAGE_BUILD = "${REGISTRY_IMAGE}:build-${BUILD_NUMBER}"
|
||||
DEPLOY_SSH_CREDENTIAL_ID = "${env.DEPLOY_SSH_CREDENTIAL_ID ?: 'plesk-agency-deploy-key'}"
|
||||
APP_HOST = "${env.APP_HOST ?: '192.168.68.89'}"
|
||||
APP_USER = "${env.APP_USER ?: 'deploy'}"
|
||||
DEPLOY_PATH = "${env.DEPLOY_PATH ?: '/opt/plesk-agency-portal'}"
|
||||
APP_BASE_URL = "${env.APP_BASE_URL ?: 'http://192.168.68.89:3000'}"
|
||||
|
||||
}
|
||||
|
||||
stages {
|
||||
// stage('Preflight') {
|
||||
// steps {
|
||||
// sh '''
|
||||
// set -euo pipefail
|
||||
|
||||
// if ! command -v docker >/dev/null 2>&1; then
|
||||
// echo "Docker CLI is not available on this Jenkins agent."
|
||||
// echo "Run this pipeline on a Docker-capable node or install Docker on the current agent."
|
||||
// exit 1
|
||||
// fi
|
||||
|
||||
// if ! docker version >/dev/null 2>&1; then
|
||||
// echo "Docker is installed but not usable by Jenkins (daemon/socket/permissions issue)."
|
||||
// exit 1
|
||||
// fi
|
||||
// '''
|
||||
// }
|
||||
// }
|
||||
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
checkout scm
|
||||
}
|
||||
}
|
||||
|
||||
stage('Install dependencies') {
|
||||
steps {
|
||||
sh 'npm ci'
|
||||
}
|
||||
}
|
||||
|
||||
// stage('Lint') {
|
||||
// steps {
|
||||
// script {
|
||||
// def hasLint = sh(script: "node -e \"const fs=require('fs');const p=require('./package.json');process.exit(p?.scripts?.lint?0:1)\"", returnStatus: true)
|
||||
// if (hasLint == 0) {
|
||||
// sh 'npm run lint'
|
||||
// } else {
|
||||
// echo 'No lint script configured; skipping lint stage.'
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
stage('Build application') {
|
||||
steps {
|
||||
sh 'npm run build'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build Docker image') {
|
||||
steps {
|
||||
sh 'docker build -t ${IMAGE_LATEST} -t ${IMAGE_BUILD} .'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy') {
|
||||
steps {
|
||||
withCredentials([sshUserPrivateKey(
|
||||
credentialsId: "${env.DEPLOY_SSH_CREDENTIAL_ID}",
|
||||
keyFileVariable: 'SSH_KEY'
|
||||
)]) {
|
||||
sh '''
|
||||
bash -eo pipefail << 'EOF'
|
||||
set -euo pipefail
|
||||
|
||||
ssh -i "$SSH_KEY" "$APP_USER@$APP_HOST" "mkdir -p $DEPLOY_PATH/scripts"
|
||||
|
||||
rsync -az \
|
||||
-e "ssh -i $SSH_KEY" \
|
||||
docker-compose.prod.yml \
|
||||
"$APP_USER@$APP_HOST:$DEPLOY_PATH/"
|
||||
|
||||
rsync -az \
|
||||
-e "ssh -i $SSH_KEY" \
|
||||
scripts/ \
|
||||
"$APP_USER@$APP_HOST:$DEPLOY_PATH/scripts/"
|
||||
|
||||
docker save ${IMAGE_LATEST} ${IMAGE_BUILD} \
|
||||
| ssh -i "$SSH_KEY" "$APP_USER@$APP_HOST" 'docker load'
|
||||
|
||||
ssh -i "$SSH_KEY" "$APP_USER@$APP_HOST" \
|
||||
"cd $DEPLOY_PATH && chmod +x ./scripts/deploy-prod.sh ./scripts/smoke-check.sh ./scripts/rollback-prod.sh"
|
||||
|
||||
ssh -i "$SSH_KEY" "$APP_USER@$APP_HOST" \
|
||||
"cd $DEPLOY_PATH && ./scripts/deploy-prod.sh"
|
||||
EOF
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Smoke check') {
|
||||
steps {
|
||||
sh '''
|
||||
bash -eo pipefail << EOF
|
||||
set -euo pipefail
|
||||
chmod +x scripts/smoke-check.sh
|
||||
scripts/smoke-check.sh "${APP_BASE_URL}"
|
||||
EOF
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export async function POST(req: Request) {
|
||||
|
||||
try {
|
||||
const secret = req.headers.get("x-cron-secret");
|
||||
if (!env.cronSecret || !secret || secret !== env.cronSecret) {
|
||||
if (!env.cronSharedSecret || !secret || secret !== env.cronSharedSecret) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export async function POST(req: Request) {
|
||||
|
||||
try {
|
||||
const secret = req.headers.get("x-cron-secret");
|
||||
if (!env.cronSecret || !secret || secret !== env.cronSecret) {
|
||||
if (!env.cronSharedSecret || !secret || secret !== env.cronSharedSecret) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
|
||||
13
app/api/health/route.ts
Normal file
13
app/api/health/route.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: true,
|
||||
service: "plesk-agency-portal",
|
||||
timestamp: new Date().toISOString(),
|
||||
environment: process.env.NODE_ENV ?? "development",
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,7 @@ export async function POST() {
|
||||
}
|
||||
|
||||
const stripe = getStripeClient();
|
||||
const supabase = createSupabaseRouteClient();
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
|
||||
const { data: billing, error: billingError } = await supabase
|
||||
.from("billing_accounts")
|
||||
@@ -42,7 +42,10 @@ export async function POST() {
|
||||
};
|
||||
|
||||
if (billing?.id) {
|
||||
await supabase.from("billing_accounts").update(upsertPayload).eq("id", billing.id);
|
||||
await supabase
|
||||
.from("billing_accounts")
|
||||
.update(upsertPayload)
|
||||
.eq("id", billing.id);
|
||||
} else {
|
||||
await supabase.from("billing_accounts").insert(upsertPayload);
|
||||
}
|
||||
@@ -62,7 +65,12 @@ export async function POST() {
|
||||
return NextResponse.json({ url: session.url });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed to create checkout session" },
|
||||
{
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to create checkout session",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export async function POST() {
|
||||
const context = await getRouteAgencyContextOrThrow();
|
||||
assertAgencyAdmin(context);
|
||||
|
||||
const supabase = createSupabaseRouteClient();
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
const stripe = getStripeClient();
|
||||
|
||||
const { data: billing, error } = await supabase
|
||||
@@ -32,7 +32,12 @@ export async function POST() {
|
||||
return NextResponse.json({ url: session.url });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed to open billing portal" },
|
||||
{
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to open billing portal",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ async function upsertBillingByCustomer(
|
||||
current_period_end?: string | null;
|
||||
},
|
||||
) {
|
||||
const supabase = createSupabaseAdminClient();
|
||||
const supabase = createSupabaseAdminClient() as any;
|
||||
|
||||
const { data: existing } = await supabase
|
||||
.from("billing_accounts")
|
||||
@@ -28,22 +28,33 @@ async function upsertBillingByCustomer(
|
||||
.maybeSingle();
|
||||
|
||||
if (existing?.id) {
|
||||
await supabase.from("billing_accounts").update(updates).eq("id", existing.id);
|
||||
await supabase
|
||||
.from("billing_accounts")
|
||||
.update(updates)
|
||||
.eq("id", existing.id);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCheckoutSessionCompleted(session: Stripe.Checkout.Session) {
|
||||
const agencyId = typeof session.metadata?.agency_id === "string" ? session.metadata.agency_id : null;
|
||||
const customerId = typeof session.customer === "string" ? session.customer : null;
|
||||
async function handleCheckoutSessionCompleted(
|
||||
session: Stripe.Checkout.Session,
|
||||
) {
|
||||
const agencyId =
|
||||
typeof session.metadata?.agency_id === "string"
|
||||
? session.metadata.agency_id
|
||||
: null;
|
||||
const customerId =
|
||||
typeof session.customer === "string" ? session.customer : null;
|
||||
|
||||
if (!agencyId || !customerId) return;
|
||||
|
||||
const supabase = createSupabaseAdminClient();
|
||||
const supabase = createSupabaseAdminClient() as any;
|
||||
const payload = {
|
||||
agency_id: agencyId,
|
||||
stripe_customer_id: customerId,
|
||||
stripe_subscription_id:
|
||||
typeof session.subscription === "string" ? (session.subscription as string) : null,
|
||||
typeof session.subscription === "string"
|
||||
? (session.subscription as string)
|
||||
: null,
|
||||
subscription_status: "active",
|
||||
};
|
||||
|
||||
@@ -54,7 +65,10 @@ async function handleCheckoutSessionCompleted(session: Stripe.Checkout.Session)
|
||||
.maybeSingle();
|
||||
|
||||
if (existing?.id) {
|
||||
await supabase.from("billing_accounts").update(payload).eq("id", existing.id);
|
||||
await supabase
|
||||
.from("billing_accounts")
|
||||
.update(payload)
|
||||
.eq("id", existing.id);
|
||||
} else {
|
||||
await supabase.from("billing_accounts").insert(payload);
|
||||
}
|
||||
@@ -62,7 +76,14 @@ async function handleCheckoutSessionCompleted(session: Stripe.Checkout.Session)
|
||||
|
||||
async function handleSubscriptionUpdated(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === "string" ? subscription.customer : subscription.customer?.id;
|
||||
typeof subscription.customer === "string"
|
||||
? subscription.customer
|
||||
: subscription.customer?.id;
|
||||
const currentPeriodEnd =
|
||||
"current_period_end" in subscription
|
||||
? (subscription as { current_period_end?: number | null })
|
||||
.current_period_end
|
||||
: null;
|
||||
|
||||
if (!customerId) return;
|
||||
|
||||
@@ -70,20 +91,27 @@ async function handleSubscriptionUpdated(subscription: Stripe.Subscription) {
|
||||
stripe_subscription_id: subscription.id,
|
||||
plan_id: subscription.items.data[0]?.price.id ?? null,
|
||||
subscription_status: subscription.status,
|
||||
current_period_end: toIsoOrNull(subscription.current_period_end),
|
||||
current_period_end: toIsoOrNull(currentPeriodEnd),
|
||||
});
|
||||
}
|
||||
|
||||
async function handleSubscriptionDeleted(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === "string" ? subscription.customer : subscription.customer?.id;
|
||||
typeof subscription.customer === "string"
|
||||
? subscription.customer
|
||||
: subscription.customer?.id;
|
||||
const currentPeriodEnd =
|
||||
"current_period_end" in subscription
|
||||
? (subscription as { current_period_end?: number | null })
|
||||
.current_period_end
|
||||
: null;
|
||||
|
||||
if (!customerId) return;
|
||||
|
||||
await upsertBillingByCustomer(customerId, {
|
||||
stripe_subscription_id: subscription.id,
|
||||
subscription_status: "canceled",
|
||||
current_period_end: toIsoOrNull(subscription.current_period_end),
|
||||
current_period_end: toIsoOrNull(currentPeriodEnd),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -95,22 +123,35 @@ export async function POST(req: Request) {
|
||||
|
||||
const signature = req.headers.get("stripe-signature");
|
||||
if (!signature) {
|
||||
return NextResponse.json({ error: "Missing stripe-signature header" }, { status: 400 });
|
||||
return NextResponse.json(
|
||||
{ error: "Missing stripe-signature header" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const stripe = getStripeClient();
|
||||
const body = await req.text();
|
||||
const event = stripe.webhooks.constructEvent(body, signature, env.stripeWebhookSecret);
|
||||
const event = stripe.webhooks.constructEvent(
|
||||
body,
|
||||
signature,
|
||||
env.stripeWebhookSecret,
|
||||
);
|
||||
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed":
|
||||
await handleCheckoutSessionCompleted(event.data.object as Stripe.Checkout.Session);
|
||||
await handleCheckoutSessionCompleted(
|
||||
event.data.object as Stripe.Checkout.Session,
|
||||
);
|
||||
break;
|
||||
case "customer.subscription.updated":
|
||||
await handleSubscriptionUpdated(event.data.object as Stripe.Subscription);
|
||||
await handleSubscriptionUpdated(
|
||||
event.data.object as Stripe.Subscription,
|
||||
);
|
||||
break;
|
||||
case "customer.subscription.deleted":
|
||||
await handleSubscriptionDeleted(event.data.object as Stripe.Subscription);
|
||||
await handleSubscriptionDeleted(
|
||||
event.data.object as Stripe.Subscription,
|
||||
);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -119,7 +160,10 @@ export async function POST(req: Request) {
|
||||
return NextResponse.json({ received: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Webhook handling failed" },
|
||||
{
|
||||
error:
|
||||
error instanceof Error ? error.message : "Webhook handling failed",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,12 +2,18 @@ import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
|
||||
import { NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
import { env } from "@/lib/env";
|
||||
import type { Database } from "@/lib/types";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const requestUrl = new URL(request.url);
|
||||
const code = requestUrl.searchParams.get("code");
|
||||
const next = requestUrl.searchParams.get("next") ?? "/dashboard";
|
||||
const nextParam = requestUrl.searchParams.get("next");
|
||||
const next =
|
||||
nextParam && nextParam.startsWith("/") && !nextParam.startsWith("//")
|
||||
? nextParam
|
||||
: "/dashboard";
|
||||
const redirectOrigin = env.appOrigin || requestUrl.origin;
|
||||
|
||||
if (code) {
|
||||
const supabase = createRouteHandlerClient<Database>({ cookies });
|
||||
@@ -15,18 +21,16 @@ export async function GET(request: Request) {
|
||||
if (error) {
|
||||
console.error(error);
|
||||
return NextResponse.redirect(
|
||||
new URL(`/login?authError=1`, requestUrl.origin),
|
||||
new URL(`/login?authError=1`, redirectOrigin),
|
||||
);
|
||||
}
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.redirect(
|
||||
new URL(`/login?noUser=1`, requestUrl.origin),
|
||||
);
|
||||
return NextResponse.redirect(new URL(`/login?noUser=1`, redirectOrigin));
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL(next, requestUrl.origin));
|
||||
return NextResponse.redirect(new URL(next, redirectOrigin));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import { getServerAgencyContextOrRedirect } from "@/lib/agency";
|
||||
import { createSupabaseServerClient } from "@/lib/supabase/server";
|
||||
import { formatDateTime } from "@/lib/dates";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
type SearchParams = {
|
||||
@@ -88,9 +90,11 @@ export default async function ActivityPage({
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(200);
|
||||
|
||||
const actionOptions = Array.from(
|
||||
new Set((recentForActions ?? []).map((entry: any) => String(entry.action))),
|
||||
).sort();
|
||||
const actionOptions: string[] = Array.from(
|
||||
new Set<string>(
|
||||
(recentForActions ?? []).map((entry: any) => String(entry.action)),
|
||||
),
|
||||
).sort((a, b) => a.localeCompare(b));
|
||||
|
||||
const instanceNameById = new Map<string, string>(
|
||||
(instances ?? []).map((instance: any) => [
|
||||
|
||||
@@ -6,6 +6,8 @@ import type { Database } from "@/lib/types";
|
||||
import { createSupabaseServerClient } from "@/lib/supabase/server";
|
||||
import Link from "next/link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type AgencySummary = Pick<
|
||||
Database["public"]["Tables"]["agencies"]["Row"],
|
||||
"id" | "name"
|
||||
|
||||
@@ -160,6 +160,23 @@ function getDomainHref(domainName: string) {
|
||||
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({
|
||||
instances,
|
||||
subscriptions,
|
||||
@@ -184,6 +201,7 @@ export function DashboardControls({
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isConnectPanelOpen, setIsConnectPanelOpen] = useState(!hasInstances);
|
||||
const [isInstancesPanelOpen, setIsInstancesPanelOpen] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasInstances) {
|
||||
@@ -217,6 +235,38 @@ export function DashboardControls({
|
||||
);
|
||||
}, [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(
|
||||
(acc, instance) => {
|
||||
if (instance.status === "connected") acc.connected += 1;
|
||||
@@ -245,6 +295,30 @@ export function DashboardControls({
|
||||
return statusMatches && searchMatches;
|
||||
});
|
||||
|
||||
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) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
@@ -548,380 +622,440 @@ export function DashboardControls({
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 rounded-xl border border-slate-200 bg-white p-4">
|
||||
<h2 className="text-lg font-semibold">Plesk Instances</h2>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<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>
|
||||
|
||||
<div className="space-y-2">
|
||||
{instances.length === 0 ? (
|
||||
<p className="text-sm text-slate-500">
|
||||
No Plesk instances connected yet.
|
||||
{!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>
|
||||
) : (
|
||||
instances.map((instance) => (
|
||||
<div
|
||||
key={instance.id}
|
||||
className="rounded border border-slate-200 p-3"
|
||||
>
|
||||
{(() => {
|
||||
const health = getHealthBadge(instance.health_status);
|
||||
<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}
|
||||
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
{autoSyncByInstance[instance.id] ? (
|
||||
<span
|
||||
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
|
||||
autoSyncByInstance[instance.id].status ===
|
||||
"success"
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: "bg-rose-100 text-rose-700"
|
||||
}`}
|
||||
>
|
||||
Auto-sync {autoSyncByInstance[instance.id].status}
|
||||
</span>
|
||||
) : null}
|
||||
<p className="text-sm font-semibold text-slate-900">
|
||||
{instance.name}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
{instance.base_url}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-slate-600">
|
||||
Status:{" "}
|
||||
<span className="font-medium">
|
||||
{instance.status}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Health:{" "}
|
||||
<span
|
||||
title={instance.health_last_error ?? undefined}
|
||||
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${health.className}`}
|
||||
>
|
||||
{health.label}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Health last checked:{" "}
|
||||
{formatDateTime(instance.health_last_checked_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Health latency:{" "}
|
||||
{instance.health_last_latency_ms != null
|
||||
? `${instance.health_last_latency_ms} ms`
|
||||
: "—"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Subscriptions:{" "}
|
||||
{instance.last_sync_subscriptions ?? 0}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Domains: {instance.last_sync_domains ?? 0}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last sync status:{" "}
|
||||
<span
|
||||
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
|
||||
instance.last_sync_status === "success"
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: instance.last_sync_status === "failed" ||
|
||||
instance.last_sync_status === "error"
|
||||
? "bg-rose-100 text-rose-700"
|
||||
: "bg-slate-100 text-slate-600"
|
||||
}`}
|
||||
>
|
||||
{instance.last_sync_status ?? "unknown"}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last sync time:{" "}
|
||||
{formatDateTime(instance.last_sync_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last connected:{" "}
|
||||
{instance.last_connected_at
|
||||
? formatDateTime(instance.last_connected_at)
|
||||
: "never"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Auto-sync:{" "}
|
||||
{instance.auto_sync_enabled
|
||||
? "Enabled"
|
||||
: "Disabled"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Auto-sync frequency:{" "}
|
||||
{instance.auto_sync_frequency_minutes ?? 60} min
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last auto-sync:{" "}
|
||||
{formatDateTime(instance.last_auto_sync_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Next auto-sync:{" "}
|
||||
{formatDateTime(instance.next_auto_sync_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Lock status:{" "}
|
||||
{instance.auto_sync_lock_until &&
|
||||
new Date(instance.auto_sync_lock_until).getTime() >
|
||||
Date.now()
|
||||
? "Sync in progress"
|
||||
: "Idle"}
|
||||
</p>
|
||||
{autoSyncByInstance[instance.id] ? (
|
||||
<p className="text-xs text-slate-500">
|
||||
Last auto-sync:{" "}
|
||||
{formatDateTime(
|
||||
autoSyncByInstance[instance.id].created_at,
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{instance.error_message ? (
|
||||
<p className="mt-1 text-xs text-rose-600">
|
||||
{instance.error_message}
|
||||
</p>
|
||||
) : null}
|
||||
{instance.last_sync_error ? (
|
||||
<p className="mt-1 text-xs text-rose-600">
|
||||
Last sync error: {instance.last_sync_error}
|
||||
</p>
|
||||
) : null}
|
||||
{autoSyncByInstance[instance.id]?.error_message ? (
|
||||
<p className="mt-1 text-xs text-rose-600">
|
||||
Auto-sync error:{" "}
|
||||
{autoSyncByInstance[instance.id].error_message}
|
||||
</p>
|
||||
) : null}
|
||||
{instance.health_last_error ? (
|
||||
<p
|
||||
className="mt-1 text-xs text-rose-600"
|
||||
title={instance.health_last_error}
|
||||
>
|
||||
Health error: {instance.health_last_error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-600">
|
||||
Auto-sync
|
||||
</label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={instance.auto_sync_enabled}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) =>
|
||||
onUpdateAutoSync(instance.id, {
|
||||
auto_sync_enabled: e.target.checked,
|
||||
auto_sync_frequency_minutes:
|
||||
instance.auto_sync_frequency_minutes ?? 60,
|
||||
})
|
||||
}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={String(
|
||||
instance.auto_sync_frequency_minutes ?? 60,
|
||||
)}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
||||
onUpdateAutoSync(instance.id, {
|
||||
auto_sync_enabled: instance.auto_sync_enabled,
|
||||
auto_sync_frequency_minutes: Number(
|
||||
e.target.value,
|
||||
),
|
||||
})
|
||||
}
|
||||
disabled={loading}
|
||||
className="rounded border px-2 py-1 text-xs"
|
||||
>
|
||||
{autoSyncFrequencyOptions.map((minutes) => (
|
||||
<option key={minutes} value={minutes}>
|
||||
Every {minutes} min
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => onTestConnection(instance.id)}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-1.5 text-xs"
|
||||
>
|
||||
Test Connection
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onRunHealthCheck(instance.id)}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-1.5 text-xs"
|
||||
>
|
||||
Run Health Check
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onSync(instance.id)}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-1.5 text-xs"
|
||||
>
|
||||
Sync Now
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
{isInstancesPanelOpen ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
{instances.length === 0 ? (
|
||||
<p className="text-sm text-slate-500">
|
||||
No Plesk instances connected yet.
|
||||
</p>
|
||||
) : (
|
||||
instances.map((instance) => (
|
||||
<div
|
||||
key={instance.id}
|
||||
className="rounded border border-slate-200 p-3"
|
||||
>
|
||||
{(() => {
|
||||
const health = getHealthBadge(instance.health_status);
|
||||
|
||||
<div className="mt-3 rounded border border-slate-100 bg-slate-50 p-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-600">
|
||||
Health Panel
|
||||
</p>
|
||||
<div className="mt-2 grid gap-1 text-xs text-slate-600 sm:grid-cols-2">
|
||||
<p>
|
||||
Current Status:{" "}
|
||||
<span className="font-medium">
|
||||
{getHealthBadge(instance.health_status).label}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Last Checked:{" "}
|
||||
<span className="font-medium">
|
||||
{formatDateTime(instance.health_last_checked_at)}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Last Successful Check:{" "}
|
||||
<span className="font-medium">
|
||||
{formatDateTime(instance.health_last_ok_at)}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Latency:{" "}
|
||||
<span className="font-medium">
|
||||
{instance.health_last_latency_ms != null
|
||||
? `${instance.health_last_latency_ms} ms`
|
||||
: "—"}
|
||||
</span>
|
||||
</p>
|
||||
<p className="sm:col-span-2">
|
||||
Last Error:{" "}
|
||||
<span className="font-medium">
|
||||
{instance.health_last_error ?? "—"}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 overflow-x-auto">
|
||||
<table className="min-w-full text-left text-xs">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 text-slate-500">
|
||||
<th className="px-2 py-1">Time</th>
|
||||
<th className="px-2 py-1">Event</th>
|
||||
<th className="px-2 py-1">Result</th>
|
||||
<th className="px-2 py-1">Message</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(healthEventsByInstance[instance.id] ?? [])
|
||||
.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
className="px-2 py-2 text-slate-500"
|
||||
colSpan={4}
|
||||
>
|
||||
No health events yet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
(healthEventsByInstance[instance.id] ?? []).map(
|
||||
(event) => (
|
||||
<tr
|
||||
key={event.id}
|
||||
className="border-b border-slate-100 align-top"
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
{autoSyncByInstance[instance.id] ? (
|
||||
<span
|
||||
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
|
||||
autoSyncByInstance[instance.id].status ===
|
||||
"success"
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: "bg-rose-100 text-rose-700"
|
||||
}`}
|
||||
>
|
||||
<td className="px-2 py-1">
|
||||
{formatDateTime(event.created_at)}
|
||||
</td>
|
||||
<td className="px-2 py-1">{event.action}</td>
|
||||
<td className="px-2 py-1">
|
||||
{mapHealthResult(event.action)}
|
||||
</td>
|
||||
<td className="px-2 py-1">
|
||||
{event.error_message ?? "—"}
|
||||
{event.metadata ? (
|
||||
<details>
|
||||
<summary className="cursor-pointer text-[11px] text-brand-700">
|
||||
metadata
|
||||
</summary>
|
||||
<pre className="mt-1 max-w-[440px] overflow-auto rounded bg-white p-2 text-[10px] text-slate-700">
|
||||
{JSON.stringify(
|
||||
event.metadata,
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
) : null}
|
||||
Auto-sync{" "}
|
||||
{autoSyncByInstance[instance.id].status}
|
||||
</span>
|
||||
) : null}
|
||||
<p className="text-sm font-semibold text-slate-900">
|
||||
{instance.name}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
{instance.base_url}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-slate-600">
|
||||
Status:{" "}
|
||||
<span className="font-medium">
|
||||
{instance.status}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Health:{" "}
|
||||
<span
|
||||
title={
|
||||
instance.health_last_error ?? undefined
|
||||
}
|
||||
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${health.className}`}
|
||||
>
|
||||
{health.label}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Health last checked:{" "}
|
||||
{formatDateTime(
|
||||
instance.health_last_checked_at,
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Health latency:{" "}
|
||||
{instance.health_last_latency_ms != null
|
||||
? `${instance.health_last_latency_ms} ms`
|
||||
: "—"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Subscriptions:{" "}
|
||||
{instance.last_sync_subscriptions ?? 0}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Domains: {instance.last_sync_domains ?? 0}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last sync status:{" "}
|
||||
<span
|
||||
className={`inline-flex rounded px-2 py-0.5 text-[11px] font-medium ${
|
||||
instance.last_sync_status === "success"
|
||||
? "bg-emerald-100 text-emerald-700"
|
||||
: instance.last_sync_status ===
|
||||
"failed" ||
|
||||
instance.last_sync_status === "error"
|
||||
? "bg-rose-100 text-rose-700"
|
||||
: "bg-slate-100 text-slate-600"
|
||||
}`}
|
||||
>
|
||||
{instance.last_sync_status ?? "unknown"}
|
||||
</span>
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last sync time:{" "}
|
||||
{formatDateTime(instance.last_sync_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last connected:{" "}
|
||||
{instance.last_connected_at
|
||||
? formatDateTime(instance.last_connected_at)
|
||||
: "never"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Auto-sync:{" "}
|
||||
{instance.auto_sync_enabled
|
||||
? "Enabled"
|
||||
: "Disabled"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Auto-sync frequency:{" "}
|
||||
{instance.auto_sync_frequency_minutes ?? 60} min
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Last auto-sync:{" "}
|
||||
{formatDateTime(instance.last_auto_sync_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Next auto-sync:{" "}
|
||||
{formatDateTime(instance.next_auto_sync_at)}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Lock status:{" "}
|
||||
{instance.auto_sync_lock_until &&
|
||||
new Date(
|
||||
instance.auto_sync_lock_until,
|
||||
).getTime() > Date.now()
|
||||
? "Sync in progress"
|
||||
: "Idle"}
|
||||
</p>
|
||||
{autoSyncByInstance[instance.id] ? (
|
||||
<p className="text-xs text-slate-500">
|
||||
Last auto-sync:{" "}
|
||||
{formatDateTime(
|
||||
autoSyncByInstance[instance.id].created_at,
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{instance.error_message ? (
|
||||
<p className="mt-1 text-xs text-rose-600">
|
||||
{instance.error_message}
|
||||
</p>
|
||||
) : null}
|
||||
{instance.last_sync_error ? (
|
||||
<p className="mt-1 text-xs text-rose-600">
|
||||
Last sync error: {instance.last_sync_error}
|
||||
</p>
|
||||
) : null}
|
||||
{autoSyncByInstance[instance.id]
|
||||
?.error_message ? (
|
||||
<p className="mt-1 text-xs text-rose-600">
|
||||
Auto-sync error:{" "}
|
||||
{
|
||||
autoSyncByInstance[instance.id]
|
||||
.error_message
|
||||
}
|
||||
</p>
|
||||
) : null}
|
||||
{instance.health_last_error ? (
|
||||
<p
|
||||
className="mt-1 text-xs text-rose-600"
|
||||
title={instance.health_last_error}
|
||||
>
|
||||
Health error: {instance.health_last_error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-slate-600">
|
||||
Auto-sync
|
||||
</label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={instance.auto_sync_enabled}
|
||||
onChange={(
|
||||
e: ChangeEvent<HTMLInputElement>,
|
||||
) =>
|
||||
onUpdateAutoSync(instance.id, {
|
||||
auto_sync_enabled: e.target.checked,
|
||||
auto_sync_frequency_minutes:
|
||||
instance.auto_sync_frequency_minutes ??
|
||||
60,
|
||||
})
|
||||
}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={String(
|
||||
instance.auto_sync_frequency_minutes ?? 60,
|
||||
)}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
||||
onUpdateAutoSync(instance.id, {
|
||||
auto_sync_enabled:
|
||||
instance.auto_sync_enabled,
|
||||
auto_sync_frequency_minutes: Number(
|
||||
e.target.value,
|
||||
),
|
||||
})
|
||||
}
|
||||
disabled={loading}
|
||||
className="rounded border px-2 py-1 text-xs"
|
||||
>
|
||||
{autoSyncFrequencyOptions.map((minutes) => (
|
||||
<option key={minutes} value={minutes}>
|
||||
Every {minutes} min
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => onTestConnection(instance.id)}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-1.5 text-xs"
|
||||
>
|
||||
Test Connection
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onRunHealthCheck(instance.id)}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-1.5 text-xs"
|
||||
>
|
||||
Run Health Check
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onSync(instance.id)}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-1.5 text-xs"
|
||||
>
|
||||
Sync Now
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
<div className="mt-3 rounded border border-slate-100 bg-slate-50 p-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-slate-600">
|
||||
Health Panel
|
||||
</p>
|
||||
<div className="mt-2 grid gap-1 text-xs text-slate-600 sm:grid-cols-2">
|
||||
<p>
|
||||
Current Status:{" "}
|
||||
<span className="font-medium">
|
||||
{getHealthBadge(instance.health_status).label}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Last Checked:{" "}
|
||||
<span className="font-medium">
|
||||
{formatDateTime(instance.health_last_checked_at)}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Last Successful Check:{" "}
|
||||
<span className="font-medium">
|
||||
{formatDateTime(instance.health_last_ok_at)}
|
||||
</span>
|
||||
</p>
|
||||
<p>
|
||||
Latency:{" "}
|
||||
<span className="font-medium">
|
||||
{instance.health_last_latency_ms != null
|
||||
? `${instance.health_last_latency_ms} ms`
|
||||
: "—"}
|
||||
</span>
|
||||
</p>
|
||||
<p className="sm:col-span-2">
|
||||
Last Error:{" "}
|
||||
<span className="font-medium">
|
||||
{instance.health_last_error ?? "—"}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 overflow-x-auto">
|
||||
<table className="min-w-full text-left text-xs">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 text-slate-500">
|
||||
<th className="px-2 py-1">Time</th>
|
||||
<th className="px-2 py-1">Event</th>
|
||||
<th className="px-2 py-1">Result</th>
|
||||
<th className="px-2 py-1">Message</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(healthEventsByInstance[instance.id] ?? [])
|
||||
.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
className="px-2 py-2 text-slate-500"
|
||||
colSpan={4}
|
||||
>
|
||||
No health events yet.
|
||||
</td>
|
||||
</tr>
|
||||
),
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
(healthEventsByInstance[instance.id] ?? []).map(
|
||||
(event) => (
|
||||
<tr
|
||||
key={event.id}
|
||||
className="border-b border-slate-100 align-top"
|
||||
>
|
||||
<td className="px-2 py-1">
|
||||
{formatDateTime(event.created_at)}
|
||||
</td>
|
||||
<td className="px-2 py-1">
|
||||
{event.action}
|
||||
</td>
|
||||
<td className="px-2 py-1">
|
||||
{mapHealthResult(event.action)}
|
||||
</td>
|
||||
<td className="px-2 py-1">
|
||||
{event.error_message ?? "—"}
|
||||
{event.metadata ? (
|
||||
<details>
|
||||
<summary className="cursor-pointer text-[11px] text-brand-700">
|
||||
metadata
|
||||
</summary>
|
||||
<pre className="mt-1 max-w-[440px] overflow-auto rounded bg-white p-2 text-[10px] text-slate-700">
|
||||
{JSON.stringify(
|
||||
event.metadata,
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
),
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Subscription Action</label>
|
||||
<select
|
||||
value={actionSubId}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
||||
setActionSubId(e.target.value)
|
||||
}
|
||||
className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
|
||||
>
|
||||
{subscriptions.map((subscription) => (
|
||||
<option key={subscription.id} value={subscription.id}>
|
||||
{subscription.name ?? subscription.plesk_subscription_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
value={actionType}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
||||
setActionType(e.target.value as "suspend" | "unsuspend")
|
||||
}
|
||||
className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="suspend">Suspend</option>
|
||||
<option value="unsuspend">Unsuspend</option>
|
||||
</select>
|
||||
<button
|
||||
onClick={onSubscriptionAction}
|
||||
disabled={loading || !actionSubId}
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
>
|
||||
Execute Action
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">
|
||||
Subscription Action
|
||||
</label>
|
||||
<select
|
||||
value={actionSubId}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
||||
setActionSubId(e.target.value)
|
||||
}
|
||||
className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
|
||||
>
|
||||
{subscriptions.map((subscription) => (
|
||||
<option key={subscription.id} value={subscription.id}>
|
||||
{subscription.name ?? subscription.plesk_subscription_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
value={actionType}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) =>
|
||||
setActionType(e.target.value as "suspend" | "unsuspend")
|
||||
}
|
||||
className="w-full rounded border border-slate-300 px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="suspend">Suspend</option>
|
||||
<option value="unsuspend">Unsuspend</option>
|
||||
</select>
|
||||
<button
|
||||
onClick={onSubscriptionAction}
|
||||
disabled={loading || !actionSubId}
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
>
|
||||
Execute Action
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-2">
|
||||
<button
|
||||
onClick={onCheckout}
|
||||
disabled={loading}
|
||||
className="rounded bg-brand-600 px-3 py-2 text-sm text-white"
|
||||
>
|
||||
Start Checkout
|
||||
</button>
|
||||
<button
|
||||
onClick={onPortal}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
>
|
||||
Billing Portal
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-2">
|
||||
<button
|
||||
onClick={onCheckout}
|
||||
disabled={loading}
|
||||
className="rounded bg-brand-600 px-3 py-2 text-sm text-white"
|
||||
>
|
||||
Start Checkout
|
||||
</button>
|
||||
<button
|
||||
onClick={onPortal}
|
||||
disabled={loading}
|
||||
className="rounded border px-3 py-2 text-sm"
|
||||
>
|
||||
Billing Portal
|
||||
</button>
|
||||
</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 className="space-y-3 rounded-xl border border-slate-200 bg-white p-4 lg:col-span-2">
|
||||
|
||||
24
docker-compose.prod.yml
Normal file
24
docker-compose.prod.yml
Normal file
@@ -0,0 +1,24 @@
|
||||
services:
|
||||
web:
|
||||
container_name: plesk-agency-portal
|
||||
image: ${APP_IMAGE:-plesk-agency-portal:latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
ports:
|
||||
- "3000:3000"
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"node",
|
||||
"-e",
|
||||
"fetch('http://127.0.0.1:3000/api/health').then((r)=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))",
|
||||
]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 20s
|
||||
157
docs/deployment-production.md
Normal file
157
docs/deployment-production.md
Normal file
@@ -0,0 +1,157 @@
|
||||
# Production Deployment Runtime Foundation
|
||||
|
||||
This project can be deployed in a dedicated Proxmox container using Docker Compose. The files added here establish a minimal production runtime baseline without changing application business logic or Supabase security boundaries.
|
||||
|
||||
## Dockerfile purpose
|
||||
|
||||
The `Dockerfile` uses a multi-stage build on Node 20:
|
||||
|
||||
- installs dependencies
|
||||
- runs `next build`
|
||||
- prepares a lean runtime image with production dependencies
|
||||
- runs the app with `next start` on port `3000`
|
||||
|
||||
This keeps the runtime image small and focused on serving the built Next.js app.
|
||||
|
||||
## docker-compose.prod.yml purpose
|
||||
|
||||
`docker-compose.prod.yml` defines one service:
|
||||
|
||||
- service name: `web`
|
||||
- container name: `plesk-agency-portal`
|
||||
- restart policy: `unless-stopped`
|
||||
- environment from `.env`
|
||||
- port mapping `3000:3000`
|
||||
- health check against `/api/health`
|
||||
|
||||
## External Supabase requirement
|
||||
|
||||
Supabase remains external to this application container. The app container must only connect to Supabase via environment variables. No local Supabase container is included in this production compose file.
|
||||
|
||||
## Health endpoint usage
|
||||
|
||||
`GET /api/health` provides a fast, dependency-light runtime check for container orchestration and uptime checks.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:3000/api/health
|
||||
```
|
||||
|
||||
Expected response shape:
|
||||
|
||||
- `ok: true`
|
||||
- `service: "plesk-agency-portal"`
|
||||
- `timestamp`
|
||||
- `environment`
|
||||
|
||||
## Production environment expectations
|
||||
|
||||
Before deploying, set production-safe values in `.env` (using `.env.example` as the template), including:
|
||||
|
||||
- app URL and `NODE_ENV`
|
||||
- Supabase public and server credentials
|
||||
- Plesk credential encryption key
|
||||
- Stripe secrets
|
||||
- cron/job shared secrets
|
||||
|
||||
Keep secrets out of source control.
|
||||
|
||||
## Reverse proxy assumptions (Nginx Proxy Manager)
|
||||
|
||||
This app is expected to run behind a reverse proxy in production.
|
||||
|
||||
- TLS is terminated at the proxy.
|
||||
- Proxy forwards standard host/protocol headers (`Host`, `X-Forwarded-Proto`, `X-Forwarded-Host`).
|
||||
- Public origin is configured explicitly with `NEXT_PUBLIC_APP_URL`.
|
||||
|
||||
To keep callback behavior stable behind proxy layers, auth redirect responses use the configured application origin from environment configuration rather than relying only on request host detection.
|
||||
|
||||
## Callback URL expectations
|
||||
|
||||
- `NEXT_PUBLIC_APP_URL` must be set to the public HTTPS URL used by users.
|
||||
- Supabase auth redirect/callback configuration must allow:
|
||||
- `<NEXT_PUBLIC_APP_URL>/auth/callback`
|
||||
|
||||
The callback route also validates the `next` parameter as an internal path to prevent unsafe external redirects.
|
||||
|
||||
## Cron protection expectations
|
||||
|
||||
Operational cron endpoints are protected with a shared secret.
|
||||
|
||||
- Required header: `x-cron-secret`
|
||||
- Server secret source: `CRON_SHARED_SECRET`
|
||||
- Backward compatibility fallback: `CRON_SECRET`
|
||||
|
||||
For new production setups, set `CRON_SHARED_SECRET` and use that value for all cron callers.
|
||||
|
||||
## Jenkins pipeline flow
|
||||
|
||||
The repository includes a declarative `Jenkinsfile` with the following stages:
|
||||
|
||||
1. **Checkout**
|
||||
2. **Install dependencies** (`npm ci`)
|
||||
3. **Lint** (runs only when `package.json` contains a `lint` script)
|
||||
4. **Build application** (`npm run build`)
|
||||
5. **Build Docker image** (tags `latest` and `build-${BUILD_NUMBER}`)
|
||||
6. **Deploy** over SSH to the app host
|
||||
7. **Smoke check** against `/api/health`
|
||||
|
||||
## Required Jenkins configuration
|
||||
|
||||
Configure these values in Jenkins job/folder/global environment or credentials-backed environment variables:
|
||||
|
||||
- `DEPLOY_SSH_HOST` - remote app host
|
||||
- `DEPLOY_SSH_USER` - SSH user on remote host
|
||||
- `DEPLOY_SSH_CREDENTIAL_ID` - Jenkins SSH Agent credential ID
|
||||
- `DEPLOY_PATH` - remote deployment path (for example `/opt/plesk-agency-portal`)
|
||||
- `APP_BASE_URL` - externally reachable app URL used by smoke check
|
||||
|
||||
The pipeline assumes Jenkins credentials are managed outside this repository.
|
||||
|
||||
Jenkins runtime requirements:
|
||||
|
||||
- The pipeline must run on a Jenkins agent with the `docker` label.
|
||||
- That agent must have Docker CLI installed and permission to access Docker daemon/socket.
|
||||
- `rsync` and `ssh` must also be available on the Jenkins agent.
|
||||
|
||||
If Docker is missing or inaccessible, the pipeline now fails early in a dedicated preflight stage with an explicit message.
|
||||
|
||||
## Deploy flow
|
||||
|
||||
Deployment is intentionally simple and bash-based:
|
||||
|
||||
1. Jenkins builds Docker image tags locally.
|
||||
2. Jenkins syncs deployment files (`docker-compose.prod.yml`, deploy/smoke/rollback scripts) to the remote deploy path.
|
||||
3. Jenkins streams Docker images to the remote host (`docker save | ssh docker load`).
|
||||
4. Jenkins runs `scripts/deploy-prod.sh` remotely.
|
||||
5. Script applies the selected image tag via:
|
||||
|
||||
```bash
|
||||
APP_IMAGE=<tag> docker compose -f docker-compose.prod.yml up -d --no-build
|
||||
```
|
||||
|
||||
6. Script prints `docker compose ps` status.
|
||||
|
||||
## Rollback flow
|
||||
|
||||
Rollback uses `scripts/rollback-prod.sh` with a previously built image tag:
|
||||
|
||||
```bash
|
||||
DEPLOY_PATH=/opt/plesk-agency-portal \
|
||||
APP_BASE_URL=https://your-app.example.com \
|
||||
scripts/rollback-prod.sh plesk-agency-portal:build-123
|
||||
```
|
||||
|
||||
Rollback redeploys that image with compose, then immediately reruns smoke checks.
|
||||
|
||||
## Smoke check behavior
|
||||
|
||||
`scripts/smoke-check.sh`:
|
||||
|
||||
- accepts a base URL argument
|
||||
- requests `${BASE_URL}/api/health`
|
||||
- fails on non-200 responses
|
||||
- fails on invalid JSON or missing expected fields (`ok: true`, `service` string)
|
||||
|
||||
This gives a quick post-deploy validation gate for both deploy and rollback operations.
|
||||
17
lib/env.ts
17
lib/env.ts
@@ -3,6 +3,18 @@ const requiredEnvs = [
|
||||
"NEXT_PUBLIC_SUPABASE_ANON_KEY",
|
||||
] as const;
|
||||
|
||||
const configuredAppUrl = process.env.NEXT_PUBLIC_APP_URL?.trim();
|
||||
|
||||
function getAppOrigin() {
|
||||
if (!configuredAppUrl) return "http://localhost:3000";
|
||||
|
||||
try {
|
||||
return new URL(configuredAppUrl).origin;
|
||||
} catch {
|
||||
return "http://localhost:3000";
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of requiredEnvs) {
|
||||
if (!process.env[key]) {
|
||||
// Keep as runtime warning for smoother local setup.
|
||||
@@ -12,9 +24,12 @@ for (const key of requiredEnvs) {
|
||||
}
|
||||
|
||||
export const env = {
|
||||
appUrl: process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000",
|
||||
appUrl: configuredAppUrl ?? "http://localhost:3000",
|
||||
appOrigin: getAppOrigin(),
|
||||
jobSecret: process.env.JOB_SECRET ?? "",
|
||||
cronSecret: process.env.CRON_SECRET ?? "",
|
||||
cronSharedSecret:
|
||||
process.env.CRON_SHARED_SECRET ?? process.env.CRON_SECRET ?? "",
|
||||
encryptionKey: process.env.ENCRYPTION_KEY ?? "",
|
||||
pleskCredEncKey: process.env.PLESK_CRED_ENC_KEY ?? "",
|
||||
stripeSecretKey: process.env.STRIPE_SECRET_KEY ?? "",
|
||||
|
||||
@@ -11,7 +11,7 @@ export function getStripeClient() {
|
||||
|
||||
if (!stripeClient) {
|
||||
stripeClient = new Stripe(env.stripeSecretKey, {
|
||||
apiVersion: "2025-02-24.acacia",
|
||||
apiVersion: "2025-08-27.basil",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
30
scripts/deploy-prod.sh
Executable file
30
scripts/deploy-prod.sh
Executable file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
DEPLOY_PATH="${DEPLOY_PATH:-/opt/plesk-agency-portal}"
|
||||
APP_IMAGE="${APP_IMAGE:-plesk-agency-portal:latest}"
|
||||
SOURCE_PATH="${SOURCE_PATH:-${DEPLOY_PATH}}"
|
||||
|
||||
mkdir -p "${DEPLOY_PATH}"
|
||||
|
||||
for file in docker-compose.prod.yml deploy-prod.sh smoke-check.sh rollback-prod.sh; do
|
||||
if [ -f "${SOURCE_PATH}/${file}" ]; then
|
||||
cp "${SOURCE_PATH}/${file}" "${DEPLOY_PATH}/${file}"
|
||||
fi
|
||||
done
|
||||
|
||||
chmod +x "${DEPLOY_PATH}/deploy-prod.sh" \
|
||||
"${DEPLOY_PATH}/smoke-check.sh" \
|
||||
"${DEPLOY_PATH}/rollback-prod.sh" 2>/dev/null || true
|
||||
|
||||
if [ ! -f "${DEPLOY_PATH}/docker-compose.prod.yml" ]; then
|
||||
echo "Missing docker-compose.prod.yml in ${DEPLOY_PATH}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd "${DEPLOY_PATH}"
|
||||
|
||||
APP_IMAGE="${APP_IMAGE}" docker compose -f docker-compose.prod.yml up -d --no-build
|
||||
|
||||
docker compose -f docker-compose.prod.yml ps
|
||||
30
scripts/rollback-prod.sh
Executable file
30
scripts/rollback-prod.sh
Executable file
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PREVIOUS_IMAGE_TAG="${1:-}"
|
||||
DEPLOY_PATH="${DEPLOY_PATH:-/opt/plesk-agency-portal}"
|
||||
APP_BASE_URL="${APP_BASE_URL:-}"
|
||||
|
||||
if [ -z "${PREVIOUS_IMAGE_TAG}" ]; then
|
||||
echo "Usage: $0 <previous-image-tag>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${APP_BASE_URL}" ]; then
|
||||
echo "APP_BASE_URL is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "${DEPLOY_PATH}/docker-compose.prod.yml" ]; then
|
||||
echo "Missing docker-compose.prod.yml in ${DEPLOY_PATH}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd "${DEPLOY_PATH}"
|
||||
|
||||
APP_IMAGE="${PREVIOUS_IMAGE_TAG}" docker compose -f docker-compose.prod.yml up -d --no-build
|
||||
|
||||
"${DEPLOY_PATH}/smoke-check.sh" "${APP_BASE_URL}"
|
||||
|
||||
docker compose -f docker-compose.prod.yml ps
|
||||
27
scripts/smoke-check.sh
Executable file
27
scripts/smoke-check.sh
Executable file
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
BASE_URL="${1:-}"
|
||||
|
||||
if [ -z "${BASE_URL}" ]; then
|
||||
echo "Usage: $0 <base-url>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
URL="${BASE_URL%/}/api/health"
|
||||
TMP_FILE="$(mktemp)"
|
||||
|
||||
trap 'rm -f "${TMP_FILE}"' EXIT
|
||||
|
||||
HTTP_CODE=$(curl -sS -o "${TMP_FILE}" -w "%{http_code}" "${URL}")
|
||||
|
||||
if [ "${HTTP_CODE}" != "200" ]; then
|
||||
echo "Smoke check failed: ${URL} returned ${HTTP_CODE}" >&2
|
||||
cat "${TMP_FILE}" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node -e "const fs=require('fs');const d=JSON.parse(fs.readFileSync(process.argv[1],'utf8'));if(d?.ok!==true||typeof d?.service!=='string'){process.exit(1)}" "${TMP_FILE}"
|
||||
|
||||
echo "Smoke check passed: ${URL}"
|
||||
Reference in New Issue
Block a user