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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user