47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
|
|
"use server";
|
||
|
|
|
||
|
|
import { createClient } from "@/lib/supabase/server";
|
||
|
|
import { redirect } from "next/navigation";
|
||
|
|
|
||
|
|
export async function createOrganization(formData: FormData) {
|
||
|
|
const name = formData.get("name") as string;
|
||
|
|
if (!name) {
|
||
|
|
throw new Error("Organization name is required");
|
||
|
|
}
|
||
|
|
|
||
|
|
const supabase = await createClient();
|
||
|
|
const { data: userData, error: userError } = await supabase.auth.getUser();
|
||
|
|
|
||
|
|
if (userError || !userData.user) {
|
||
|
|
redirect("/auth/login");
|
||
|
|
}
|
||
|
|
|
||
|
|
const userId = userData.user.id;
|
||
|
|
|
||
|
|
// Insert organization
|
||
|
|
const { data: orgData, error: orgError } = await supabase
|
||
|
|
.from("organizations")
|
||
|
|
.insert([{ name, owner_id: userId }])
|
||
|
|
.select("id")
|
||
|
|
.single();
|
||
|
|
|
||
|
|
if (orgError || !orgData) {
|
||
|
|
console.error("Error creating organization:", orgError);
|
||
|
|
throw new Error("Failed to create organization.");
|
||
|
|
}
|
||
|
|
|
||
|
|
// Update profile
|
||
|
|
const { error: profileError } = await supabase
|
||
|
|
.from("profiles")
|
||
|
|
.update({ organization_id: orgData.id, role: "owner" })
|
||
|
|
.eq("id", userId);
|
||
|
|
|
||
|
|
if (profileError) {
|
||
|
|
console.error("Error updating profile:", profileError);
|
||
|
|
throw new Error("Failed to assign user to organization.");
|
||
|
|
}
|
||
|
|
|
||
|
|
// Redirect to dashboard
|
||
|
|
redirect("/dashboard");
|
||
|
|
}
|