mirror of
https://github.com/Portabase/portabase.git
synced 2026-07-14 11:16:13 +02:00
chore(release): 1.2.4-rc.1
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"use server";
|
||||
import {ActionError, userAction} from "@/lib/safe-actions/actions";
|
||||
import {AgentSchema} from "@/features/agents/agents.schema";
|
||||
import {z} from "zod";
|
||||
import {eq, and, ne, count} from "drizzle-orm";
|
||||
import {db} from "@/db";
|
||||
import * as drizzleDb from "@/db";
|
||||
import {slugify} from "@/utils/slugify";
|
||||
|
||||
const verifySlugUniqueness = async (slug: string, agentId?: string) => {
|
||||
const conditions = agentId ? and(eq(drizzleDb.schemas.agent.slug, slug), ne(drizzleDb.schemas.agent.id, agentId)) : eq(drizzleDb.schemas.agent.slug, slug);
|
||||
|
||||
const [countResult] = await db.select({count: count()}).from(drizzleDb.schemas.agent).where(conditions);
|
||||
|
||||
if (countResult.count > 0) {
|
||||
throw new ActionError("Slug already exists");
|
||||
}
|
||||
};
|
||||
|
||||
export const createAgentAction = userAction.schema(AgentSchema).action(async ({parsedInput}) => {
|
||||
const slug = slugify(parsedInput.name);
|
||||
await verifySlugUniqueness(slug);
|
||||
const [createdAgent] = await db.insert(drizzleDb.schemas.agent).values({...parsedInput, slug: slug}).returning();
|
||||
return {
|
||||
data: createdAgent,
|
||||
};
|
||||
});
|
||||
|
||||
export const updateAgentAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
data: AgentSchema,
|
||||
})
|
||||
)
|
||||
.action(async ({parsedInput}) => {
|
||||
const slug = slugify(parsedInput.data.name);
|
||||
await verifySlugUniqueness(slug, parsedInput.id);
|
||||
|
||||
const [updatedAgent] = await db.update(drizzleDb.schemas.agent).set({
|
||||
...parsedInput.data,
|
||||
slug: slug
|
||||
}).where(eq(drizzleDb.schemas.agent.id, parsedInput.id)).returning();
|
||||
|
||||
return {
|
||||
data: updatedAgent,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const AgentSchema = z.object({
|
||||
name: z.string().nonempty("Name is required"),
|
||||
description: z.string(),
|
||||
});
|
||||
|
||||
export type AgentType = z.infer<typeof AgentSchema>;
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {AgentForm} from "@/features/agents/components/agent.form";
|
||||
import {useState} from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Plus} from "lucide-react";
|
||||
import {AgentType} from "@/features/agents/agents.schema";
|
||||
|
||||
type AgentDialogProps = {
|
||||
children?: React.ReactNode;
|
||||
agent?: AgentType & { id: string };
|
||||
};
|
||||
|
||||
export const AgentDialog = ({children, agent}: AgentDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const isEdit = !!agent;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children ? children : <Button><Plus className="mr-2 h-4 w-4"/> Create Agent</Button>}
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? `Edit ${agent.name}` : "Create new agent"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<AgentForm
|
||||
onSuccess={() => setOpen(false)}
|
||||
defaultValues={agent}
|
||||
agentId={agent?.id}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
useZodForm
|
||||
} from "@/components/ui/form";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Form} from "@/components/ui/form";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {useMutation} from "@tanstack/react-query";
|
||||
import {TooltipProvider} from "@/components/ui/tooltip";
|
||||
import {AgentSchema, AgentType} from "@/features/agents/agents.schema";
|
||||
import {toast} from "sonner";
|
||||
import {createAgentAction, updateAgentAction} from "@/features/agents/agents.action";
|
||||
|
||||
export type agentFormProps = {
|
||||
defaultValues?: AgentType;
|
||||
agentId?: string;
|
||||
onSuccess?: (data: any) => void;
|
||||
};
|
||||
|
||||
export const AgentForm = (props: agentFormProps) => {
|
||||
const isCreate = !Boolean(props.defaultValues);
|
||||
|
||||
const form = useZodForm({
|
||||
schema: AgentSchema,
|
||||
defaultValues: props.defaultValues,
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (values: AgentType) => {
|
||||
|
||||
const createAgent = isCreate
|
||||
? await createAgentAction(values)
|
||||
: await updateAgentAction({
|
||||
id: props.agentId ?? "-",
|
||||
data: values,
|
||||
});
|
||||
|
||||
const data = createAgent?.data?.data;
|
||||
if (createAgent?.serverError || !data) {
|
||||
toast.error(createAgent?.serverError);
|
||||
return;
|
||||
}
|
||||
toast.success(`Success ${isCreate ? "creating" : "updating"} agent`);
|
||||
router.refresh();
|
||||
|
||||
if (props.onSuccess) {
|
||||
props.onSuccess(data);
|
||||
} else {
|
||||
router.push(`/dashboard/agents/${data.id}`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Form
|
||||
form={form}
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Agent 1" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>Your agent project name</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
defaultValue=""
|
||||
name="description"
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="This agent is for the client exemple.com" {...field}
|
||||
value={field.value ?? ""}/>
|
||||
</FormControl>
|
||||
<FormDescription>Enter your project agent description</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit">
|
||||
{isCreate ? "Create" : "Update"}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {OrganizationForm} from "@/features/organization/components/organization.form";
|
||||
import {useState} from "react";
|
||||
import {Button, buttonVariants} from "@/components/ui/button";
|
||||
import {GearIcon} from "@radix-ui/react-icons";
|
||||
import {OrganizationWithMembers} from "@/db/schema/03_organization";
|
||||
import {User} from "@/db/schema/02_user";
|
||||
import {User as BetterAuthUser} from "better-auth";
|
||||
|
||||
type EditOrganizationDialogProps = {
|
||||
children?: React.ReactNode;
|
||||
organization: OrganizationWithMembers;
|
||||
users: User[];
|
||||
currentUser: BetterAuthUser;
|
||||
};
|
||||
|
||||
export const EditOrganizationDialog = ({children, organization, users, currentUser}: EditOrganizationDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children ? children : (
|
||||
<Button variant="outline">
|
||||
<GearIcon className="w-4 h-4 mr-2"/> Edit
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit {organization.name}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<OrganizationForm
|
||||
onSuccess={() => setOpen(false)}
|
||||
defaultValues={organization}
|
||||
users={users}
|
||||
currentUser={currentUser}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,172 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
useZodForm
|
||||
} from "@/components/ui/form";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Form} from "@/components/ui/form";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {useMutation} from "@tanstack/react-query";
|
||||
import {useRouter} from "next/navigation";
|
||||
import {MultiSelect} from "@/components/wrappers/common/multiselect/multi-select";
|
||||
import {
|
||||
UpdateOrganizationSchema,
|
||||
UpdateOrganizationType
|
||||
} from "@/features/organization/organization.schema";
|
||||
import {MemberWithUser, OrganizationWithMembers} from "@/db/schema/03_organization";
|
||||
import {
|
||||
updateOrganizationAction
|
||||
} from "@/features/organization/organization.action";
|
||||
import {toast} from "sonner";
|
||||
import {User as BetterAuthUser} from "better-auth";
|
||||
import {User} from "@/db/schema/02_user";
|
||||
import {authClient} from "@/lib/auth/auth-client";
|
||||
|
||||
export type organizationFormProps = {
|
||||
defaultValues?: OrganizationWithMembers;
|
||||
users: User[];
|
||||
currentUser: BetterAuthUser;
|
||||
onSuccess?: (data: any) => void;
|
||||
};
|
||||
|
||||
export const OrganizationForm = (props: organizationFormProps) => {
|
||||
const {data: activeOrganization, refetch: refetchActiveOrga} = authClient.useActiveOrganization();
|
||||
const {data: organizations, refetch} = authClient.useListOrganizations();
|
||||
|
||||
const router = useRouter();
|
||||
const isCreate = !Boolean(props.defaultValues);
|
||||
|
||||
const formatUsersList = (users: User[]) => {
|
||||
|
||||
return users
|
||||
.filter((user) => user.id !== props.currentUser.id)
|
||||
.map((user) => ({
|
||||
value: user.id,
|
||||
label: `${user.name} | ${user.email}`,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatDefaultUsers = (members: MemberWithUser[]): string[] => {
|
||||
return members
|
||||
.filter((member) => member.userId !== props.currentUser.id)
|
||||
.map((member) => member.userId);
|
||||
};
|
||||
|
||||
const formattedDefaultValues = {
|
||||
name: props.defaultValues?.name,
|
||||
slug: props.defaultValues?.slug,
|
||||
users: !isCreate ? formatDefaultUsers(props.defaultValues?.members as MemberWithUser[]) : [],
|
||||
};
|
||||
|
||||
const form = useZodForm({
|
||||
schema: UpdateOrganizationSchema,
|
||||
defaultValues: formattedDefaultValues,
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: UpdateOrganizationType) => updateOrganizationAction({
|
||||
data: values,
|
||||
organizationId: props.defaultValues?.id ?? ""
|
||||
}),
|
||||
onSuccess: async (result) => {
|
||||
if (result?.data?.success) {
|
||||
toast.success(result.data.actionSuccess?.message || "Organization updated successfully.");
|
||||
refetch()
|
||||
refetchActiveOrga()
|
||||
if (props.onSuccess) {
|
||||
props.onSuccess(result.data.value);
|
||||
} else {
|
||||
router.push("/dashboard/settings");
|
||||
}
|
||||
} else {
|
||||
// @ts-ignore
|
||||
const errorMsg = result?.data?.actionError?.message || result?.data?.actionError?.messageParams?.message || "Failed to update the organization.";
|
||||
toast.error(errorMsg);
|
||||
}
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Mutation network error:", error);
|
||||
toast.error(error?.message || "A network error occurred.");
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Organization 1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slug"
|
||||
defaultValue=""
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Slug</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="project-1"
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value.replaceAll(" ", "-").toLowerCase();
|
||||
field.onChange(value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="users"
|
||||
render={({field}) => (
|
||||
<FormItem>
|
||||
<FormLabel>Users</FormLabel>
|
||||
<FormControl>
|
||||
<MultiSelect
|
||||
options={formatUsersList(props.users)}
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value ?? []}
|
||||
placeholder="Select users"
|
||||
variant="inverted"
|
||||
animation={2}
|
||||
// maxCount={100}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>Select users you want to add to this organization</FormDescription>
|
||||
<FormMessage/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit">
|
||||
{isCreate ? "Create" : "Update"}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,221 @@
|
||||
"use server";
|
||||
|
||||
import {userAction} from "@/lib/safe-actions/actions";
|
||||
import {CreateOrganizationSchema, UpdateOrganizationSchema} from "@/features/organization/organization.schema";
|
||||
import {ServerActionResult} from "@/types/action-type";
|
||||
import {z} from "zod";
|
||||
import {db} from "@/db";
|
||||
import {and, eq, inArray, or} from "drizzle-orm";
|
||||
import {auth, checkSlugOrganization, createOrganization} from "@/lib/auth/auth";
|
||||
import {slugify} from "@/utils/slugify";
|
||||
import {Organization} from "@/db/schema/03_organization";
|
||||
import * as drizzleDb from "@/db";
|
||||
|
||||
export const createOrganizationAction = userAction.schema(CreateOrganizationSchema).action(async ({parsedInput}): Promise<ServerActionResult<Organization>> => {
|
||||
try {
|
||||
const slug = slugify(parsedInput.name);
|
||||
if (!await checkSlugOrganization(slug)) {
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Slug is already taken",
|
||||
status: 500,
|
||||
messageParams: {message: "Error creating the organization"},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let createdOrganization: Organization;
|
||||
|
||||
try {
|
||||
createdOrganization = await createOrganization(parsedInput.name, slug) as unknown as Organization;
|
||||
} catch (authError: any) {
|
||||
console.error("Auth deletion failed:", authError);
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: authError.message || "Authentication service error.",
|
||||
status: authError.status || 500,
|
||||
cause: "auth_error",
|
||||
messageParams: {message: authError.message},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
value: createdOrganization,
|
||||
actionSuccess: {
|
||||
message: "Organization has been successfully created.",
|
||||
messageParams: {organizationId: createdOrganization!.id},
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating organization:", error);
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Failed to create organization.",
|
||||
status: 500,
|
||||
messageParams: {message: "Error creating the organization"},
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const updateOrganizationAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
data: UpdateOrganizationSchema,
|
||||
organizationId: z.string(),
|
||||
})
|
||||
)
|
||||
.action(async ({parsedInput, ctx}): Promise<ServerActionResult<Organization>> => {
|
||||
try {
|
||||
const newUserList = parsedInput.data.users;
|
||||
const organization = await db.query.organization.findFirst({
|
||||
where: eq(drizzleDb.schemas.organization.id, parsedInput.organizationId),
|
||||
with: {
|
||||
members: true,
|
||||
}
|
||||
});
|
||||
|
||||
if (!organization) {
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Organization not found.",
|
||||
status: 404,
|
||||
cause: "not_found",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const existingItemIds = organization.members
|
||||
.filter((member) => member.userId !== ctx.user.id)
|
||||
.map((member) => member.userId);
|
||||
const usersToAdd = newUserList.filter((id) => !existingItemIds.includes(id));
|
||||
const usersToRemove = existingItemIds.filter((id) => !newUserList.includes(id));
|
||||
|
||||
if (usersToAdd.length > 0) {
|
||||
for (const userToAdd of usersToAdd) {
|
||||
await auth.api.addMember({
|
||||
body: {
|
||||
userId: userToAdd,
|
||||
role: "member",
|
||||
organizationId: organization.id,
|
||||
},
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
if (usersToRemove.length > 0) {
|
||||
await db.delete(drizzleDb.schemas.member).where(and(inArray(drizzleDb.schemas.member.userId, usersToRemove), eq(drizzleDb.schemas.member.organizationId, organization.id))).execute();
|
||||
|
||||
}
|
||||
const updatedOrganization = await db
|
||||
.update(drizzleDb.schemas.organization)
|
||||
.set({
|
||||
name: parsedInput.data.name,
|
||||
slug: parsedInput.data.slug,
|
||||
})
|
||||
.where(eq(drizzleDb.schemas.organization.id, parsedInput.organizationId))
|
||||
.returning()
|
||||
.execute();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
value: updatedOrganization as unknown as Organization,
|
||||
actionSuccess: {
|
||||
message: "Organization has been successfully updated.",
|
||||
messageParams: {organizationId: organization.id},
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error updating organization:", error);
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Failed to update organization.",
|
||||
status: 500,
|
||||
cause: "server_error",
|
||||
messageParams: {message: "Error updating the organization"},
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
export const deleteOrganizationAction = userAction.schema(
|
||||
z.object({
|
||||
id: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
})
|
||||
).action(
|
||||
async ({parsedInput, ctx}): Promise<ServerActionResult<Organization>> => {
|
||||
try {
|
||||
const conditions = [];
|
||||
if (parsedInput.id) {
|
||||
conditions.push(eq(drizzleDb.schemas.organization.id, parsedInput.id));
|
||||
}
|
||||
if (parsedInput.slug) {
|
||||
conditions.push(eq(drizzleDb.schemas.organization.slug, parsedInput.slug));
|
||||
}
|
||||
|
||||
const org = await db.query.organization.findFirst({
|
||||
where: or(...conditions),
|
||||
});
|
||||
|
||||
if (!org) {
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Organization not found.",
|
||||
status: 404,
|
||||
cause: "not_found",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let deletedOrganization: Organization;
|
||||
|
||||
try {
|
||||
[deletedOrganization] = await db
|
||||
.delete(drizzleDb.schemas.organization)
|
||||
.where(eq(drizzleDb.schemas.organization.id, org.id))
|
||||
.returning();
|
||||
|
||||
} catch (authError: any) {
|
||||
console.error("Auth deletion failed:", authError);
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: authError.message || "Authentication service error.",
|
||||
status: authError.status || 500,
|
||||
cause: "auth_error",
|
||||
messageParams: {message: authError.message},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
value: deletedOrganization,
|
||||
actionSuccess: {
|
||||
message: "Organization has been successfully deleted.",
|
||||
messageParams: {organizationId: deletedOrganization.id},
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Unexpected error in deleteOrganizationAction:", error);
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Failed to delete organization due to a server error.",
|
||||
status: 500,
|
||||
cause: "server_error",
|
||||
messageParams: {message: "Internal server error while deleting the organization"},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const CreateOrganizationSchema = z.object({
|
||||
name: z.string().min(5, "Name must be at least 5 characters long").max(40, "Name must be at most 40 characters long"),
|
||||
});
|
||||
|
||||
export const UpdateOrganizationSchema = z.object({
|
||||
name: z.string().min(5, 'Name must be at least 5 characters long').max(40, 'Name must be at most 40 characters long'),
|
||||
slug: z.string()
|
||||
.regex(/^[a-zA-Z0-9_-]*$/, 'Slug can only contain letters, numbers, underscores, and hyphens')
|
||||
.min(5, 'Slug must be at least 5 characters long')
|
||||
.max(20, 'Slug must be at most 20 characters long'),
|
||||
users: z.array(z.string()),
|
||||
});
|
||||
|
||||
export type CreateOrganizationType = z.infer<typeof CreateOrganizationSchema>;
|
||||
export type UpdateOrganizationType = z.infer<typeof UpdateOrganizationSchema>;
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {ProjectForm} from "@/features/projects/components/project.form";
|
||||
import {useState} from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Plus} from "lucide-react";
|
||||
import {DatabaseWith} from "@/db/schema/07_database";
|
||||
import {Organization} from "@/db/schema/03_organization";
|
||||
import {ProjectWith} from "@/db/schema/06_project";
|
||||
|
||||
type ProjectDialogProps = {
|
||||
children?: React.ReactNode;
|
||||
databases: DatabaseWith[];
|
||||
organization: Organization;
|
||||
project?: ProjectWith;
|
||||
};
|
||||
|
||||
export const ProjectDialog = ({children, databases, organization, project}: ProjectDialogProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const isEdit = !!project;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children ? children : <Button><Plus className="mr-2 h-4 w-4"/> Create Project</Button>}
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? `Edit ${project.name}` : "Create new project"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ProjectForm
|
||||
onSuccess={() => setOpen(false)}
|
||||
databases={databases}
|
||||
organization={organization}
|
||||
defaultValues={project ? {
|
||||
...project,
|
||||
databases: project.databases.map(db => db.id)
|
||||
} : undefined}
|
||||
projectId={project?.id}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useZodForm } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { ProjectSchema, ProjectType } from "@/features/projects/projects.schema";
|
||||
import { createProjectAction, updateProjectAction } from "@/features/projects/projects.action";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { MultiSelect } from "@/components/wrappers/common/multiselect/multi-select";
|
||||
import { toast } from "sonner";
|
||||
import {DatabaseWith} from "@/db/schema/07_database";
|
||||
import {Organization} from "@/db/schema/03_organization";
|
||||
|
||||
export type projectFormProps = {
|
||||
defaultValues?: ProjectType;
|
||||
databases: DatabaseWith[];
|
||||
organization: Organization;
|
||||
projectId?: string;
|
||||
onSuccess?: (data: any) => void;
|
||||
};
|
||||
|
||||
export const ProjectForm = (props: projectFormProps) => {
|
||||
const router = useRouter();
|
||||
const isCreate = !Boolean(props.defaultValues);
|
||||
const formatDatabasesList = (databases: DatabaseWith[]) => {
|
||||
return databases.map((database) => ({
|
||||
value: database.id,
|
||||
label: `${database.name} | ${database.agent?.name}`,
|
||||
}));
|
||||
};
|
||||
|
||||
const formatDefaultDatabases = (databases: string[]): string[] => {
|
||||
return databases;
|
||||
};
|
||||
|
||||
const formattedDefaultValues = {
|
||||
...props.defaultValues,
|
||||
databases: !isCreate ? formatDefaultDatabases(props.defaultValues?.databases ?? []) : [],
|
||||
};
|
||||
|
||||
const form = useZodForm({
|
||||
schema: ProjectSchema,
|
||||
defaultValues: formattedDefaultValues,
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (values: ProjectType) => {
|
||||
if (!isCreate && !props.projectId) {
|
||||
throw new Error("Project ID is required for updates");
|
||||
}
|
||||
const project = isCreate
|
||||
? await createProjectAction({
|
||||
data: values,
|
||||
organizationId: props.organization.id,
|
||||
})
|
||||
: await updateProjectAction({
|
||||
data: values,
|
||||
organizationId: props.organization.id,
|
||||
projectId: props.projectId!,
|
||||
});
|
||||
|
||||
if (project && project.data) {
|
||||
if (project.data.success) {
|
||||
project.data.actionSuccess && toast.success(project.data.actionSuccess.message);
|
||||
router.refresh();
|
||||
if (props.onSuccess) {
|
||||
props.onSuccess(project.data.value);
|
||||
} else {
|
||||
router.push(`/dashboard/projects/${project.data.value!.id}`);
|
||||
}
|
||||
} else {
|
||||
project.data.actionError && toast.error(project.data.actionError.message || "Unknown error occurred.");
|
||||
router.refresh();
|
||||
}
|
||||
} else {
|
||||
toast.error("Failed to process request. No response received.");
|
||||
router.refresh();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={async (values) => {
|
||||
await mutation.mutateAsync(values);
|
||||
}}
|
||||
>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Project 1" {...field} value={field.value ?? ""} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="databases"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Databases</FormLabel>
|
||||
<FormControl>
|
||||
<MultiSelect
|
||||
options={formatDatabasesList(props.databases)}
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value ?? []}
|
||||
placeholder="Select databases"
|
||||
variant="inverted"
|
||||
animation={2}
|
||||
// maxCount={100}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>Select databases you want to add to this project</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit">
|
||||
{isCreate ? "Create" : "Update"}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,150 @@
|
||||
"use server";
|
||||
|
||||
import {userAction} from "@/lib/safe-actions/actions";
|
||||
import {ProjectSchema} from "@/features/projects/projects.schema";
|
||||
import {z} from "zod";
|
||||
import {ServerActionResult} from "@/types/action-type";
|
||||
import {db} from "@/db";
|
||||
import {and, eq, inArray} from "drizzle-orm";
|
||||
import {Project} from "@/db/schema/06_project";
|
||||
import * as drizzleDb from "@/db";
|
||||
import {Database} from "@/db/schema/07_database";
|
||||
import {slugify} from "@/utils/slugify";
|
||||
|
||||
export const createProjectAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
data: ProjectSchema,
|
||||
organizationId: z.string(),
|
||||
})
|
||||
)
|
||||
.action(async ({parsedInput}): Promise<ServerActionResult<Project>> => {
|
||||
try {
|
||||
const slug = slugify(parsedInput.data.name);
|
||||
|
||||
const existingProject = await db.query.project.findFirst({
|
||||
where: and(eq(drizzleDb.schemas.project.name, parsedInput.data.name)),
|
||||
})
|
||||
|
||||
if (existingProject) {
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "A project with this name already exists.",
|
||||
status: 400,
|
||||
messageParams: {projectName: parsedInput.data.name},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const [createdProject] = await db
|
||||
.insert(drizzleDb.schemas.project)
|
||||
.values({
|
||||
name: parsedInput.data.name,
|
||||
slug: slug,
|
||||
organizationId: parsedInput.organizationId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (parsedInput.data.databases.length > 0) {
|
||||
await db
|
||||
.update(drizzleDb.schemas.database)
|
||||
.set({projectId: createdProject.id})
|
||||
.where(inArray(drizzleDb.schemas.database.id, parsedInput.data.databases));
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
value: createdProject,
|
||||
actionSuccess: {
|
||||
message: "Project has been successfully created.",
|
||||
messageParams: {projectName: parsedInput.data.name},
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Failed to create project.",
|
||||
status: 500,
|
||||
cause: error instanceof Error ? error.message : "Unknown error",
|
||||
messageParams: {projectName: parsedInput.data.name},
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
export const updateProjectAction = userAction
|
||||
.schema(
|
||||
z.object({
|
||||
data: ProjectSchema,
|
||||
organizationId: z.string(),
|
||||
projectId: z.string(),
|
||||
})
|
||||
)
|
||||
.action(async ({parsedInput}): Promise<ServerActionResult<Project>> => {
|
||||
try {
|
||||
const existing = await db.query.project.findFirst({
|
||||
where: eq(drizzleDb.schemas.project.id, parsedInput.projectId),
|
||||
with: {
|
||||
databases: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new Error("Project not found.");
|
||||
}
|
||||
|
||||
const existingDbIds = existing.databases.map((db: Database) => db.id);
|
||||
const newDbIds = parsedInput.data.databases;
|
||||
|
||||
const databasesToAdd = newDbIds.filter((id) => !existingDbIds.includes(id));
|
||||
const databasesToRemove = existingDbIds.filter((id: string) => !newDbIds.includes(id));
|
||||
|
||||
if (databasesToAdd.length > 0) {
|
||||
await db.update(drizzleDb.schemas.database).set({projectId: parsedInput.projectId}).where(inArray(drizzleDb.schemas.database.id, databasesToAdd));
|
||||
}
|
||||
|
||||
if (databasesToRemove.length > 0) {
|
||||
await db.update(drizzleDb.schemas.database).set({
|
||||
projectId: null,
|
||||
backupPolicy: null
|
||||
}).where(inArray(drizzleDb.schemas.database.id, databasesToRemove));
|
||||
|
||||
await db.delete(drizzleDb.schemas.retentionPolicy)
|
||||
.where(inArray(drizzleDb.schemas.retentionPolicy.databaseId, databasesToRemove)).execute();
|
||||
|
||||
await db.delete(drizzleDb.schemas.alertPolicy)
|
||||
.where(inArray(drizzleDb.schemas.alertPolicy.databaseId, databasesToRemove)).execute();
|
||||
|
||||
}
|
||||
|
||||
const [updatedProject] = await db
|
||||
.update(drizzleDb.schemas.project)
|
||||
.set({
|
||||
name: parsedInput.data.name,
|
||||
})
|
||||
.where(eq(drizzleDb.schemas.project.id, parsedInput.projectId))
|
||||
.returning();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
value: updatedProject,
|
||||
actionSuccess: {
|
||||
message: "Project has been successfully updated.",
|
||||
messageParams: {projectName: parsedInput.data.name},
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
actionError: {
|
||||
message: "Failed to update project.",
|
||||
status: 500,
|
||||
cause: error instanceof Error ? error.message : "Unknown error",
|
||||
messageParams: {projectName: parsedInput.data.name},
|
||||
},
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ProjectSchema = z.object({
|
||||
name: z.string().nonempty("Name is required"),
|
||||
databases: z.array(z.string()),
|
||||
});
|
||||
|
||||
export type ProjectType = z.infer<typeof ProjectSchema>;
|
||||
Reference in New Issue
Block a user