88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
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 { createSupabaseRouteClient } from "@/lib/supabase/route";
|
|
|
|
const autosyncSchema = z.object({
|
|
auto_sync_enabled: z.boolean(),
|
|
auto_sync_frequency_minutes: z.number().int().min(5).max(10080).optional(),
|
|
});
|
|
|
|
export async function POST(
|
|
req: Request,
|
|
{ params }: { params: { id: string } },
|
|
) {
|
|
try {
|
|
assertSameOrigin(req);
|
|
|
|
const context = await getRouteAgencyContextOrThrow();
|
|
assertAgencyAdmin(context);
|
|
assertRateLimit(`plesk-autosync-settings:${context.userId}`, 20, 60_000);
|
|
|
|
const input = autosyncSchema.parse(await req.json());
|
|
const frequency = input.auto_sync_frequency_minutes ?? 60;
|
|
const nowIso = new Date().toISOString();
|
|
const nextAtIso = new Date(
|
|
Date.now() + frequency * 60 * 1000,
|
|
).toISOString();
|
|
|
|
const supabase = createSupabaseRouteClient() as any;
|
|
|
|
const updates = {
|
|
auto_sync_enabled: input.auto_sync_enabled,
|
|
auto_sync_frequency_minutes: frequency,
|
|
next_auto_sync_at: input.auto_sync_enabled ? nextAtIso : null,
|
|
auto_sync_lock_until: null,
|
|
auto_sync_lock_token: null,
|
|
last_auto_sync_at: input.auto_sync_enabled ? undefined : null,
|
|
} as Record<string, unknown>;
|
|
|
|
const { data: instance, error } = await supabase
|
|
.from("plesk_instances")
|
|
.update(updates)
|
|
.eq("id", params.id)
|
|
.eq("agency_id", context.agencyId)
|
|
.select(
|
|
"id, auto_sync_enabled, auto_sync_frequency_minutes, last_auto_sync_at, next_auto_sync_at, auto_sync_lock_until",
|
|
)
|
|
.single();
|
|
|
|
if (error || !instance) {
|
|
throw new Error(error?.message ?? "Plesk instance not found");
|
|
}
|
|
|
|
try {
|
|
await supabase.from("actions_log").insert({
|
|
agency_id: context.agencyId,
|
|
actor_user_id: context.userId,
|
|
target_type: "plesk_instance",
|
|
target_id: params.id,
|
|
action: "autosync_settings_updated",
|
|
status: "success",
|
|
metadata: {
|
|
auto_sync_enabled: input.auto_sync_enabled,
|
|
auto_sync_frequency_minutes: frequency,
|
|
updated_at: nowIso,
|
|
},
|
|
});
|
|
} catch {
|
|
// best effort logging
|
|
}
|
|
|
|
return NextResponse.json({ instance });
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{
|
|
error:
|
|
error instanceof Error
|
|
? error.message
|
|
: "Failed to update auto-sync settings",
|
|
},
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
}
|