Initial working state: CL3.5 complete (Plesk sync + suspend/unsuspend)
This commit is contained in:
108
app/api/jobs/plesk-sync-all/route.ts
Normal file
108
app/api/jobs/plesk-sync-all/route.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { env } from "@/lib/env";
|
||||
import { syncPleskInstance } from "@/lib/plesk/sync";
|
||||
import { createSupabaseAdminClient } from "@/lib/supabase/admin";
|
||||
|
||||
const JOB_NAME = "plesk_sync_all";
|
||||
const MAX_INSTANCES_PER_RUN = 10;
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const secret = req.headers.get("x-job-secret");
|
||||
if (!env.jobSecret || !secret || secret !== env.jobSecret) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const supabase = createSupabaseAdminClient() as any;
|
||||
const lockOwner = `nextjs:${process.pid}:${Date.now()}`;
|
||||
|
||||
const { data: acquired, error: lockError } = await supabase.rpc(
|
||||
"acquire_job_lock",
|
||||
{
|
||||
p_job_name: JOB_NAME,
|
||||
p_locked_by: lockOwner,
|
||||
p_ttl_seconds: 240,
|
||||
},
|
||||
);
|
||||
|
||||
if (lockError) {
|
||||
throw new Error(`Unable to acquire job lock: ${lockError.message}`);
|
||||
}
|
||||
|
||||
if (!acquired) {
|
||||
return NextResponse.json({ skipped: true, reason: "already_running" });
|
||||
}
|
||||
|
||||
try {
|
||||
const { data: instances, error: instancesError } = await supabase
|
||||
.from("plesk_instances")
|
||||
.select(
|
||||
"id, agency_id, base_url, auth_type, encrypted_secret, last_connected_at",
|
||||
)
|
||||
.eq("status", "connected")
|
||||
.order("last_connected_at", { ascending: true, nullsFirst: true })
|
||||
.limit(MAX_INSTANCES_PER_RUN);
|
||||
|
||||
if (instancesError) throw instancesError;
|
||||
|
||||
const results: Array<Record<string, unknown>> = [];
|
||||
|
||||
for (const instance of instances ?? []) {
|
||||
try {
|
||||
const result = await syncPleskInstance(
|
||||
supabase,
|
||||
instance,
|
||||
null,
|
||||
"plesk_sync_auto",
|
||||
);
|
||||
results.push(result);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message.slice(0, 1000)
|
||||
: "Auto sync failed";
|
||||
|
||||
await supabase
|
||||
.from("plesk_instances")
|
||||
.update({ status: "error", error_message: message })
|
||||
.eq("id", instance.id)
|
||||
.eq("agency_id", instance.agency_id);
|
||||
|
||||
await supabase.from("actions_log").insert({
|
||||
agency_id: instance.agency_id,
|
||||
actor_user_id: null,
|
||||
target_type: "plesk_instance",
|
||||
target_id: instance.id,
|
||||
action: "plesk_sync_auto",
|
||||
status: "failed",
|
||||
error_message: message,
|
||||
metadata: { auto: true },
|
||||
});
|
||||
|
||||
results.push({
|
||||
instanceId: instance.id,
|
||||
agencyId: instance.agency_id,
|
||||
skipped: false,
|
||||
failed: true,
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
skipped: false,
|
||||
processed: results.length,
|
||||
maxPerRun: MAX_INSTANCES_PER_RUN,
|
||||
results,
|
||||
});
|
||||
} finally {
|
||||
await supabase.rpc("release_job_lock", { p_job_name: JOB_NAME });
|
||||
}
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Job failed" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
52
app/api/plesk/instances/[id]/sync/route.ts
Normal file
52
app/api/plesk/instances/[id]/sync/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
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 { syncPleskInstance } 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-sync:${context.userId}`, 8, 60_000);
|
||||
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
|
||||
const { data: instance, error: instanceError } = await supabase
|
||||
.from("plesk_instances")
|
||||
.select(
|
||||
"id, agency_id, base_url, auth_type, encrypted_secret, last_connected_at",
|
||||
)
|
||||
.eq("id", params.id)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.single();
|
||||
|
||||
if (instanceError || !instance) throw new Error("Plesk instance not found");
|
||||
|
||||
const result = await syncPleskInstance(
|
||||
supabase,
|
||||
instance,
|
||||
context.userId,
|
||||
"sync",
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
subscriptionsUpserted: result.subscriptionsUpserted,
|
||||
domainsUpserted: result.domainsUpserted,
|
||||
skipped: result.skipped,
|
||||
reason: result.reason,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Sync failed" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
85
app/api/plesk/instances/[id]/test/route.ts
Normal file
85
app/api/plesk/instances/[id]/test/route.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
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 { testPleskConnection } from "@/lib/plesk/client";
|
||||
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-test:${context.userId}`, 20, 60_000);
|
||||
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
const { data: instance, error: loadError } = await supabase
|
||||
.from("plesk_instances")
|
||||
.select("id, agency_id, base_url, auth_type, encrypted_secret")
|
||||
.eq("id", params.id)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.single();
|
||||
|
||||
if (loadError || !instance) {
|
||||
throw new Error("Plesk instance not found");
|
||||
}
|
||||
|
||||
let status: "connected" | "error" = "connected";
|
||||
let errorMessage: string | null = null;
|
||||
|
||||
try {
|
||||
await testPleskConnection({
|
||||
baseUrl: instance.base_url,
|
||||
authType: instance.auth_type,
|
||||
encryptedSecret: instance.encrypted_secret,
|
||||
});
|
||||
} catch (error) {
|
||||
status = "error";
|
||||
errorMessage =
|
||||
error instanceof Error
|
||||
? error.message.slice(0, 1000)
|
||||
: "Connection test failed";
|
||||
}
|
||||
|
||||
const { data: updated } = await supabase
|
||||
.from("plesk_instances")
|
||||
.update({
|
||||
status,
|
||||
error_message: errorMessage,
|
||||
last_connected_at:
|
||||
status === "connected" ? new Date().toISOString() : null,
|
||||
})
|
||||
.eq("id", instance.id)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.select(
|
||||
"id, name, base_url, auth_type, status, error_message, last_connected_at",
|
||||
)
|
||||
.single();
|
||||
|
||||
await supabase.from("actions_log").insert({
|
||||
agency_id: context.agencyId,
|
||||
actor_user_id: context.userId,
|
||||
target_type: "plesk_instance",
|
||||
target_id: instance.id,
|
||||
action: "test_connection",
|
||||
status: status === "connected" ? "success" : "failed",
|
||||
error_message: errorMessage,
|
||||
metadata: { instance_id: instance.id },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: status === "connected", instance: updated });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
error instanceof Error ? error.message : "Connection test failed",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
122
app/api/plesk/instances/route.ts
Normal file
122
app/api/plesk/instances/route.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||
import { assertSameOrigin } from "@/lib/api/security";
|
||||
import { encryptPleskSecret } from "@/lib/crypto";
|
||||
import { testPleskConnection } from "@/lib/plesk/client";
|
||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||
|
||||
const createSchema = z.object({
|
||||
name: z.string().min(2),
|
||||
base_url: z.string().url(),
|
||||
auth_type: z.enum(["api_key", "basic"]),
|
||||
api_key: z.string().min(8).optional(),
|
||||
username: z.string().min(1).optional(),
|
||||
password: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
assertSameOrigin(req);
|
||||
|
||||
const context = await getRouteAgencyContextOrThrow();
|
||||
assertAgencyAdmin(context);
|
||||
assertRateLimit(`plesk-connect:${context.userId}`, 10, 60_000);
|
||||
|
||||
const input = createSchema.parse(await req.json());
|
||||
const payload =
|
||||
input.auth_type === "api_key"
|
||||
? {
|
||||
...input,
|
||||
secret: input.api_key,
|
||||
}
|
||||
: {
|
||||
...input,
|
||||
secret:
|
||||
input.username && input.password
|
||||
? `${input.username}:${input.password}`
|
||||
: undefined,
|
||||
};
|
||||
|
||||
if (!payload.secret) {
|
||||
throw new Error("Missing credentials for selected auth type");
|
||||
}
|
||||
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
|
||||
const { encryptedSecret, secretKid } = encryptPleskSecret(payload.secret);
|
||||
|
||||
try {
|
||||
await testPleskConnection({
|
||||
baseUrl: payload.base_url,
|
||||
authType: payload.auth_type,
|
||||
encryptedSecret: encryptedSecret,
|
||||
});
|
||||
} catch (connectError) {
|
||||
const errorMessage =
|
||||
connectError instanceof Error
|
||||
? connectError.message.slice(0, 1000)
|
||||
: "Connection test failed";
|
||||
|
||||
await supabase.from("actions_log").insert({
|
||||
agency_id: context.agencyId,
|
||||
actor_user_id: context.userId,
|
||||
target_type: "plesk_instance",
|
||||
target_id: null,
|
||||
action: "connect",
|
||||
status: "failed",
|
||||
error_message: errorMessage,
|
||||
metadata: { base_url: payload.base_url, auth_type: payload.auth_type },
|
||||
});
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const { data: instance, error } = await supabase
|
||||
.from("plesk_instances")
|
||||
.insert({
|
||||
agency_id: context.agencyId,
|
||||
name: payload.name,
|
||||
base_url: payload.base_url,
|
||||
auth_type: payload.auth_type,
|
||||
encrypted_secret: encryptedSecret,
|
||||
secret_kid: secretKid,
|
||||
status: "connected",
|
||||
error_message: null,
|
||||
last_connected_at: new Date().toISOString(),
|
||||
})
|
||||
.select(
|
||||
"id, name, base_url, auth_type, status, error_message, last_connected_at",
|
||||
)
|
||||
.single();
|
||||
|
||||
if (error || !instance) {
|
||||
throw new Error(error?.message ?? "Failed to create Plesk instance");
|
||||
}
|
||||
|
||||
await supabase.from("actions_log").insert({
|
||||
agency_id: context.agencyId,
|
||||
actor_user_id: context.userId,
|
||||
target_type: "plesk_instance",
|
||||
target_id: instance.id,
|
||||
action: "connect",
|
||||
status: "success",
|
||||
error_message: null,
|
||||
metadata: { base_url: payload.base_url, auth_type: payload.auth_type },
|
||||
});
|
||||
|
||||
return NextResponse.json({ instance });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to create Plesk instance",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
133
app/api/plesk/subscriptions/[id]/action/route.ts
Normal file
133
app/api/plesk/subscriptions/[id]/action/route.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||
import { assertSameOrigin } from "@/lib/api/security";
|
||||
import {
|
||||
suspendPleskSubscription,
|
||||
unsuspendPleskSubscription,
|
||||
} from "@/lib/plesk/client";
|
||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||
|
||||
const actionSchema = z.object({
|
||||
action: z.enum(["suspend", "unsuspend"]),
|
||||
});
|
||||
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: { id: string } },
|
||||
) {
|
||||
let requestedAction: "suspend" | "unsuspend" | null = null;
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
let context: Awaited<ReturnType<typeof getRouteAgencyContextOrThrow>> | null =
|
||||
null;
|
||||
let subscription: {
|
||||
id: string;
|
||||
plesk_subscription_id: string;
|
||||
plesk_instance_id: string;
|
||||
} | null = null;
|
||||
|
||||
try {
|
||||
assertSameOrigin(req);
|
||||
|
||||
context = await getRouteAgencyContextOrThrow();
|
||||
assertAgencyAdmin(context);
|
||||
assertRateLimit(`plesk-subscription-action:${context.userId}`, 20, 60_000);
|
||||
|
||||
const payload = actionSchema.parse(await req.json());
|
||||
requestedAction = payload.action;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from("plesk_subscriptions")
|
||||
.select("id, plesk_subscription_id, plesk_instance_id")
|
||||
.eq("id", params.id)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.single();
|
||||
|
||||
subscription = data;
|
||||
|
||||
if (error || !subscription) {
|
||||
throw new Error("Subscription not found");
|
||||
}
|
||||
|
||||
const { data: instance, error: instanceError } = await supabase
|
||||
.from("plesk_instances")
|
||||
.select("id, base_url, auth_type, encrypted_secret")
|
||||
.eq("id", subscription.plesk_instance_id)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.single();
|
||||
|
||||
if (instanceError || !instance) {
|
||||
throw new Error("Plesk instance not found");
|
||||
}
|
||||
|
||||
const connection = {
|
||||
baseUrl: instance.base_url,
|
||||
authType: instance.auth_type,
|
||||
encryptedSecret: instance.encrypted_secret,
|
||||
} as const;
|
||||
|
||||
if (payload.action === "suspend") {
|
||||
await suspendPleskSubscription(
|
||||
connection,
|
||||
subscription.plesk_subscription_id,
|
||||
);
|
||||
} else {
|
||||
await unsuspendPleskSubscription(
|
||||
connection,
|
||||
subscription.plesk_subscription_id,
|
||||
);
|
||||
}
|
||||
|
||||
const newStatus = payload.action === "suspend" ? "suspended" : "active";
|
||||
const { error: updateError } = await supabase
|
||||
.from("plesk_subscriptions")
|
||||
.update({ status: newStatus })
|
||||
.eq("id", subscription.id);
|
||||
|
||||
await supabase.from("actions_log").insert({
|
||||
agency_id: context.agencyId,
|
||||
actor_user_id: context.userId,
|
||||
target_type: "plesk_subscription",
|
||||
target_id: subscription.id,
|
||||
action: payload.action,
|
||||
status: "success",
|
||||
metadata: {
|
||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||
db_status_update_error: updateError?.message ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
status: newStatus,
|
||||
dbStatusUpdated: !updateError,
|
||||
});
|
||||
} catch (error) {
|
||||
if (supabase && context && subscription) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Subscription action 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: requestedAction ?? "subscription_action",
|
||||
status: "failed",
|
||||
error_message: message,
|
||||
metadata: {
|
||||
plesk_subscription_id: subscription.plesk_subscription_id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
error instanceof Error ? error.message : "Subscription action failed",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
60
app/api/plesk/sync/route.ts
Normal file
60
app/api/plesk/sync/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { assertRateLimit } from "@/lib/api/rate-limit";
|
||||
import { assertSameOrigin } from "@/lib/api/security";
|
||||
import { syncPleskInstance } from "@/lib/plesk/sync";
|
||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||
|
||||
const syncSchema = z.object({
|
||||
instanceId: z.string().uuid(),
|
||||
});
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
assertSameOrigin(req);
|
||||
|
||||
const context = await getRouteAgencyContextOrThrow();
|
||||
assertAgencyAdmin(context);
|
||||
assertRateLimit(`plesk-sync:${context.userId}`, 8, 60_000);
|
||||
|
||||
const payload = syncSchema.parse(await req.json());
|
||||
const supabase = createSupabaseRouteClient() as any;
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
console.log("SYNC USER:", user?.id, user?.email);
|
||||
|
||||
const { data: instance, error: instanceError } = await supabase
|
||||
.from("plesk_instances")
|
||||
.select(
|
||||
"id, agency_id, base_url, auth_type, encrypted_secret, last_connected_at",
|
||||
)
|
||||
.eq("id", payload.instanceId)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.single();
|
||||
|
||||
if (instanceError || !instance) throw new Error("Plesk instance not found");
|
||||
|
||||
const result = await syncPleskInstance(
|
||||
supabase,
|
||||
instance,
|
||||
context.userId,
|
||||
"sync",
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
subscriptionsUpserted: result.subscriptionsUpserted,
|
||||
domainsUpserted: result.domainsUpserted,
|
||||
skipped: result.skipped,
|
||||
reason: result.reason,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Sync failed" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
69
app/api/stripe/checkout/route.ts
Normal file
69
app/api/stripe/checkout/route.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { env } from "@/lib/env";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const context = await getRouteAgencyContextOrThrow();
|
||||
assertAgencyAdmin(context);
|
||||
|
||||
if (!env.stripePriceId) {
|
||||
throw new Error("STRIPE_PRICE_ID is not configured");
|
||||
}
|
||||
|
||||
const stripe = getStripeClient();
|
||||
const supabase = createSupabaseRouteClient();
|
||||
|
||||
const { data: billing, error: billingError } = await supabase
|
||||
.from("billing_accounts")
|
||||
.select("id, stripe_customer_id")
|
||||
.eq("agency_id", context.agencyId)
|
||||
.maybeSingle();
|
||||
|
||||
if (billingError) throw billingError;
|
||||
|
||||
let customerId = billing?.stripe_customer_id ?? null;
|
||||
|
||||
if (!customerId) {
|
||||
const customer = await stripe.customers.create({
|
||||
metadata: {
|
||||
agency_id: context.agencyId,
|
||||
},
|
||||
});
|
||||
|
||||
customerId = customer.id;
|
||||
|
||||
const upsertPayload = {
|
||||
agency_id: context.agencyId,
|
||||
stripe_customer_id: customerId,
|
||||
};
|
||||
|
||||
if (billing?.id) {
|
||||
await supabase.from("billing_accounts").update(upsertPayload).eq("id", billing.id);
|
||||
} else {
|
||||
await supabase.from("billing_accounts").insert(upsertPayload);
|
||||
}
|
||||
}
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
customer: customerId,
|
||||
line_items: [{ price: env.stripePriceId, quantity: 1 }],
|
||||
success_url: `${env.appUrl}/dashboard?checkout=success`,
|
||||
cancel_url: `${env.appUrl}/dashboard?checkout=cancelled`,
|
||||
metadata: {
|
||||
agency_id: context.agencyId,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: session.url });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed to create checkout session" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
39
app/api/stripe/portal/route.ts
Normal file
39
app/api/stripe/portal/route.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency";
|
||||
import { env } from "@/lib/env";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
import { createSupabaseRouteClient } from "@/lib/supabase/route";
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const context = await getRouteAgencyContextOrThrow();
|
||||
assertAgencyAdmin(context);
|
||||
|
||||
const supabase = createSupabaseRouteClient();
|
||||
const stripe = getStripeClient();
|
||||
|
||||
const { data: billing, error } = await supabase
|
||||
.from("billing_accounts")
|
||||
.select("stripe_customer_id")
|
||||
.eq("agency_id", context.agencyId)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) throw error;
|
||||
if (!billing?.stripe_customer_id) {
|
||||
throw new Error("No Stripe customer is linked to this agency");
|
||||
}
|
||||
|
||||
const session = await stripe.billingPortal.sessions.create({
|
||||
customer: billing.stripe_customer_id,
|
||||
return_url: `${env.appUrl}/dashboard`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: session.url });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed to open billing portal" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
126
app/api/stripe/webhook/route.ts
Normal file
126
app/api/stripe/webhook/route.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
|
||||
import { env } from "@/lib/env";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
import { createSupabaseAdminClient } from "@/lib/supabase/admin";
|
||||
|
||||
function toIsoOrNull(unixSeconds?: number | null) {
|
||||
if (!unixSeconds) return null;
|
||||
return new Date(unixSeconds * 1000).toISOString();
|
||||
}
|
||||
|
||||
async function upsertBillingByCustomer(
|
||||
customerId: string,
|
||||
updates: {
|
||||
stripe_subscription_id?: string | null;
|
||||
plan_id?: string | null;
|
||||
subscription_status?: string | null;
|
||||
current_period_end?: string | null;
|
||||
},
|
||||
) {
|
||||
const supabase = createSupabaseAdminClient();
|
||||
|
||||
const { data: existing } = await supabase
|
||||
.from("billing_accounts")
|
||||
.select("id")
|
||||
.eq("stripe_customer_id", customerId)
|
||||
.maybeSingle();
|
||||
|
||||
if (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;
|
||||
|
||||
if (!agencyId || !customerId) return;
|
||||
|
||||
const supabase = createSupabaseAdminClient();
|
||||
const payload = {
|
||||
agency_id: agencyId,
|
||||
stripe_customer_id: customerId,
|
||||
stripe_subscription_id:
|
||||
typeof session.subscription === "string" ? (session.subscription as string) : null,
|
||||
subscription_status: "active",
|
||||
};
|
||||
|
||||
const { data: existing } = await supabase
|
||||
.from("billing_accounts")
|
||||
.select("id")
|
||||
.eq("agency_id", agencyId)
|
||||
.maybeSingle();
|
||||
|
||||
if (existing?.id) {
|
||||
await supabase.from("billing_accounts").update(payload).eq("id", existing.id);
|
||||
} else {
|
||||
await supabase.from("billing_accounts").insert(payload);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubscriptionUpdated(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === "string" ? subscription.customer : subscription.customer?.id;
|
||||
|
||||
if (!customerId) return;
|
||||
|
||||
await upsertBillingByCustomer(customerId, {
|
||||
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),
|
||||
});
|
||||
}
|
||||
|
||||
async function handleSubscriptionDeleted(subscription: Stripe.Subscription) {
|
||||
const customerId =
|
||||
typeof subscription.customer === "string" ? subscription.customer : subscription.customer?.id;
|
||||
|
||||
if (!customerId) return;
|
||||
|
||||
await upsertBillingByCustomer(customerId, {
|
||||
stripe_subscription_id: subscription.id,
|
||||
subscription_status: "canceled",
|
||||
current_period_end: toIsoOrNull(subscription.current_period_end),
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
if (!env.stripeWebhookSecret) {
|
||||
throw new Error("STRIPE_WEBHOOK_SECRET is not configured");
|
||||
}
|
||||
|
||||
const signature = req.headers.get("stripe-signature");
|
||||
if (!signature) {
|
||||
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);
|
||||
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed":
|
||||
await handleCheckoutSessionCompleted(event.data.object as Stripe.Checkout.Session);
|
||||
break;
|
||||
case "customer.subscription.updated":
|
||||
await handleSubscriptionUpdated(event.data.object as Stripe.Subscription);
|
||||
break;
|
||||
case "customer.subscription.deleted":
|
||||
await handleSubscriptionDeleted(event.data.object as Stripe.Subscription);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return NextResponse.json({ received: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Webhook handling failed" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
32
app/auth/callback/route.ts
Normal file
32
app/auth/callback/route.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
|
||||
import { NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
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";
|
||||
|
||||
if (code) {
|
||||
const supabase = createRouteHandlerClient<Database>({ cookies });
|
||||
const { error } = await supabase.auth.exchangeCodeForSession(code);
|
||||
if (error) {
|
||||
console.error(error);
|
||||
return NextResponse.redirect(
|
||||
new URL(`/login?authError=1`, requestUrl.origin),
|
||||
);
|
||||
}
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.redirect(
|
||||
new URL(`/login?noUser=1`, requestUrl.origin),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL(next, requestUrl.origin));
|
||||
}
|
||||
163
app/dashboard/page.tsx
Normal file
163
app/dashboard/page.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { SignOutButton } from "@/components/auth/sign-out-button";
|
||||
import { DashboardControls } from "@/components/dashboard/dashboard-controls";
|
||||
import { getServerAgencyContextOrRedirect } from "@/lib/agency";
|
||||
import type { Database } from "@/lib/types";
|
||||
import { createSupabaseServerClient } from "@/lib/supabase/server";
|
||||
|
||||
type AgencySummary = Pick<Database["public"]["Tables"]["agencies"]["Row"], "id" | "name">;
|
||||
type BillingSummary = Pick<
|
||||
Database["public"]["Tables"]["billing_accounts"]["Row"],
|
||||
"subscription_status" | "plan_id" | "current_period_end"
|
||||
>;
|
||||
type ActionLogSummary = Pick<
|
||||
Database["public"]["Tables"]["actions_log"]["Row"],
|
||||
"target_id" | "status" | "action" | "created_at" | "error_message"
|
||||
>;
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const context = await getServerAgencyContextOrRedirect();
|
||||
const supabase = createSupabaseServerClient() as any;
|
||||
|
||||
const [
|
||||
{ data: agency },
|
||||
{ data: instances },
|
||||
{ data: subscriptions },
|
||||
{ data: domains },
|
||||
{ data: billing },
|
||||
{ data: autoSyncLogs },
|
||||
] =
|
||||
(await Promise.all([
|
||||
supabase.from("agencies").select("id, name").eq("id", context.agencyId).maybeSingle(),
|
||||
supabase
|
||||
.from("plesk_instances")
|
||||
.select(
|
||||
"id, name, base_url, auth_type, status, error_message, last_connected_at, last_sync_at, last_sync_status, last_sync_error, last_sync_subscriptions, last_sync_domains",
|
||||
)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.order("created_at", { ascending: false }),
|
||||
supabase
|
||||
.from("plesk_subscriptions")
|
||||
.select("id, name, status, plesk_subscription_id, plesk_instance_id")
|
||||
.eq("agency_id", context.agencyId)
|
||||
.order("updated_at", { ascending: false })
|
||||
.limit(10),
|
||||
supabase
|
||||
.from("plesk_domains")
|
||||
.select(
|
||||
"id, plesk_instance_id, domain_name, status, hosting_type, source_created_at, aliases_count, updated_at",
|
||||
)
|
||||
.eq("agency_id", context.agencyId)
|
||||
.order("updated_at", { ascending: false })
|
||||
.limit(500),
|
||||
supabase
|
||||
.from("billing_accounts")
|
||||
.select("subscription_status, plan_id, current_period_end")
|
||||
.eq("agency_id", context.agencyId)
|
||||
.maybeSingle(),
|
||||
supabase
|
||||
.from("actions_log")
|
||||
.select("target_id, status, action, created_at, error_message")
|
||||
.eq("agency_id", context.agencyId)
|
||||
.eq("target_type", "plesk_instance")
|
||||
.eq("action", "plesk_sync_auto")
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(200),
|
||||
])) as [
|
||||
{ data: AgencySummary | null },
|
||||
{
|
||||
data:
|
||||
| Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
base_url: string;
|
||||
auth_type: "api_key" | "basic";
|
||||
status: string;
|
||||
error_message: string | null;
|
||||
last_connected_at: string | null;
|
||||
last_sync_at: string | null;
|
||||
last_sync_status: string | null;
|
||||
last_sync_error: string | null;
|
||||
last_sync_subscriptions: number;
|
||||
last_sync_domains: number;
|
||||
}>
|
||||
| null;
|
||||
},
|
||||
{
|
||||
data:
|
||||
| Array<{
|
||||
id: string;
|
||||
name: string | null;
|
||||
status: string | null;
|
||||
plesk_subscription_id: string;
|
||||
plesk_instance_id: string;
|
||||
}>
|
||||
| null;
|
||||
},
|
||||
{
|
||||
data:
|
||||
| Array<{
|
||||
id: string;
|
||||
plesk_instance_id: string;
|
||||
domain_name: string;
|
||||
status: string | null;
|
||||
hosting_type: string | null;
|
||||
source_created_at: string | null;
|
||||
aliases_count: number | null;
|
||||
updated_at: string;
|
||||
}>
|
||||
| null;
|
||||
},
|
||||
{ data: BillingSummary | null },
|
||||
{ data: ActionLogSummary[] | null },
|
||||
];
|
||||
|
||||
const autoSyncByInstance = new Map<
|
||||
string,
|
||||
{ status: string; created_at: string; error_message: string | null }
|
||||
>();
|
||||
|
||||
for (const log of autoSyncLogs ?? []) {
|
||||
if (!log.target_id || autoSyncByInstance.has(log.target_id)) continue;
|
||||
autoSyncByInstance.set(log.target_id, {
|
||||
status: log.status,
|
||||
created_at: log.created_at,
|
||||
error_message: log.error_message,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-8">
|
||||
<header className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">{agency?.name ?? "Agency"} Dashboard</h1>
|
||||
<p className="text-sm text-slate-600">Role: {context.role}</p>
|
||||
</div>
|
||||
<SignOutButton />
|
||||
</header>
|
||||
|
||||
<section className="grid gap-4 md:grid-cols-3">
|
||||
<div className="rounded-xl border border-slate-200 bg-white p-4">
|
||||
<p className="text-sm text-slate-500">Plesk Instances</p>
|
||||
<p className="text-2xl font-semibold text-slate-900">{instances?.length ?? 0}</p>
|
||||
</div>
|
||||
<div className="rounded-xl border border-slate-200 bg-white p-4">
|
||||
<p className="text-sm text-slate-500">Tracked Subscriptions</p>
|
||||
<p className="text-2xl font-semibold text-slate-900">{subscriptions?.length ?? 0}</p>
|
||||
</div>
|
||||
<div className="rounded-xl border border-slate-200 bg-white p-4">
|
||||
<p className="text-sm text-slate-500">Billing Status</p>
|
||||
<p className="text-2xl font-semibold text-slate-900">{billing?.subscription_status ?? "none"}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<DashboardControls
|
||||
instances={instances ?? []}
|
||||
subscriptions={subscriptions ?? []}
|
||||
domains={domains ?? []}
|
||||
autoSyncByInstance={Object.fromEntries(autoSyncByInstance.entries())}
|
||||
/>
|
||||
|
||||
|
||||
</main>
|
||||
);
|
||||
}
|
||||
12
app/globals.css
Normal file
12
app/globals.css
Normal file
@@ -0,0 +1,12 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
html,
|
||||
body {
|
||||
@apply bg-slate-50 text-slate-900;
|
||||
}
|
||||
|
||||
a {
|
||||
@apply text-brand-600 hover:text-brand-500;
|
||||
}
|
||||
18
app/layout.tsx
Normal file
18
app/layout.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import type { ReactNode } from "react";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Plesk Agency Portal",
|
||||
description: "Multi-tenant agency management portal for Plesk hosting",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{ children: ReactNode }>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
22
app/login/page.tsx
Normal file
22
app/login/page.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { LoginForm } from "@/components/auth/login-form";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-md flex-col justify-center gap-6 px-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-slate-900">Sign in</h1>
|
||||
<p className="mt-2 text-sm text-slate-600">
|
||||
Use your agency email to receive a magic-link and access the portal.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<LoginForm />
|
||||
|
||||
<Link href="/" className="text-sm text-slate-500">
|
||||
← Back to home
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
24
app/page.tsx
Normal file
24
app/page.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen w-full max-w-4xl flex-col justify-center gap-6 px-6">
|
||||
<h1 className="text-4xl font-bold text-slate-900">Plesk Agency Portal</h1>
|
||||
<p className="max-w-2xl text-slate-600">
|
||||
Multi-tenant MVP for agencies to connect Plesk instances, manage subscriptions and
|
||||
domains, and control billing with Stripe.
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
href="/login"
|
||||
className="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
<Link href="/dashboard" className="rounded-lg border border-slate-300 px-4 py-2 text-sm">
|
||||
Dashboard
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user