Merge remote-tracking branch 'origin/main'

# Conflicts:
#	yarn.lock
This commit is contained in:
killian-larcher
2024-11-11 15:00:34 +01:00
24 changed files with 626 additions and 37 deletions
@@ -0,0 +1,36 @@
import {PageParams} from "@/types/next";
import {Page, PageContent, PageDescription, PageHeader, PageTitle} from "@/features/layout/page";
import {AgentForm} from "@/components/wrappers/Agent/AgentForm/AgentForm";
import {requiredCurrentUser} from "@/auth/current-user";
import {prisma} from "@/prisma";
import {notFound} from "next/navigation";
export default async function RoutePage(props: PageParams<{
agentId: string;
}>) {
const user = await requiredCurrentUser()
const agent = await prisma.agent.findUnique({
where: {
id: props.params.agentId,
}
});
if (!agent){
notFound();
}
return (
<Page>
<PageHeader>
<PageTitle>
Edit {agent.name}
</PageTitle>
</PageHeader>
<PageContent>
<AgentForm defaultValues={agent} agentId={agent.id}/>
</PageContent>
</Page>
)
}
+13 -1
View File
@@ -1,7 +1,19 @@
import {PageParams} from "@/types/next";
import {Page, PageContent, PageDescription, PageHeader, PageTitle} from "@/features/layout/page";
import {AgentForm} from "@/components/wrappers/Agent/AgentForm/AgentForm";
export default async function RoutePage(props: PageParams<{}>) {
return (
<div>new agent</div>
<Page>
<PageHeader>
<PageTitle>
Create new agent
</PageTitle>
</PageHeader>
<PageContent>
<AgentForm/>
</PageContent>
</Page>
)
}
+44
View File
@@ -0,0 +1,44 @@
import {PageParams} from "@/types/next";
import {Page, PageActions, PageContent, PageHeader, PageTitle} from "@/features/layout/page";
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import {notFound} from "next/navigation";
import {requiredCurrentUser} from "@/auth/current-user";
import {UserForm} from "@/components/wrappers/Dashboard/Profile/UserForm/UserForm";
import {prisma} from "@/prisma";
import {Badge} from "@/components/ui/badge";
export default async function RoutePage(props: PageParams<{}>) {
const user = await requiredCurrentUser()
if (!user) {
notFound()
}
const userInfo = await prisma.user.findUnique({
where: {
email: user.email
}
})
console.log(userInfo)
return (
<Page>
<PageHeader>
<PageTitle className="flex items-center">
<Avatar className="size-14 mr-3">
<AvatarFallback>{user.name?.[0]}</AvatarFallback>
{user.image ? (
<AvatarImage src={user.image} alt={`${user.name ?? "-"}'s profile picture`}/>
) : null}
</Avatar>
{user.name}
<Badge className="ml-3">{userInfo.authMethod}</Badge>
</PageTitle>
</PageHeader>
<PageContent>
<UserForm userId={userInfo.id} defaultValues={userInfo} />
</PageContent>
</Page>
)
}
+20
View File
@@ -0,0 +1,20 @@
// next-auth.d.ts
import NextAuth from "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
email: string;
name: string;
authMethod: string; // Add authMethod to the session user type
};
}
interface User {
id: string;
email: string;
name: string;
authMethod: string; // Add authMethod to the user type
}
}
+2 -2
View File
@@ -11,7 +11,7 @@
"dependencies": {
"@auth/prisma-adapter": "^2.4.1",
"@hookform/resolvers": "^3.9.1",
"@prisma/client": "^5.21.1",
"@prisma/client": "^5.22.0",
"@radix-ui/react-accordion": "^1.2.1",
"@radix-ui/react-alert-dialog": "^1.1.2",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -77,7 +77,7 @@
"eslint": "^8",
"eslint-config-next": "15.0.3",
"postcss": "^8",
"prisma": "^5.21.1",
"prisma": "^5.22.0",
"tailwindcss": "^3.4.1",
"typescript": "^5"
},
@@ -0,0 +1,46 @@
-- CreateEnum
CREATE TYPE "Status" AS ENUM ('waiting', 'ongoing', 'failed', 'success');
-- CreateTable
CREATE TABLE "Agent" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
"last_contact" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Agent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Database" (
"id" TEXT NOT NULL,
"agent_id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
"backup_policy" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Database_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Backup" (
"id" TEXT NOT NULL,
"database_id" TEXT NOT NULL,
"status" "Status" NOT NULL DEFAULT 'waiting',
"file" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Backup_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Restore" (
"id" TEXT NOT NULL,
"backup_id" TEXT NOT NULL,
"status" "Status" NOT NULL DEFAULT 'waiting',
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Restore_pkey" PRIMARY KEY ("id")
);
@@ -0,0 +1,12 @@
/*
Warnings:
- A unique constraint covering the columns `[slug]` on the table `Agent` will be added. If there are existing duplicate values, this will fail.
- Added the required column `slug` to the `Agent` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Agent" ADD COLUMN "slug" TEXT NOT NULL;
-- CreateIndex
CREATE UNIQUE INDEX "Agent_slug_key" ON "Agent"("slug");
@@ -0,0 +1,2 @@
-- AddForeignKey
ALTER TABLE "Database" ADD CONSTRAINT "Database_agent_id_fkey" FOREIGN KEY ("agent_id") REFERENCES "Agent"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+14 -10
View File
@@ -62,26 +62,30 @@ model User {
role String?
password String?
accounts Account[]
sessions Session[]
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime? @updatedAt @map("updated_at")
accounts Account[]
sessions Session[]
authMethod String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime? @updatedAt @map("updated_at")
@@map("users")
}
model Agent {
id String @id @default(cuid())
id String @id @default(cuid())
slug String @unique
name String
description String?
lastContact DateTime? @map("last_contact")
createdAt DateTime @default(now()) @map("created_at")
lastContact DateTime? @map("last_contact")
createdAt DateTime @default(now()) @map("created_at")
databases Database[]
}
model Database {
id String @id @default(cuid())
agentId String @map("agent_id")
id String @id @default(cuid())
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
name String
description String?
backupPolicy String? @map("backup_policy")
+39 -5
View File
@@ -52,6 +52,7 @@ export const {handlers, auth: baseAuth, signIn, signOut} = NextAuth({
name: profile.name,
email: profile.email,
image: profile.picture,
authMethod: "google",
}
},
})
@@ -64,11 +65,44 @@ export const {handlers, auth: baseAuth, signIn, signOut} = NextAuth({
error: "/error"
},
callbacks: {
session({session, user, token}) {
// session.user.role = user.role
return session
}
},
// session({session, user, token}) {
// // session.user.role = user.role
// // session.user.authMethod = user.authMethod;
// return session
// },
async jwt({ token, trigger, session, user }) {
if (trigger === "update" && session) {
return { ...token, ...session?.user };
}
return { ...token, ...user };
},
async session({ session, token, user }) {
session.user = token;
return session;
},
async signIn({ account, user }) {
console.log(account)
// const authMethod = account.provider === 'credentials' ? 'credentials' : 'oauth';
user = await prisma.user.findFirst({
where: {
email: user.email,
}
})
if (!user) {
return true
}
console.log(user)
// Update the user in the database with the auth method
await prisma.user.update({
where: { id: user.id },
data: {
authMethod: account.provider
},
});
return true;
},
}
});
@@ -0,0 +1,130 @@
"use client";
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
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 "@/components/wrappers/Agent/AgentForm/agent-form.schema";
import {toast} from "sonner";
import {createAgentAction, updateAgentAction} from "@/components/wrappers/Agent/AgentForm/agent-form.action";
export type agentFormProps = {
defaultValues?: AgentType;
agentId?: string;
}
export const AgentForm = (props: agentFormProps) => {
const isCreate = !Boolean(props.defaultValues)
// const defaultValues = isCreate ? {slug: ""} : props.defaultValues
const form = useZodForm({
schema: AgentSchema,
defaultValues: props.defaultValues,
});
const router = useRouter();
const mutation = useMutation({
mutationFn: async (values: AgentType) => {
console.log("values", values)
const createAgent = isCreate ? await createAgentAction(values) : await updateAgentAction({
id: props.agentId ?? "-",
data: values
});
const data = createAgent?.data?.data
if (createAgent?.serverError || !data) {
console.log(createAgent?.serverError);
toast.error(createAgent?.serverError);
return;
}
toast.success(`Success`);
router.push(`/dashboard/agents/${data.id}`);
router.refresh()
}
})
return (
<TooltipProvider>
<Card>
<CardContent>
<Form form={form}
className="flex flex-col gap-4 mt-3"
onSubmit={async (values) => {
await mutation.mutateAsync(values);
}}
>
<FormField
control={form.control}
name="name"
defaultValue=""
render={({field}) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input
placeholder={"Project 1"} {...field} />
</FormControl>
<FormDescription>{"Your agent project name"}</FormDescription>
<FormMessage/>
</FormItem>
)}
/>
<FormField
control={form.control}
defaultValue=""
name="slug"
render={({field}) => (
<FormItem>
<FormLabel>Slug</FormLabel>
<FormControl>
<Input
value={field.value ?? ""}
placeholder={"agent-5-project-1"} {...field}
onChange={(e) => {
const value = e.target.value.replaceAll(" ", "-").toLowerCase()
field.onChange(value)
}}
/>
</FormControl>
<FormDescription>{'The slug is used in the url of the agent'}</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>
)}
/>
<Button>
{isCreate ? `Create agent` : `Save agent`}
</Button>
</Form>
</CardContent>
</Card>
</TooltipProvider>
)
}
@@ -0,0 +1,68 @@
"use server"
import {ActionError, userAction} from "@/safe-actions";
import {prisma} from "@/prisma";
import {AgentSchema} from "@/components/wrappers/Agent/AgentForm/agent-form.schema";
import {z} from "zod";
const verifySlugUniqueness = async (slug: string, agentId?: string) => {
const slugExists = await prisma.agent.count({
where: {
slug: slug,
id: agentId ? {
not: agentId
} : undefined,
},
})
console.log(slugExists)
if (slugExists) {
throw new ActionError("Slug already exists");
}
}
export const createAgentAction = userAction
.schema(AgentSchema)
.action(async ({parsedInput, ctx}) => {
// Verify if slug already exist
await verifySlugUniqueness(parsedInput.slug);
const agent = await prisma.agent.create({
data: {
...parsedInput
}
})
// await sendEmailIfUserCreatedFirstForm(ctx.user)
return {
data: agent,
}
});
export const updateAgentAction = userAction
.schema(
z.object({
id: z.string(),
data: AgentSchema,
}
)
)
.action(async ({parsedInput, ctx}) => {
await verifySlugUniqueness(parsedInput.data.slug, parsedInput.id);
console.log("parsedInput", parsedInput.data)
const updatedAgent = await prisma.agent.update({
where: {
id: parsedInput.id,
},
data: parsedInput.data,
})
return {
data: updatedAgent,
}
})
@@ -0,0 +1,9 @@
import {z} from "zod";
export const AgentSchema = z.object({
name: z.string(),
slug: z.string().regex(/^[a-zA-Z0-9_-]*$/).min(5).max(25),
description: z.string().optional().nullable(),
});
export type AgentType = z.infer<typeof AgentSchema>;
@@ -12,7 +12,7 @@ import {useMutation} from "@tanstack/react-query";
import {TooltipProvider} from "@/components/ui/tooltip";
import Link from "next/link";
import {PasswordInput} from "@/components/wrappers/Auth/PaswordInput/password-input";
import {LoginSchema, LoginType} from "@/components/wrappers/Auth/Login/LoginForm/login-form-schema";
import {LoginSchema, LoginType} from "@/components/wrappers/Auth/Login/LoginForm/login-form.schema";
import {signInAction} from "@/features/auth/auth.action";
import {SocialAuthButton} from "@/components/wrappers/Auth/Login/SocialAuth/SocialAuthButtons/SocialAuthButton";
import Image from 'next/image';
@@ -30,6 +30,7 @@ export const RegisterForm = (props: registerFormProps) => {
mutationFn: async (values: RegisterType) => {
console.log(values)
const createUser = await registerUserAction(values);
console.log(createUser)
const data = createUser?.data?.data
if (createUser?.serverError || !data) {
console.log(createUser?.serverError);
@@ -22,7 +22,6 @@ export const registerUserAction = action
data: new_user,
}
}
return {
data: user,
}
throw new Error('An error occured while creating user');
});
@@ -8,6 +8,7 @@ import Link from "next/link";
import {useTranslations} from "use-intl";
import {SidebarMenuButton} from "@/components/ui/sidebar";
import {UserAvatar} from "@/components/wrappers/Dashboard/UserAvatar/UserAvatar";
import {redirect} from "next/navigation";
export type LoggedInDropdownProps = PropsWithChildren<{}>
@@ -22,7 +23,9 @@ export const LoggedInDropdown = (props: LoggedInDropdownProps) => {
side="top"
className="w-[--radix-popper-anchor-width]"
>
<DropdownMenuItem>
<DropdownMenuItem onClick={() => {
redirect("/dashboard/profile")
}}>
<span>Account</span>
</DropdownMenuItem>
<DropdownMenuItem>
@@ -0,0 +1,125 @@
"use client";
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card";
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 {UserSchema, UserType} from "@/components/wrappers/Dashboard/Profile/UserForm/user-form.schema";
import {toast} from "sonner";
import {updateUserAction} from "@/components/wrappers/Dashboard/Profile/UserForm/user-form.action";
import { useSession } from "next-auth/react";
export type userFormProps = {
defaultValues?: UserType;
userId?: string;
}
export const UserForm = (props: userFormProps) => {
const isCreate = !Boolean(props.defaultValues)
const form = useZodForm({
schema: UserSchema,
defaultValues: props.defaultValues,
});
const router = useRouter();
const { data: session, update } = useSession();
const mutation = useMutation({
mutationFn: async (values: UserType) => {
console.log("values", values)
console.log(props.userId)
const updateUser = await updateUserAction({
id: props.userId ?? "-",
data: values
})
const data = updateUser?.data?.data
if (updateUser?.serverError || !data) {
console.log(updateUser?.serverError);
toast.error(updateUser?.serverError);
return;
}
console.log("email:", values.email)
const newSession = {
...session,
user: {
...session?.user,
name: values.name,
email: values.email
},
};
const updateSession = await update(newSession);
console.log(updateSession);
toast.success(`Success updating user informations`);
router.push(`/dashboard/profile`);
router.refresh()
}
})
return (
<TooltipProvider>
<Card>
<CardHeader>
<CardTitle>
Account
</CardTitle>
<CardDescription>
Your informations
</CardDescription>
</CardHeader>
<CardContent>
<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={"Your Name"} {...field} />
</FormControl>
<FormMessage/>
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({field}) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
placeholder={'exemple@portabase.com'} disabled {...field}
value={field.value ?? ""}/>
</FormControl>
<FormMessage/>
</FormItem>
)}
/>
<Button>
{isCreate ? `` : `Save`}
</Button>
</Form>
</CardContent>
</Card>
</TooltipProvider>
)
}
@@ -0,0 +1,26 @@
"use server"
import {userAction} from "@/safe-actions";
import {z} from "zod";
import {prisma} from "@/prisma";
import {UserSchema} from "@/components/wrappers/Dashboard/Profile/UserForm/user-form.schema";
export const updateUserAction = userAction
.schema(
z.object({
id: z.string(),
data: UserSchema,
}
)
)
.action(async ({parsedInput, ctx}) => {
const updatedUser = await prisma.user.update({
where: {
id: parsedInput.id,
},
data: parsedInput.data,
})
return {
data: updatedUser,
}
})
@@ -0,0 +1,8 @@
import {z} from "zod";
export const UserSchema = z.object({
name: z.string(),
email: z.string(),
});
export type UserType = z.infer<typeof UserSchema>;
@@ -13,27 +13,31 @@ import {
} from "lucide-react";
import {LoggedInButton} from "@/components/wrappers/Dashboard/LoggedInButton/LoggedInButton";
import {SidebarMenuCustom} from "@/components/wrappers/Dashboard/SideBar/SideBarMenu/SideBarMenu";
import Image from 'next/image';
export function AppSidebar() {
return (
<Sidebar collapsible="icon">
<SidebarHeader>
<div className="flex justify-center items-center ">
<h1 className="font-bold text-xl">Portabase</h1>
</div>
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton>
Select Workspace
Select Project
<ChevronDown className="ml-auto"/>
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[--radix-popper-anchor-width]">
<DropdownMenuItem>
<span>Acme Inc</span>
<span>Project 1</span>
</DropdownMenuItem>
<DropdownMenuItem>
<span>Acme Corp.</span>
<span>Project 2</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -54,6 +58,9 @@ export function AppSidebar() {
<LoggedInButton/>
</SidebarMenuItem>
</SidebarMenu>
<div className="text-center">
<h1 className="text-[10px]">Portabase Community Edition 1.0.0</h1>
</div>
</SidebarFooter>
</Sidebar>
)
+14 -11
View File
@@ -1,4 +1,6 @@
import {PropsWithChildren} from 'react';
import {twx} from "@/lib/twx";
import {cn} from "@/lib/utils";
export const Page = ({children}: PropsWithChildren<{}>) => {
return (
@@ -12,17 +14,17 @@ export const PageHeader = ({children}: PropsWithChildren<{}>) => {
);
};
export const PageTitle = ({children}: PropsWithChildren<{}>) => {
return (
<h1 className="text-3xl font-bold mb-6">{children}</h1>
);
};
export const PageDescription = ({children}: PropsWithChildren<{}>) => {
return (
<h2 className="text-s mb-6 text-gray-700">{children}</h2>
);
};
export const PageTitle = twx.h1((props)=>[
cn(`text-3xl font-bold mb-6`, props.className),
])
export const PageDescription = twx.h2((props)=>[
cn(`text-s mb-6 text-gray-700`, props.className),
])
export const PageActions = ({children}: PropsWithChildren<{}>) => {
return (
@@ -35,4 +37,5 @@ export const PageContent = ({children}: PropsWithChildren<{}>) => {
return (
<div className="">{children}</div>
);
};
};