Compare commits
10 Commits
fix/action
...
fix/plesk-
| Author | SHA1 | Date | |
|---|---|---|---|
| c528392682 | |||
| a678713d1d | |||
| 033d816d42 | |||
| a22fc2c4d2 | |||
| 825bf8dc84 | |||
| 2c52d89dc9 | |||
| cc7e30092d | |||
| ce8b04285a | |||
| a49448c04b | |||
| dceccecf0c |
@@ -5,6 +5,8 @@ import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
|||||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||||
import { assertSameOrigin } from "@/lib/api/security";
|
import { assertSameOrigin } from "@/lib/api/security";
|
||||||
import {
|
import {
|
||||||
|
parseSubscriptionStatusDetailsFromInfo,
|
||||||
|
pleskCliCall,
|
||||||
suspendPleskSubscription,
|
suspendPleskSubscription,
|
||||||
unsuspendPleskSubscription,
|
unsuspendPleskSubscription,
|
||||||
} from "@/lib/plesk/client";
|
} from "@/lib/plesk/client";
|
||||||
@@ -12,6 +14,7 @@ import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
|||||||
|
|
||||||
const actionSchema = z.object({
|
const actionSchema = z.object({
|
||||||
action: z.enum(["suspend", "unsuspend"]),
|
action: z.enum(["suspend", "unsuspend"]),
|
||||||
|
subscription_id: z.string().uuid().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
@@ -22,7 +25,11 @@ export async function POST(
|
|||||||
let context: Awaited<ReturnType<typeof getRouteAgencyContextOrThrow>> | null =
|
let context: Awaited<ReturnType<typeof getRouteAgencyContextOrThrow>> | null =
|
||||||
null;
|
null;
|
||||||
let domain: { id: string; subscription_id: string | null } | null = null;
|
let domain: { id: string; subscription_id: string | null } | null = null;
|
||||||
let subscription: { id: string; plesk_subscription_id: string } | null = null;
|
let subscription: {
|
||||||
|
id: string;
|
||||||
|
plesk_subscription_id: string;
|
||||||
|
plesk_instance_id: string;
|
||||||
|
} | null = null;
|
||||||
let requestedAction: "suspend" | "unsuspend" | null = null;
|
let requestedAction: "suspend" | "unsuspend" | null = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -32,7 +39,8 @@ export async function POST(
|
|||||||
assertAgencyAdmin(context);
|
assertAgencyAdmin(context);
|
||||||
assertRateLimit(`plesk-domain-action:${context.userId}`, 10, 60_000);
|
assertRateLimit(`plesk-domain-action:${context.userId}`, 10, 60_000);
|
||||||
|
|
||||||
const { action } = actionSchema.parse(await req.json());
|
const payload = actionSchema.parse(await req.json());
|
||||||
|
const { action } = payload;
|
||||||
requestedAction = action;
|
requestedAction = action;
|
||||||
|
|
||||||
const { data: domainRow, error: domainError } = await supabase
|
const { data: domainRow, error: domainError } = await supabase
|
||||||
@@ -46,21 +54,23 @@ export async function POST(
|
|||||||
throw new Error("Domain not found");
|
throw new Error("Domain not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const resolvedSubscriptionId =
|
||||||
|
payload.subscription_id ??
|
||||||
|
(domainRow.subscription_id ? String(domainRow.subscription_id) : null);
|
||||||
|
|
||||||
domain = {
|
domain = {
|
||||||
id: String(domainRow.id),
|
id: String(domainRow.id),
|
||||||
subscription_id: domainRow.subscription_id
|
subscription_id: resolvedSubscriptionId,
|
||||||
? String(domainRow.subscription_id)
|
|
||||||
: null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!domain.subscription_id) {
|
if (!resolvedSubscriptionId) {
|
||||||
throw new Error("Domain is not linked to a subscription");
|
throw new Error("Domain is not linked to a subscription");
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data: subscriptionRow, error: subscriptionError } = await supabase
|
const { data: subscriptionRow, error: subscriptionError } = await supabase
|
||||||
.from("plesk_subscriptions")
|
.from("plesk_subscriptions")
|
||||||
.select("id, plesk_subscription_id, plesk_instance_id")
|
.select("id, plesk_subscription_id, plesk_instance_id")
|
||||||
.eq("id", domain.subscription_id)
|
.eq("id", resolvedSubscriptionId)
|
||||||
.eq("agency_id", context.agencyId)
|
.eq("agency_id", context.agencyId)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
@@ -71,6 +81,7 @@ export async function POST(
|
|||||||
subscription = {
|
subscription = {
|
||||||
id: String(subscriptionRow.id),
|
id: String(subscriptionRow.id),
|
||||||
plesk_subscription_id: String(subscriptionRow.plesk_subscription_id),
|
plesk_subscription_id: String(subscriptionRow.plesk_subscription_id),
|
||||||
|
plesk_instance_id: String(subscriptionRow.plesk_instance_id),
|
||||||
};
|
};
|
||||||
|
|
||||||
const { data: instance, error: instanceError } = await supabase
|
const { data: instance, error: instanceError } = await supabase
|
||||||
@@ -102,6 +113,61 @@ export async function POST(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fallbackStatus = action === "suspend" ? "suspended" : "active";
|
||||||
|
let refreshedStatus = fallbackStatus;
|
||||||
|
let refreshedStatusRaw: string | null = null;
|
||||||
|
let refreshErrorMessage: string | null = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const infoResult = await pleskCliCall(connection, "subscription", [
|
||||||
|
"--info",
|
||||||
|
subscription.plesk_subscription_id,
|
||||||
|
]);
|
||||||
|
const parsed = parseSubscriptionStatusDetailsFromInfo(
|
||||||
|
infoResult.stdout ?? "",
|
||||||
|
);
|
||||||
|
refreshedStatus = parsed.status;
|
||||||
|
refreshedStatusRaw = parsed.statusRaw;
|
||||||
|
} catch (refreshError) {
|
||||||
|
refreshErrorMessage =
|
||||||
|
refreshError instanceof Error
|
||||||
|
? refreshError.message.slice(0, 1000)
|
||||||
|
: "subscription_status_refresh_failed";
|
||||||
|
|
||||||
|
await supabase.from("actions_log").insert({
|
||||||
|
agency_id: context.agencyId,
|
||||||
|
actor_user_id: context.userId,
|
||||||
|
target_type: "plesk_subscription",
|
||||||
|
target_id: subscription.id,
|
||||||
|
action: "subscription_status_refresh_failed",
|
||||||
|
status: "failed",
|
||||||
|
error_message: refreshErrorMessage,
|
||||||
|
metadata: {
|
||||||
|
subscription_id: subscription.id,
|
||||||
|
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||||
|
plesk_instance_id: subscription.plesk_instance_id,
|
||||||
|
source: "domain_action",
|
||||||
|
domain_id: domain.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await supabase
|
||||||
|
.from("plesk_subscriptions")
|
||||||
|
.update({
|
||||||
|
status: refreshedStatus,
|
||||||
|
status_raw: refreshedStatusRaw,
|
||||||
|
last_status_sync_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq("id", subscription.id)
|
||||||
|
.eq("agency_id", context.agencyId);
|
||||||
|
|
||||||
|
await supabase
|
||||||
|
.from("plesk_domains")
|
||||||
|
.update({ status: refreshedStatus })
|
||||||
|
.eq("agency_id", context.agencyId)
|
||||||
|
.eq("subscription_id", subscription.id);
|
||||||
|
|
||||||
await supabase.from("actions_log").insert({
|
await supabase.from("actions_log").insert({
|
||||||
agency_id: context.agencyId,
|
agency_id: context.agencyId,
|
||||||
actor_user_id: context.userId,
|
actor_user_id: context.userId,
|
||||||
@@ -113,6 +179,8 @@ export async function POST(
|
|||||||
domain_id: domain.id,
|
domain_id: domain.id,
|
||||||
subscription_id: subscription.id,
|
subscription_id: subscription.id,
|
||||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||||
|
refreshed_status: refreshedStatus,
|
||||||
|
refresh_error: refreshErrorMessage,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
51
app/api/plesk/instances/[id]/backfill-domain-links/route.ts
Normal file
51
app/api/plesk/instances/[id]/backfill-domain-links/route.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||||
|
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||||
|
import { assertSameOrigin } from "@/lib/api/security";
|
||||||
|
import { backfillDomainSubscriptionLinks } from "@/lib/plesk/sync";
|
||||||
|
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: Request,
|
||||||
|
{ params }: { params: { id: string } },
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
assertSameOrigin(req);
|
||||||
|
|
||||||
|
const context = await getRouteAgencyContextOrThrow();
|
||||||
|
assertAgencyAdmin(context);
|
||||||
|
assertRateLimit(`plesk-backfill-links:${context.userId}`, 5, 60_000);
|
||||||
|
|
||||||
|
const supabase = createSupabaseRouteClient() as any;
|
||||||
|
|
||||||
|
const { data: instance, error: instanceError } = await supabase
|
||||||
|
.from("plesk_instances")
|
||||||
|
.select("id")
|
||||||
|
.eq("id", params.id)
|
||||||
|
.eq("agency_id", context.agencyId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (instanceError || !instance) {
|
||||||
|
throw new Error("Plesk instance not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await backfillDomainSubscriptionLinks(supabase, {
|
||||||
|
agencyId: context.agencyId,
|
||||||
|
instanceId: params.id,
|
||||||
|
actorUserId: context.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, ...result });
|
||||||
|
} catch (error) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Backfill domain links failed",
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,22 @@ function normalizeDomainLike(value: string) {
|
|||||||
return value.trim().toLowerCase().replace(/\.$/, "");
|
return value.trim().toLowerCase().replace(/\.$/, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function findBestSuffixStatusMatch(
|
||||||
|
normalizedDomain: string,
|
||||||
|
candidates: Array<{ normalizedName: string; status: string | null }>,
|
||||||
|
) {
|
||||||
|
let best: { normalizedName: string; status: string | null } | null = null;
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (!normalizedDomain.endsWith(`.${candidate.normalizedName}`)) continue;
|
||||||
|
if (!best || candidate.normalizedName.length > best.normalizedName.length) {
|
||||||
|
best = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best?.status ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
const context = await getServerAgencyContextOrRedirect();
|
const context = await getServerAgencyContextOrRedirect();
|
||||||
const supabase = createSupabaseServerClient() as any;
|
const supabase = createSupabaseServerClient() as any;
|
||||||
@@ -118,14 +134,6 @@ export default async function DashboardPage() {
|
|||||||
{ data: ActionLogSummary[] | null },
|
{ data: ActionLogSummary[] | null },
|
||||||
];
|
];
|
||||||
|
|
||||||
const domainSubscriptionIds = Array.from(
|
|
||||||
new Set(
|
|
||||||
(domains ?? [])
|
|
||||||
.map((domain) => domain.subscription_id)
|
|
||||||
.filter((id): id is string => Boolean(id)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const domainInstanceIds = Array.from(
|
const domainInstanceIds = Array.from(
|
||||||
new Set((domains ?? []).map((domain) => domain.plesk_instance_id)),
|
new Set((domains ?? []).map((domain) => domain.plesk_instance_id)),
|
||||||
);
|
);
|
||||||
@@ -171,6 +179,24 @@ export default async function DashboardPage() {
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const subscriptionStatusNameCandidatesByInstance = new Map<
|
||||||
|
string,
|
||||||
|
Array<{ normalizedName: string; status: string | null }>
|
||||||
|
>();
|
||||||
|
|
||||||
|
for (const subscription of domainSubscriptions ?? []) {
|
||||||
|
if (!subscription?.plesk_instance_id || !subscription?.name) continue;
|
||||||
|
|
||||||
|
const instanceId = String(subscription.plesk_instance_id);
|
||||||
|
const existing =
|
||||||
|
subscriptionStatusNameCandidatesByInstance.get(instanceId) ?? [];
|
||||||
|
existing.push({
|
||||||
|
normalizedName: normalizeDomainLike(String(subscription.name)),
|
||||||
|
status: subscription?.status ? String(subscription.status) : null,
|
||||||
|
});
|
||||||
|
subscriptionStatusNameCandidatesByInstance.set(instanceId, existing);
|
||||||
|
}
|
||||||
|
|
||||||
const autoSyncByInstance = new Map<
|
const autoSyncByInstance = new Map<
|
||||||
string,
|
string,
|
||||||
{ status: string; created_at: string; error_message: string | null }
|
{ status: string; created_at: string; error_message: string | null }
|
||||||
@@ -237,10 +263,17 @@ export default async function DashboardPage() {
|
|||||||
const joinedStatusByName = subscriptionStatusByInstanceAndName.get(
|
const joinedStatusByName = subscriptionStatusByInstanceAndName.get(
|
||||||
`${domain.plesk_instance_id}:${normalizeDomainLike(domain.domain_name)}`,
|
`${domain.plesk_instance_id}:${normalizeDomainLike(domain.domain_name)}`,
|
||||||
);
|
);
|
||||||
|
const joinedStatusBySuffix = findBestSuffixStatusMatch(
|
||||||
|
normalizeDomainLike(domain.domain_name),
|
||||||
|
subscriptionStatusNameCandidatesByInstance.get(
|
||||||
|
domain.plesk_instance_id,
|
||||||
|
) ?? [],
|
||||||
|
);
|
||||||
const joinedStatus =
|
const joinedStatus =
|
||||||
joinedStatusByLocalId ??
|
joinedStatusByLocalId ??
|
||||||
joinedStatusByExternalId ??
|
joinedStatusByExternalId ??
|
||||||
joinedStatusByName;
|
joinedStatusByName ??
|
||||||
|
joinedStatusBySuffix;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...domain,
|
...domain,
|
||||||
|
|||||||
@@ -239,13 +239,23 @@ export function DashboardControls({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function onDomainAction(
|
async function onDomainAction(
|
||||||
domainId: string,
|
domain: Domain,
|
||||||
action: "suspend" | "unsuspend",
|
action: "suspend" | "unsuspend",
|
||||||
) {
|
) {
|
||||||
|
if (!domain.subscription_id) {
|
||||||
|
setMessage(
|
||||||
|
"Domain is not linked to a subscription yet. Run Sync Now (or backfill links) and try again.",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMessage(null);
|
setMessage(null);
|
||||||
try {
|
try {
|
||||||
await runRequest(`/api/plesk/domains/${domainId}/action`, { action });
|
await runRequest(`/api/plesk/domains/${domain.id}/action`, {
|
||||||
|
action,
|
||||||
|
subscription_id: domain.subscription_id,
|
||||||
|
});
|
||||||
setMessage("Domain action completed.");
|
setMessage("Domain action completed.");
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -633,7 +643,7 @@ export function DashboardControls({
|
|||||||
<td className="px-2 py-2">
|
<td className="px-2 py-2">
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={() => onDomainAction(domain.id, "suspend")}
|
onClick={() => onDomainAction(domain, "suspend")}
|
||||||
disabled={
|
disabled={
|
||||||
loading || isDomainSuspended(domain.status)
|
loading || isDomainSuspended(domain.status)
|
||||||
}
|
}
|
||||||
@@ -642,9 +652,7 @@ export function DashboardControls({
|
|||||||
Suspend
|
Suspend
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() =>
|
onClick={() => onDomainAction(domain, "unsuspend")}
|
||||||
onDomainAction(domain.id, "unsuspend")
|
|
||||||
}
|
|
||||||
disabled={loading || isDomainActive(domain.status)}
|
disabled={loading || isDomainActive(domain.status)}
|
||||||
className="rounded border border-emerald-300 px-2 py-1 text-xs text-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
className="rounded border border-emerald-300 px-2 py-1 text-xs text-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -289,7 +289,7 @@ export async function unsuspendPleskSubscription(
|
|||||||
subscriptionName: string,
|
subscriptionName: string,
|
||||||
) {
|
) {
|
||||||
return pleskCliCall(connection, "subscription", [
|
return pleskCliCall(connection, "subscription", [
|
||||||
"--webspace-on",
|
"--unsuspend",
|
||||||
subscriptionName,
|
subscriptionName,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,25 @@ type LocalSubscriptionLookupRow = {
|
|||||||
|
|
||||||
const MIN_INTERVAL_MS = 3 * 60 * 1000;
|
const MIN_INTERVAL_MS = 3 * 60 * 1000;
|
||||||
|
|
||||||
|
function normalizeDomainLike(value: string) {
|
||||||
|
return value.trim().toLowerCase().replace(/\.$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function findBestSuffixSubscriptionMatch<
|
||||||
|
T extends { normalizedName: string; id: string; status: string | null },
|
||||||
|
>(normalizedDomain: string, candidates: T[]) {
|
||||||
|
let best: T | undefined;
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (!normalizedDomain.endsWith(`.${candidate.normalizedName}`)) continue;
|
||||||
|
if (!best || candidate.normalizedName.length > best.normalizedName.length) {
|
||||||
|
best = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
export async function syncPleskInstance(
|
export async function syncPleskInstance(
|
||||||
supabase: SupabaseLike,
|
supabase: SupabaseLike,
|
||||||
instance: InstanceRow,
|
instance: InstanceRow,
|
||||||
@@ -213,13 +232,30 @@ export async function syncPleskInstance(
|
|||||||
>(
|
>(
|
||||||
subscriptionsIndexed
|
subscriptionsIndexed
|
||||||
.filter((row) => row.name)
|
.filter((row) => row.name)
|
||||||
.map((row) => [String(row.name).trim().toLowerCase(), row]),
|
.map((row) => [normalizeDomainLike(String(row.name)), row]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const subscriptionNameCandidates: Array<{
|
||||||
|
id: string;
|
||||||
|
pleskSubscriptionId: string;
|
||||||
|
status: string | null;
|
||||||
|
normalizedName: string;
|
||||||
|
}> = subscriptionsIndexed
|
||||||
|
.filter((row) => row.name)
|
||||||
|
.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
pleskSubscriptionId: row.pleskSubscriptionId,
|
||||||
|
status: row.status,
|
||||||
|
normalizedName: normalizeDomainLike(String(row.name)),
|
||||||
|
}));
|
||||||
|
|
||||||
const domainsForUpsert = domainsRaw
|
const domainsForUpsert = domainsRaw
|
||||||
.map((item: any) => {
|
.map((item: any) => {
|
||||||
const domainId = item?.id ?? item?.guid ?? item?.name;
|
const domainId = item?.id ?? item?.guid ?? item?.name;
|
||||||
const domainName = item?.name ?? item?.domain_name ?? item?.domain;
|
const domainName = item?.name ?? item?.domain_name ?? item?.domain;
|
||||||
|
const normalizedDomainName = domainName
|
||||||
|
? normalizeDomainLike(String(domainName))
|
||||||
|
: null;
|
||||||
const subExternalId =
|
const subExternalId =
|
||||||
item?.subscription?.id ?? item?.subscription_id ?? item?.webspace_id;
|
item?.subscription?.id ?? item?.subscription_id ?? item?.webspace_id;
|
||||||
const rawExternalSubscriptionId = subExternalId
|
const rawExternalSubscriptionId = subExternalId
|
||||||
@@ -240,13 +276,24 @@ export async function syncPleskInstance(
|
|||||||
: undefined;
|
: undefined;
|
||||||
const localSubscriptionByName = subscriptionNameHint
|
const localSubscriptionByName = subscriptionNameHint
|
||||||
? subscriptionByName.get(
|
? subscriptionByName.get(
|
||||||
String(subscriptionNameHint).trim().toLowerCase(),
|
normalizeDomainLike(String(subscriptionNameHint)),
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
const localSubscriptionByDomainName = normalizedDomainName
|
||||||
|
? subscriptionByName.get(normalizedDomainName)
|
||||||
|
: undefined;
|
||||||
|
const localSubscriptionBySuffix = normalizedDomainName
|
||||||
|
? findBestSuffixSubscriptionMatch(
|
||||||
|
normalizedDomainName,
|
||||||
|
subscriptionNameCandidates,
|
||||||
)
|
)
|
||||||
: undefined;
|
: undefined;
|
||||||
const localSubscription =
|
const localSubscription =
|
||||||
localSubscriptionByExternal ??
|
localSubscriptionByExternal ??
|
||||||
localSubscriptionByLocalId ??
|
localSubscriptionByLocalId ??
|
||||||
localSubscriptionByName;
|
localSubscriptionByName ??
|
||||||
|
localSubscriptionByDomainName ??
|
||||||
|
localSubscriptionBySuffix;
|
||||||
|
|
||||||
const externalSubscriptionId = localSubscription
|
const externalSubscriptionId = localSubscription
|
||||||
? localSubscription.pleskSubscriptionId
|
? localSubscription.pleskSubscriptionId
|
||||||
@@ -281,6 +328,10 @@ export async function syncPleskInstance(
|
|||||||
})
|
})
|
||||||
.filter(Boolean) as Array<Record<string, unknown>>;
|
.filter(Boolean) as Array<Record<string, unknown>>;
|
||||||
|
|
||||||
|
const unlinkedDomains = domainsForUpsert.filter(
|
||||||
|
(domain) => !domain.subscription_id,
|
||||||
|
);
|
||||||
|
|
||||||
if (domainsForUpsert.length > 0) {
|
if (domainsForUpsert.length > 0) {
|
||||||
const { error } = await supabase
|
const { error } = await supabase
|
||||||
.from("plesk_domains")
|
.from("plesk_domains")
|
||||||
@@ -315,6 +366,10 @@ export async function syncPleskInstance(
|
|||||||
metadata: {
|
metadata: {
|
||||||
subscriptions_seen: subscriptionsRaw.length,
|
subscriptions_seen: subscriptionsRaw.length,
|
||||||
domains_seen: domainsRaw.length,
|
domains_seen: domainsRaw.length,
|
||||||
|
unlinked_domains: unlinkedDomains.length,
|
||||||
|
unlinked_domain_samples: unlinkedDomains
|
||||||
|
.slice(0, 25)
|
||||||
|
.map((domain) => String(domain.domain_name ?? "unknown")),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -387,3 +442,146 @@ export async function syncPleskInstance(
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function backfillDomainSubscriptionLinks(
|
||||||
|
supabase: SupabaseLike,
|
||||||
|
input: {
|
||||||
|
agencyId: string;
|
||||||
|
instanceId: string;
|
||||||
|
actorUserId?: string | null;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const { agencyId, instanceId, actorUserId } = input;
|
||||||
|
|
||||||
|
const { data: subscriptions, error: subscriptionsError } = await supabase
|
||||||
|
.from("plesk_subscriptions")
|
||||||
|
.select("id, plesk_subscription_id, name, status")
|
||||||
|
.eq("agency_id", agencyId)
|
||||||
|
.eq("plesk_instance_id", instanceId);
|
||||||
|
|
||||||
|
if (subscriptionsError) {
|
||||||
|
throw new Error(subscriptionsError.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: domains, error: domainsError } = await supabase
|
||||||
|
.from("plesk_domains")
|
||||||
|
.select("id, domain_name, external_subscription_id, subscription_id")
|
||||||
|
.eq("agency_id", agencyId)
|
||||||
|
.eq("plesk_instance_id", instanceId)
|
||||||
|
.is("subscription_id", null);
|
||||||
|
|
||||||
|
if (domainsError) {
|
||||||
|
throw new Error(domainsError.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const subscriptionByExternalId = new Map<
|
||||||
|
string,
|
||||||
|
{ id: string; status: string }
|
||||||
|
>(
|
||||||
|
(subscriptions ?? [])
|
||||||
|
.filter((subscription: any) => subscription?.plesk_subscription_id)
|
||||||
|
.map((subscription: any) => [
|
||||||
|
String(subscription.plesk_subscription_id),
|
||||||
|
{
|
||||||
|
id: String(subscription.id),
|
||||||
|
status: subscription?.status
|
||||||
|
? String(subscription.status)
|
||||||
|
: "unknown",
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const subscriptionByName = new Map<string, { id: string; status: string }>(
|
||||||
|
(subscriptions ?? [])
|
||||||
|
.filter((subscription: any) => subscription?.name)
|
||||||
|
.map((subscription: any) => [
|
||||||
|
normalizeDomainLike(String(subscription.name)),
|
||||||
|
{
|
||||||
|
id: String(subscription.id),
|
||||||
|
status: subscription?.status
|
||||||
|
? String(subscription.status)
|
||||||
|
: "unknown",
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const subscriptionNameCandidates: Array<{
|
||||||
|
id: string;
|
||||||
|
status: string;
|
||||||
|
normalizedName: string;
|
||||||
|
}> = (subscriptions ?? [])
|
||||||
|
.filter((subscription: any) => subscription?.name)
|
||||||
|
.map((subscription: any) => ({
|
||||||
|
id: String(subscription.id),
|
||||||
|
status: subscription?.status ? String(subscription.status) : "unknown",
|
||||||
|
normalizedName: normalizeDomainLike(String(subscription.name)),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let linkedCount = 0;
|
||||||
|
const failures: Array<{ domain_id: string; error: string }> = [];
|
||||||
|
|
||||||
|
for (const domain of domains ?? []) {
|
||||||
|
const matchByExternal = domain?.external_subscription_id
|
||||||
|
? subscriptionByExternalId.get(String(domain.external_subscription_id))
|
||||||
|
: undefined;
|
||||||
|
const matchByDomainName = domain?.domain_name
|
||||||
|
? subscriptionByName.get(normalizeDomainLike(String(domain.domain_name)))
|
||||||
|
: undefined;
|
||||||
|
const normalizedDomainName = domain?.domain_name
|
||||||
|
? normalizeDomainLike(String(domain.domain_name))
|
||||||
|
: null;
|
||||||
|
const matchBySuffix = normalizedDomainName
|
||||||
|
? findBestSuffixSubscriptionMatch(
|
||||||
|
normalizedDomainName,
|
||||||
|
subscriptionNameCandidates,
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
const linkedSubscription =
|
||||||
|
matchByExternal ?? matchByDomainName ?? matchBySuffix;
|
||||||
|
|
||||||
|
if (!linkedSubscription) continue;
|
||||||
|
|
||||||
|
const { error: updateError } = await supabase
|
||||||
|
.from("plesk_domains")
|
||||||
|
.update({
|
||||||
|
subscription_id: linkedSubscription.id,
|
||||||
|
status: linkedSubscription.status,
|
||||||
|
})
|
||||||
|
.eq("id", domain.id)
|
||||||
|
.eq("agency_id", agencyId);
|
||||||
|
|
||||||
|
if (updateError) {
|
||||||
|
failures.push({
|
||||||
|
domain_id: String(domain.id),
|
||||||
|
error: updateError.message,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
linkedCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
await supabase.from("actions_log").insert({
|
||||||
|
agency_id: agencyId,
|
||||||
|
actor_user_id: actorUserId ?? null,
|
||||||
|
target_type: "plesk_instance",
|
||||||
|
target_id: instanceId,
|
||||||
|
action: "domain_subscription_backfill",
|
||||||
|
status: failures.length > 0 ? "failed" : "success",
|
||||||
|
error_message:
|
||||||
|
failures.length > 0
|
||||||
|
? `${failures.length} domain links failed during backfill`
|
||||||
|
: null,
|
||||||
|
metadata: {
|
||||||
|
attempted: (domains ?? []).length,
|
||||||
|
linked: linkedCount,
|
||||||
|
failures: failures.slice(0, 25),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
attempted: (domains ?? []).length,
|
||||||
|
linked: linkedCount,
|
||||||
|
failed: failures.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user