Compare commits
16 Commits
feature/cl
...
fix/unsusp
| Author | SHA1 | Date | |
|---|---|---|---|
| 033d816d42 | |||
| a22fc2c4d2 | |||
| 825bf8dc84 | |||
| 2c52d89dc9 | |||
| cc7e30092d | |||
| ce8b04285a | |||
| ed31598a1d | |||
| a49448c04b | |||
| dceccecf0c | |||
| 8e5d9865ac | |||
| ee9b90e3d1 | |||
| ea671336d3 | |||
| 0d914f5973 | |||
| fbeb089b9e | |||
| 269c9e47c9 | |||
| c9e3fe1dbc |
@@ -5,6 +5,8 @@ import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||
import { assertSameOrigin } from "@/lib/api/security";
|
||||
import {
|
||||
parseSubscriptionStatusDetailsFromInfo,
|
||||
pleskCliCall,
|
||||
suspendPleskSubscription,
|
||||
unsuspendPleskSubscription,
|
||||
} from "@/lib/plesk/client";
|
||||
@@ -12,6 +14,7 @@ import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||
|
||||
const actionSchema = z.object({
|
||||
action: z.enum(["suspend", "unsuspend"]),
|
||||
subscription_id: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
export async function POST(
|
||||
@@ -22,7 +25,11 @@ export async function POST(
|
||||
let context: Awaited<ReturnType<typeof getRouteAgencyContextOrThrow>> | 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;
|
||||
|
||||
try {
|
||||
@@ -32,7 +39,8 @@ export async function POST(
|
||||
assertAgencyAdmin(context);
|
||||
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;
|
||||
|
||||
const { data: domainRow, error: domainError } = await supabase
|
||||
@@ -46,21 +54,23 @@ export async function POST(
|
||||
throw new Error("Domain not found");
|
||||
}
|
||||
|
||||
const resolvedSubscriptionId =
|
||||
payload.subscription_id ??
|
||||
(domainRow.subscription_id ? String(domainRow.subscription_id) : null);
|
||||
|
||||
domain = {
|
||||
id: String(domainRow.id),
|
||||
subscription_id: domainRow.subscription_id
|
||||
? String(domainRow.subscription_id)
|
||||
: null,
|
||||
subscription_id: resolvedSubscriptionId,
|
||||
};
|
||||
|
||||
if (!domain.subscription_id) {
|
||||
if (!resolvedSubscriptionId) {
|
||||
throw new Error("Domain is not linked to a subscription");
|
||||
}
|
||||
|
||||
const { data: subscriptionRow, error: subscriptionError } = await supabase
|
||||
.from("plesk_subscriptions")
|
||||
.select("id, plesk_subscription_id, plesk_instance_id")
|
||||
.eq("id", domain.subscription_id)
|
||||
.eq("id", resolvedSubscriptionId)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.single();
|
||||
|
||||
@@ -71,6 +81,7 @@ export async function POST(
|
||||
subscription = {
|
||||
id: String(subscriptionRow.id),
|
||||
plesk_subscription_id: String(subscriptionRow.plesk_subscription_id),
|
||||
plesk_instance_id: String(subscriptionRow.plesk_instance_id),
|
||||
};
|
||||
|
||||
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({
|
||||
agency_id: context.agencyId,
|
||||
actor_user_id: context.userId,
|
||||
@@ -113,6 +179,8 @@ export async function POST(
|
||||
domain_id: domain.id,
|
||||
subscription_id: 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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||
import { assertSameOrigin } from "@/lib/api/security";
|
||||
import {
|
||||
parseSubscriptionStatusDetailsFromInfo,
|
||||
pleskCliCall,
|
||||
suspendPleskSubscription,
|
||||
unsuspendPleskSubscription,
|
||||
} from "@/lib/plesk/client";
|
||||
@@ -80,12 +82,59 @@ export async function POST(
|
||||
);
|
||||
}
|
||||
|
||||
const newStatus = payload.action === "suspend" ? "suspended" : "active";
|
||||
const fallbackStatus =
|
||||
payload.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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from("plesk_subscriptions")
|
||||
.update({ status: newStatus })
|
||||
.update({
|
||||
status: refreshedStatus,
|
||||
status_raw: refreshedStatusRaw,
|
||||
last_status_sync_at: new Date().toISOString(),
|
||||
})
|
||||
.eq("id", subscription.id);
|
||||
|
||||
await supabase
|
||||
.from("plesk_domains")
|
||||
.update({ status: refreshedStatus })
|
||||
.eq("agency_id", context.agencyId)
|
||||
.eq("subscription_id", subscription.id);
|
||||
|
||||
await supabase.from("actions_log").insert({
|
||||
agency_id: context.agencyId,
|
||||
actor_user_id: context.userId,
|
||||
@@ -95,14 +144,17 @@ export async function POST(
|
||||
status: "success",
|
||||
metadata: {
|
||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||
refreshed_status: refreshedStatus,
|
||||
refresh_error: refreshErrorMessage,
|
||||
db_status_update_error: updateError?.message ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
status: newStatus,
|
||||
status: refreshedStatus,
|
||||
dbStatusUpdated: !updateError,
|
||||
refreshError: refreshErrorMessage,
|
||||
});
|
||||
} catch (error) {
|
||||
if (supabase && context && subscription) {
|
||||
|
||||
@@ -17,6 +17,26 @@ type ActionLogSummary = Pick<
|
||||
"target_id" | "status" | "action" | "created_at" | "error_message"
|
||||
>;
|
||||
|
||||
function normalizeDomainLike(value: string) {
|
||||
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() {
|
||||
const context = await getServerAgencyContextOrRedirect();
|
||||
const supabase = createSupabaseServerClient() as any;
|
||||
@@ -50,7 +70,7 @@ export default async function DashboardPage() {
|
||||
supabase
|
||||
.from("plesk_domains")
|
||||
.select(
|
||||
"id, plesk_instance_id, subscription_id, domain_name, status, hosting_type, source_created_at, aliases_count, updated_at",
|
||||
"id, plesk_instance_id, subscription_id, external_subscription_id, status, domain_name, hosting_type, source_created_at, aliases_count, updated_at",
|
||||
)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.order("updated_at", { ascending: false })
|
||||
@@ -101,6 +121,7 @@ export default async function DashboardPage() {
|
||||
id: string;
|
||||
plesk_instance_id: string;
|
||||
subscription_id: string | null;
|
||||
external_subscription_id: string | null;
|
||||
domain_name: string;
|
||||
status: string | null;
|
||||
hosting_type: string | null;
|
||||
@@ -113,6 +134,69 @@ export default async function DashboardPage() {
|
||||
{ data: ActionLogSummary[] | null },
|
||||
];
|
||||
|
||||
const domainInstanceIds = Array.from(
|
||||
new Set((domains ?? []).map((domain) => domain.plesk_instance_id)),
|
||||
);
|
||||
|
||||
const { data: domainSubscriptions } =
|
||||
domainInstanceIds.length > 0
|
||||
? await supabase
|
||||
.from("plesk_subscriptions")
|
||||
.select("id, plesk_instance_id, plesk_subscription_id, name, status")
|
||||
.eq("agency_id", context.agencyId)
|
||||
.in("plesk_instance_id", domainInstanceIds)
|
||||
: { data: [] };
|
||||
|
||||
const subscriptionStatusById = new Map<string, string | null>(
|
||||
(domainSubscriptions ?? []).map((subscription: any) => [
|
||||
String(subscription.id),
|
||||
subscription?.status ? String(subscription.status) : null,
|
||||
]),
|
||||
);
|
||||
|
||||
const subscriptionStatusByExternalId = new Map<string, string | null>(
|
||||
(domainSubscriptions ?? [])
|
||||
.filter((subscription: any) =>
|
||||
Boolean(
|
||||
subscription?.plesk_instance_id &&
|
||||
subscription?.plesk_subscription_id,
|
||||
),
|
||||
)
|
||||
.map((subscription: any) => [
|
||||
`${String(subscription.plesk_instance_id)}:${String(subscription.plesk_subscription_id)}`,
|
||||
subscription?.status ? String(subscription.status) : null,
|
||||
]),
|
||||
);
|
||||
|
||||
const subscriptionStatusByInstanceAndName = new Map<string, string | null>(
|
||||
(domainSubscriptions ?? [])
|
||||
.filter((subscription: any) =>
|
||||
Boolean(subscription?.plesk_instance_id && subscription?.name),
|
||||
)
|
||||
.map((subscription: any) => [
|
||||
`${String(subscription.plesk_instance_id)}:${normalizeDomainLike(String(subscription.name))}`,
|
||||
subscription?.status ? String(subscription.status) : null,
|
||||
]),
|
||||
);
|
||||
|
||||
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<
|
||||
string,
|
||||
{ status: string; created_at: string; error_message: string | null }
|
||||
@@ -167,7 +251,35 @@ export default async function DashboardPage() {
|
||||
<DashboardControls
|
||||
instances={instances ?? []}
|
||||
subscriptions={subscriptions ?? []}
|
||||
domains={domains ?? []}
|
||||
domains={(domains ?? []).map((domain) => {
|
||||
const joinedStatusByLocalId = domain.subscription_id
|
||||
? subscriptionStatusById.get(domain.subscription_id)
|
||||
: null;
|
||||
const joinedStatusByExternalId = domain.external_subscription_id
|
||||
? subscriptionStatusByExternalId.get(
|
||||
`${domain.plesk_instance_id}:${domain.external_subscription_id}`,
|
||||
)
|
||||
: null;
|
||||
const joinedStatusByName = subscriptionStatusByInstanceAndName.get(
|
||||
`${domain.plesk_instance_id}:${normalizeDomainLike(domain.domain_name)}`,
|
||||
);
|
||||
const joinedStatusBySuffix = findBestSuffixStatusMatch(
|
||||
normalizeDomainLike(domain.domain_name),
|
||||
subscriptionStatusNameCandidatesByInstance.get(
|
||||
domain.plesk_instance_id,
|
||||
) ?? [],
|
||||
);
|
||||
const joinedStatus =
|
||||
joinedStatusByLocalId ??
|
||||
joinedStatusByExternalId ??
|
||||
joinedStatusByName ??
|
||||
joinedStatusBySuffix;
|
||||
|
||||
return {
|
||||
...domain,
|
||||
status: joinedStatus ?? "unknown",
|
||||
};
|
||||
})}
|
||||
autoSyncByInstance={Object.fromEntries(autoSyncByInstance.entries())}
|
||||
/>
|
||||
</main>
|
||||
|
||||
@@ -239,13 +239,23 @@ export function DashboardControls({
|
||||
}
|
||||
|
||||
async function onDomainAction(
|
||||
domainId: string,
|
||||
domain: Domain,
|
||||
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);
|
||||
setMessage(null);
|
||||
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.");
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
@@ -633,7 +643,7 @@ export function DashboardControls({
|
||||
<td className="px-2 py-2">
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => onDomainAction(domain.id, "suspend")}
|
||||
onClick={() => onDomainAction(domain, "suspend")}
|
||||
disabled={
|
||||
loading || isDomainSuspended(domain.status)
|
||||
}
|
||||
@@ -642,9 +652,7 @@ export function DashboardControls({
|
||||
Suspend
|
||||
</button>
|
||||
<button
|
||||
onClick={() =>
|
||||
onDomainAction(domain.id, "unsuspend")
|
||||
}
|
||||
onClick={() => onDomainAction(domain, "unsuspend")}
|
||||
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"
|
||||
>
|
||||
|
||||
@@ -31,6 +31,25 @@ type LocalSubscriptionLookupRow = {
|
||||
|
||||
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(
|
||||
supabase: SupabaseLike,
|
||||
instance: InstanceRow,
|
||||
@@ -213,13 +232,30 @@ export async function syncPleskInstance(
|
||||
>(
|
||||
subscriptionsIndexed
|
||||
.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
|
||||
.map((item: any) => {
|
||||
const domainId = item?.id ?? item?.guid ?? item?.name;
|
||||
const domainName = item?.name ?? item?.domain_name ?? item?.domain;
|
||||
const normalizedDomainName = domainName
|
||||
? normalizeDomainLike(String(domainName))
|
||||
: null;
|
||||
const subExternalId =
|
||||
item?.subscription?.id ?? item?.subscription_id ?? item?.webspace_id;
|
||||
const rawExternalSubscriptionId = subExternalId
|
||||
@@ -240,13 +276,24 @@ export async function syncPleskInstance(
|
||||
: undefined;
|
||||
const localSubscriptionByName = subscriptionNameHint
|
||||
? subscriptionByName.get(
|
||||
String(subscriptionNameHint).trim().toLowerCase(),
|
||||
normalizeDomainLike(String(subscriptionNameHint)),
|
||||
)
|
||||
: undefined;
|
||||
const localSubscriptionByDomainName = normalizedDomainName
|
||||
? subscriptionByName.get(normalizedDomainName)
|
||||
: undefined;
|
||||
const localSubscriptionBySuffix = normalizedDomainName
|
||||
? findBestSuffixSubscriptionMatch(
|
||||
normalizedDomainName,
|
||||
subscriptionNameCandidates,
|
||||
)
|
||||
: undefined;
|
||||
const localSubscription =
|
||||
localSubscriptionByExternal ??
|
||||
localSubscriptionByLocalId ??
|
||||
localSubscriptionByName;
|
||||
localSubscriptionByName ??
|
||||
localSubscriptionByDomainName ??
|
||||
localSubscriptionBySuffix;
|
||||
|
||||
const externalSubscriptionId = localSubscription
|
||||
? localSubscription.pleskSubscriptionId
|
||||
@@ -281,6 +328,10 @@ export async function syncPleskInstance(
|
||||
})
|
||||
.filter(Boolean) as Array<Record<string, unknown>>;
|
||||
|
||||
const unlinkedDomains = domainsForUpsert.filter(
|
||||
(domain) => !domain.subscription_id,
|
||||
);
|
||||
|
||||
if (domainsForUpsert.length > 0) {
|
||||
const { error } = await supabase
|
||||
.from("plesk_domains")
|
||||
@@ -315,6 +366,10 @@ export async function syncPleskInstance(
|
||||
metadata: {
|
||||
subscriptions_seen: subscriptionsRaw.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;
|
||||
}
|
||||
}
|
||||
|
||||
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