mirror of
https://github.com/Portabase/portabase.git
synced 2026-07-14 11:16:13 +02:00
Working on bugs, add delete restore. Review the auth style. working on the RBAC.
This commit is contained in:
+37
-9
@@ -1,19 +1,47 @@
|
|||||||
import React from "react";
|
"use client"
|
||||||
|
import React, {useEffect, useState} from "react";
|
||||||
import {LayoutAdmin} from "@/components/layout";
|
import {LayoutAdmin} from "@/components/layout";
|
||||||
|
import Image from "next/image";
|
||||||
|
import {env} from "@/env.mjs";
|
||||||
|
import {useTheme} from "next-themes";
|
||||||
|
|
||||||
|
|
||||||
export default async function Layout({children}: { children: React.ReactNode }) {
|
export default function Layout({children}: { children: React.ReactNode }) {
|
||||||
|
|
||||||
|
const { resolvedTheme } = useTheme();
|
||||||
|
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!mounted) return null;
|
||||||
|
|
||||||
|
const imageTheme = resolvedTheme === "dark" ? "/images/logo-white.png" : "/images/logo-black.png";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LayoutAdmin>
|
<div className="flex min-h-full flex-1 flex-col justify-center py-12 sm:px-6 lg:px-8 ">
|
||||||
<div
|
<div className="mx-auto w-full max-w-md">
|
||||||
className="w-full h-full grid "
|
<div className="sm:mx-auto sm:w-full sm:max-w-md flex items-center justify-center space-x-2">
|
||||||
>
|
<Image
|
||||||
<div className="flex items-center justify-center py-12">
|
className="p-12 text-black dark:text-white"
|
||||||
{children}
|
src={imageTheme}
|
||||||
|
loading="eager"
|
||||||
|
alt="Logo"
|
||||||
|
width={1024}
|
||||||
|
height={1024}
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
className="text-sm text-muted-foreground -ml-12 -mb-12">
|
||||||
|
v{env.NEXT_PUBLIC_PROJECT_VERSION}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div>{children}</div>
|
||||||
</div>
|
</div>
|
||||||
</LayoutAdmin>
|
<footer className="py-4 text-center text-xs justify-items-end text-muted-foreground">
|
||||||
|
Powered by <span className="font-medium">Soluce Technologies</span>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import {useEffect, useRef} from "react";
|
import {useEffect, useRef, useState} from "react";
|
||||||
import {useSearchParams} from "next/navigation";
|
import {useSearchParams} from "next/navigation";
|
||||||
|
|
||||||
import {LoginForm} from "@/components/wrappers/auth/login/loginForm/LoginForm";
|
import {LoginForm} from "@/components/wrappers/auth/login/loginForm/LoginForm";
|
||||||
@@ -10,19 +10,22 @@ export default function SignInPage(props: {
|
|||||||
searchParams: Promise<{ callbackUrl: string | undefined }>
|
searchParams: Promise<{ callbackUrl: string | undefined }>
|
||||||
}) {
|
}) {
|
||||||
|
|
||||||
const searchParams = useSearchParams();
|
const [urlParams, setUrlParams] = useState<URLSearchParams>();
|
||||||
const error = searchParams.get("error");
|
|
||||||
const isFirstRender = useRef(true);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isFirstRender.current && error) {
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
toast.error("Error occurred.");
|
setUrlParams(urlParams);
|
||||||
isFirstRender.current = false;
|
const error = urlParams.get("error");
|
||||||
|
console.log(urlParams.get("redirect"));
|
||||||
|
if (error?.includes("pending")) {
|
||||||
|
toast.error("Your account is not active.");
|
||||||
|
urlParams.delete("error");
|
||||||
|
window.history.replaceState({}, document.title, window.location.pathname + "?" + urlParams.toString());
|
||||||
}
|
}
|
||||||
}, [error]);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto grid w-[350px] gap-6">
|
<div className="mx-auto grid w-full gap-6">
|
||||||
<LoginForm/>
|
<LoginForm/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {RegisterForm} from "@/components/wrappers/auth/register/register-form/re
|
|||||||
|
|
||||||
export default async function RoutePage(props: PageParams<{}>) {
|
export default async function RoutePage(props: PageParams<{}>) {
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto grid w-[350px] gap-6">
|
<div className="mx-auto grid w-full gap-6">
|
||||||
<RegisterForm/>
|
<RegisterForm/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -24,8 +24,7 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
|
|||||||
databases: true
|
databases: true
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
//
|
|
||||||
console.log(agent)
|
|
||||||
|
|
||||||
if (!agent) {
|
if (!agent) {
|
||||||
notFound()
|
notFound()
|
||||||
@@ -33,6 +32,13 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
|
|||||||
//
|
//
|
||||||
// const databaseId = 'db-123';
|
// const databaseId = 'db-123';
|
||||||
//
|
//
|
||||||
|
|
||||||
|
console.log("agent",agent)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// const totalBackupsResult = await db
|
// const totalBackupsResult = await db
|
||||||
// .select({ count: drizzleDb.schemas.backup.id })
|
// .select({ count: drizzleDb.schemas.backup.id })
|
||||||
// .from(drizzleDb.schemas.backup)
|
// .from(drizzleDb.schemas.backup)
|
||||||
@@ -67,11 +73,6 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
|
|||||||
href={`/dashboard/agents/${agent.id}/edit`}>
|
href={`/dashboard/agents/${agent.id}/edit`}>
|
||||||
<GearIcon className="w-7 h-7"/>
|
<GearIcon className="w-7 h-7"/>
|
||||||
</Link>
|
</Link>
|
||||||
{/*<AgentModalKey agent={agent}>*/}
|
|
||||||
{/* <Button variant="outline">*/}
|
|
||||||
{/* <KeyRound/>*/}
|
|
||||||
{/* </Button>*/}
|
|
||||||
{/*</AgentModalKey>*/}
|
|
||||||
</PageTitle>
|
</PageTitle>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
@@ -80,9 +81,9 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
|
|||||||
<div className="flex flex-col sm:flex-row sm:justify-between gap-8 mb-6">
|
<div className="flex flex-col sm:flex-row sm:justify-between gap-8 mb-6">
|
||||||
<Card className="w-full sm:w-auto flex-1">
|
<Card className="w-full sm:w-auto flex-1">
|
||||||
<CardHeader className="font-bold text-xl">
|
<CardHeader className="font-bold text-xl">
|
||||||
Backups
|
Databases
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent></CardContent>
|
<CardContent>{agent.databases.length}</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Card className="w-full sm:w-auto flex-1">
|
<Card className="w-full sm:w-auto flex-1">
|
||||||
<CardHeader className="font-bold text-xl">
|
<CardHeader className="font-bold text-xl">
|
||||||
@@ -102,7 +103,7 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
|
|||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
<Card className="w-full sm:w-auto flex-1">
|
<Card className="w-full sm:w-auto flex-1 mb-4">
|
||||||
<CardHeader className="font-bold text-xl">
|
<CardHeader className="font-bold text-xl">
|
||||||
Edge Key
|
Edge Key
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
@@ -110,7 +111,7 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
|
|||||||
<AgentCardKey agent={agent}/>
|
<AgentCardKey agent={agent}/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<CardsWithPagination data={agent.databases} cardItem={DatabaseCard}/>
|
<CardsWithPagination cardsPerPage={2} data={agent.databases} cardItem={DatabaseCard}/>
|
||||||
</PageContent>
|
</PageContent>
|
||||||
</Page>
|
</Page>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,20 +1,29 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { authClient } from "@/lib/auth/auth-client";
|
import { authClient } from "@/lib/auth/auth-client";
|
||||||
import { PageParams } from "@/types/next";
|
import { PageParams } from "@/types/next";
|
||||||
|
import {Page, PageHeader, PageTitle} from "@/features/layout/page";
|
||||||
|
|
||||||
export default function RoutePage(props: PageParams<{}>) {
|
export default function RoutePage(props: PageParams<{}>) {
|
||||||
const { data: activeOrganization } = authClient.useActiveOrganization();
|
const { data: activeOrganization } = authClient.useActiveOrganization();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-1 flex-col gap-4 p-4">
|
<Page>
|
||||||
<div className="grid auto-rows-min gap-4 md:grid-cols-3">
|
<PageHeader>
|
||||||
<div className="aspect-video rounded-xl bg-muted/50" />
|
<PageTitle>Dashboard</PageTitle>
|
||||||
<div className="aspect-video rounded-xl bg-muted/50" />
|
</PageHeader>
|
||||||
<div className="aspect-video rounded-xl bg-muted/50" />
|
|
||||||
|
<div className="flex flex-1 flex-col gap-4">
|
||||||
|
<div className="grid auto-rows-min gap-4 md:grid-cols-3">
|
||||||
|
<div className="aspect-video rounded-xl bg-muted/50" />
|
||||||
|
<div className="aspect-video rounded-xl bg-muted/50" />
|
||||||
|
<div className="aspect-video rounded-xl bg-muted/50" />
|
||||||
|
</div>
|
||||||
|
{/*<div className="min-h-[100vh] flex-1 rounded-xl bg-muted/50 md:min-h-min" />*/}
|
||||||
|
{/*{JSON.stringify(activeOrganization)}*/}
|
||||||
|
{/*{activeOrganization?.name}*/}
|
||||||
</div>
|
</div>
|
||||||
<div className="min-h-[100vh] flex-1 rounded-xl bg-muted/50 md:min-h-min" />
|
|
||||||
{JSON.stringify(activeOrganization)}
|
</Page>
|
||||||
{activeOrganization?.name}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export default async function RoutePage(props: PageParams<{
|
|||||||
|
|
||||||
if (!proj) notFound();
|
if (!proj) notFound();
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Page>
|
<Page>
|
||||||
<div className="justify-between gap-2 sm:flex">
|
<div className="justify-between gap-2 sm:flex">
|
||||||
@@ -62,6 +63,7 @@ export default async function RoutePage(props: PageParams<{
|
|||||||
<CardsWithPagination
|
<CardsWithPagination
|
||||||
data={proj.databases}
|
data={proj.databases}
|
||||||
organizationSlug={organization.slug}
|
organizationSlug={organization.slug}
|
||||||
|
// @ts-ignore
|
||||||
cardItem={ProjectDatabaseCard}
|
cardItem={ProjectDatabaseCard}
|
||||||
cardsPerPage={4}
|
cardsPerPage={4}
|
||||||
numberOfColumns={1}
|
numberOfColumns={1}
|
||||||
|
|||||||
+13
-1
@@ -3,9 +3,11 @@ import { loggingMiddleware } from "@/middleware/loggingMiddleware";
|
|||||||
import { errorHandler } from "@/middleware/errorHandler";
|
import { errorHandler } from "@/middleware/errorHandler";
|
||||||
import { auth } from "@/lib/auth/auth";
|
import { auth } from "@/lib/auth/auth";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
|
import { signOut } from "@/lib/auth/auth-client";
|
||||||
|
|
||||||
export async function middleware(request: NextRequest) {
|
export async function middleware(request: NextRequest) {
|
||||||
const url = request.nextUrl.clone();
|
const url = request.nextUrl.clone();
|
||||||
|
const redirectUrl = encodeURIComponent(request.nextUrl.pathname)
|
||||||
|
|
||||||
if (url.pathname.startsWith("/dashboard")) {
|
if (url.pathname.startsWith("/dashboard")) {
|
||||||
const session = await auth.api.getSession({
|
const session = await auth.api.getSession({
|
||||||
@@ -13,7 +15,17 @@ export async function middleware(request: NextRequest) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!session) {
|
if (!session) {
|
||||||
return NextResponse.redirect(new URL("/login", request.url));
|
return NextResponse.redirect(new URL(`/login?redirect=${redirectUrl}`, request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.user.banned) {
|
||||||
|
signOut();
|
||||||
|
return NextResponse.redirect(new URL("/login?error=banned", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.user.role === "pending") {
|
||||||
|
signOut();
|
||||||
|
return NextResponse.redirect(new URL(`/login?error=pending?redirect=${redirectUrl}`, request.url));
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.next();
|
return NextResponse.next();
|
||||||
|
|||||||
+34
-34
@@ -50,40 +50,40 @@ const nextConfig: NextConfig = {
|
|||||||
experimental: {
|
experimental: {
|
||||||
nodeMiddleware: true,
|
nodeMiddleware: true,
|
||||||
},
|
},
|
||||||
async headers() {
|
// async headers() {
|
||||||
return [
|
// return [
|
||||||
{
|
// {
|
||||||
source: "/(.*)",
|
// source: "/(.*)",
|
||||||
headers: [
|
// headers: [
|
||||||
{
|
// {
|
||||||
key: "Content-Security-Policy",
|
// key: "Content-Security-Policy",
|
||||||
value: buildCSPHeader(),
|
// value: buildCSPHeader(),
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
key: "Permissions-Policy",
|
// key: "Permissions-Policy",
|
||||||
value: buildPermissionsPolicy(),
|
// value: buildPermissionsPolicy(),
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
key: 'X-Content-Type-Options',
|
// key: 'X-Content-Type-Options',
|
||||||
value: 'nosniff',
|
// value: 'nosniff',
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
key: 'X-Frame-Options',
|
// key: 'X-Frame-Options',
|
||||||
value: 'DENY',
|
// value: 'DENY',
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
key: 'Referrer-Policy',
|
// key: 'Referrer-Policy',
|
||||||
value: 'strict-origin-when-cross-origin',
|
// value: 'strict-origin-when-cross-origin',
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
key: 'Strict-Transport-Security',
|
// key: 'Strict-Transport-Security',
|
||||||
value: 'max-age=63072000; includeSubDomains; preload',
|
// value: 'max-age=63072000; includeSubDomains; preload',
|
||||||
}
|
// }
|
||||||
// ...other security headers
|
// // ...other security headers
|
||||||
],
|
// ],
|
||||||
},
|
// },
|
||||||
];
|
// ];
|
||||||
},
|
// },
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export function CardsWithPagination<T>(props: CardsWithPaginationProps<T>) {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<PaginationNavigation
|
<PaginationNavigation
|
||||||
className="justify-end"
|
className="justify-end mt-4"
|
||||||
totalPages={totalPages}
|
totalPages={totalPages}
|
||||||
currentPage={currentPage}
|
currentPage={currentPage}
|
||||||
goToPage={goToPage}
|
goToPage={goToPage}
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ export type ConnectionCircleProps = {
|
|||||||
export const ConnectionCircle = ({ date }: ConnectionCircleProps) => {
|
export const ConnectionCircle = ({ date }: ConnectionCircleProps) => {
|
||||||
let style = "bg-gray-300 border-gray-400";
|
let style = "bg-gray-300 border-gray-400";
|
||||||
|
|
||||||
if (date) {
|
if (date instanceof Date && !isNaN(date.getTime())) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const timestamp = new Date(date).getTime();
|
const timestamp = date.getTime();
|
||||||
const interval = now - timestamp;
|
const interval = now - timestamp;
|
||||||
|
|
||||||
|
console.log({ now, timestamp, interval });
|
||||||
|
|
||||||
if (interval < 10000) {
|
if (interval < 10000) {
|
||||||
style = "bg-green-400 border-green-600";
|
style = "bg-green-400 border-green-600";
|
||||||
} else if (interval <= 20000) {
|
} else if (interval <= 20000) {
|
||||||
@@ -19,7 +21,11 @@ export const ConnectionCircle = ({ date }: ConnectionCircleProps) => {
|
|||||||
} else {
|
} else {
|
||||||
style = "bg-red-400 border-red-600";
|
style = "bg-red-400 border-red-600";
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
console.warn("Invalid date passed to ConnectionCircle:", date);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(style);
|
||||||
|
|
||||||
return <div className={cn("w-5 h-5 rounded-full border-4", style)} />;
|
return <div className={cn("w-5 h-5 rounded-full border-4", style)} />;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,13 +14,13 @@ export const AgentCard = (props: agentCardProps) => {
|
|||||||
const { data: agent } = props;
|
const { data: agent } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link href={`/dashboard/agents/${agent.id}`}>
|
<Link href={`/dashboard/agents/${agent.id}`} className="block transition-all duration-200 hover:scale-[1.01] hover:shadow-md">
|
||||||
<Card className="flex flex-row justify-between">
|
<Card className="flex flex-row justify-between">
|
||||||
<div className="">
|
<div>
|
||||||
<CardHeader>{agent.name}</CardHeader>
|
<CardHeader className="text-2xl font-bold">{agent.name}</CardHeader>
|
||||||
<CardContent>Last contact : {formatDateLastContact(agent.lastContact)}</CardContent>
|
<CardContent>Last contact: {formatDateLastContact(agent.lastContact)}</CardContent>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 mr-3">
|
<div className="flex items-center px-4">
|
||||||
<ConnectionCircle date={agent.lastContact} />
|
<ConnectionCircle date={agent.lastContact} />
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import {Card, CardContent} from "@/components/ui/card";
|
||||||
import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, useZodForm } from "@/components/ui/form";
|
import {
|
||||||
import { Input } from "@/components/ui/input";
|
FormControl,
|
||||||
import { Form } from "@/components/ui/form";
|
FormDescription,
|
||||||
import { Button } from "@/components/ui/button";
|
FormField,
|
||||||
import { useRouter } from "next/navigation";
|
FormItem,
|
||||||
import { useMutation } from "@tanstack/react-query";
|
FormLabel,
|
||||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
FormMessage,
|
||||||
import { AgentSchema, AgentType } from "@/components/wrappers/dashboard/agent/AgentForm/agent-form.schema";
|
useZodForm
|
||||||
import { toast } from "sonner";
|
} from "@/components/ui/form";
|
||||||
import { createAgentAction, updateAgentAction } from "@/components/wrappers/dashboard/agent/AgentForm/agent-form.action";
|
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/dashboard/agent/AgentForm/agent-form.schema";
|
||||||
|
import {toast} from "sonner";
|
||||||
|
import {createAgentAction, updateAgentAction} from "@/components/wrappers/dashboard/agent/AgentForm/agent-form.action";
|
||||||
|
|
||||||
export type agentFormProps = {
|
export type agentFormProps = {
|
||||||
defaultValues?: AgentType;
|
defaultValues?: AgentType;
|
||||||
@@ -29,14 +37,13 @@ export const AgentForm = (props: agentFormProps) => {
|
|||||||
|
|
||||||
const mutation = useMutation({
|
const mutation = useMutation({
|
||||||
mutationFn: async (values: AgentType) => {
|
mutationFn: async (values: AgentType) => {
|
||||||
console.log("values", values);
|
|
||||||
|
|
||||||
const createAgent = isCreate
|
const createAgent = isCreate
|
||||||
? await createAgentAction(values)
|
? await createAgentAction(values)
|
||||||
: await updateAgentAction({
|
: await updateAgentAction({
|
||||||
id: props.agentId ?? "-",
|
id: props.agentId ?? "-",
|
||||||
data: values,
|
data: values,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = createAgent?.data?.data;
|
const data = createAgent?.data?.data;
|
||||||
if (createAgent?.serverError || !data) {
|
if (createAgent?.serverError || !data) {
|
||||||
@@ -44,7 +51,7 @@ export const AgentForm = (props: agentFormProps) => {
|
|||||||
toast.error(createAgent?.serverError);
|
toast.error(createAgent?.serverError);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
toast.success(`Success`);
|
toast.success(`Success ${isCreate ? "creating" : "updating"} agent`);
|
||||||
router.push(`/dashboard/agents/${data.id}`);
|
router.push(`/dashboard/agents/${data.id}`);
|
||||||
router.refresh();
|
router.refresh();
|
||||||
},
|
},
|
||||||
@@ -65,37 +72,14 @@ export const AgentForm = (props: agentFormProps) => {
|
|||||||
control={form.control}
|
control={form.control}
|
||||||
name="name"
|
name="name"
|
||||||
defaultValue=""
|
defaultValue=""
|
||||||
render={({ field }) => (
|
render={({field}) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Name</FormLabel>
|
<FormLabel>Name</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="Agent 1" {...field} />
|
<Input placeholder="Agent 1" {...field} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormDescription>Your agent project name</FormDescription>
|
<FormDescription>Your agent project name</FormDescription>
|
||||||
<FormMessage />
|
<FormMessage/>
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
defaultValue=""
|
|
||||||
name="slug"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>Slug</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Input
|
|
||||||
//value={field.value ?? ""}
|
|
||||||
placeholder="agent-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>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
@@ -103,14 +87,15 @@ export const AgentForm = (props: agentFormProps) => {
|
|||||||
control={form.control}
|
control={form.control}
|
||||||
defaultValue=""
|
defaultValue=""
|
||||||
name="description"
|
name="description"
|
||||||
render={({ field }) => (
|
render={({field}) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Description</FormLabel>
|
<FormLabel>Description</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="This agent is for the client exemple.com" {...field} value={field.value ?? ""} />
|
<Input placeholder="This agent is for the client exemple.com" {...field}
|
||||||
|
value={field.value ?? ""}/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
<FormDescription>Enter your project agent description</FormDescription>
|
<FormDescription>Enter your project agent description</FormDescription>
|
||||||
<FormMessage />
|
<FormMessage/>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
"use server";
|
"use server";
|
||||||
import { ActionError, userAction } from "@/safe-actions";
|
import {ActionError, userAction} from "@/safe-actions";
|
||||||
import { AgentSchema } from "@/components/wrappers/dashboard/agent/AgentForm/agent-form.schema";
|
import {AgentSchema} from "@/components/wrappers/dashboard/agent/AgentForm/agent-form.schema";
|
||||||
import { z } from "zod";
|
import {z} from "zod";
|
||||||
import { eq, and, ne, count } from "drizzle-orm";
|
import {eq, and, ne, count} from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import {db} from "@/db";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
|
import {slugify} from "@/utils/slugify";
|
||||||
|
|
||||||
const verifySlugUniqueness = async (slug: string, agentId?: string) => {
|
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 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);
|
const [countResult] = await db.select({count: count()}).from(drizzleDb.schemas.agent).where(conditions);
|
||||||
|
|
||||||
if (countResult.count > 0) {
|
if (countResult.count > 0) {
|
||||||
throw new ActionError("Slug already exists");
|
throw new ActionError("Slug already exists");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createAgentAction = userAction.schema(AgentSchema).action(async ({ parsedInput }) => {
|
export const createAgentAction = userAction.schema(AgentSchema).action(async ({parsedInput}) => {
|
||||||
await verifySlugUniqueness(parsedInput.slug);
|
const slug = slugify(parsedInput.name);
|
||||||
|
await verifySlugUniqueness(slug);
|
||||||
const [createdAgent] = await db.insert(drizzleDb.schemas.agent).values(parsedInput).returning();
|
const [createdAgent] = await db.insert(drizzleDb.schemas.agent).values({...parsedInput, slug: slug}).returning();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data: createdAgent,
|
data: createdAgent,
|
||||||
};
|
};
|
||||||
@@ -33,10 +33,14 @@ export const updateAgentAction = userAction
|
|||||||
data: AgentSchema,
|
data: AgentSchema,
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.action(async ({ parsedInput }) => {
|
.action(async ({parsedInput}) => {
|
||||||
await verifySlugUniqueness(parsedInput.data.slug, parsedInput.id);
|
const slug = slugify(parsedInput.data.name);
|
||||||
|
await verifySlugUniqueness(slug, parsedInput.id);
|
||||||
|
|
||||||
const [updatedAgent] = await db.update(drizzleDb.schemas.agent).set(parsedInput.data).where(eq(drizzleDb.schemas.agent.id, parsedInput.id)).returning();
|
const [updatedAgent] = await db.update(drizzleDb.schemas.agent).set({
|
||||||
|
...parsedInput.data,
|
||||||
|
slug: slug
|
||||||
|
}).where(eq(drizzleDb.schemas.agent.id, parsedInput.id)).returning();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data: updatedAgent,
|
data: updatedAgent,
|
||||||
|
|||||||
@@ -2,11 +2,6 @@ import { z } from "zod";
|
|||||||
|
|
||||||
export const AgentSchema = z.object({
|
export const AgentSchema = z.object({
|
||||||
name: z.string(),
|
name: z.string(),
|
||||||
slug: z
|
|
||||||
.string()
|
|
||||||
.regex(/^[a-zA-Z0-9_-]*$/)
|
|
||||||
.min(5)
|
|
||||||
.max(25),
|
|
||||||
description: z.string(),
|
description: z.string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -41,13 +41,10 @@ export const DatabaseTabs = (props: DatabaseTabsProps) => {
|
|||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<TabsContent className="h-full justify-between" value="backup">
|
<TabsContent className="h-full justify-between" value="backup">
|
||||||
|
|
||||||
{/*<DataTable columns={backupColumns} data={props.backups} extendedProps={props.isAlreadyRestore} />*/}
|
|
||||||
<DataTable columns={backupColumns(props.isAlreadyRestore)} data={props.backups} enablePagination />
|
<DataTable columns={backupColumns(props.isAlreadyRestore)} data={props.backups} enablePagination />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent className="h-full justify-between" value="restore">
|
<TabsContent className="h-full justify-between" value="restore">
|
||||||
<DataTable columns={restoreColumns} data={props.restorations} enablePagination />
|
<DataTable columns={restoreColumns(props.isAlreadyRestore)} data={props.restorations} enablePagination />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,10 +13,10 @@ export const ProjectCard = (props: projectCardProps) => {
|
|||||||
const { data: project, organizationSlug } = props;
|
const { data: project, organizationSlug } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link href={`/dashboard/projects/${project.id}`}>
|
<Link href={`/dashboard/projects/${project.id}`} className="block transition-all duration-200 hover:scale-[1.01] hover:shadow-md">
|
||||||
<Card className="flex flex-row justify-between">
|
<Card className="flex flex-row justify-between">
|
||||||
<div className="">
|
<div className="">
|
||||||
<CardHeader>{project.name}</CardHeader>
|
<CardHeader className="text-2xl font-bold">{project.name}</CardHeader>
|
||||||
<CardContent>{project.databases.length} databases</CardContent>
|
<CardContent>{project.databases.length} databases</CardContent>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
|||||||
import { ConnectionCircle } from "@/components/wrappers/common/connection-circle";
|
import { ConnectionCircle } from "@/components/wrappers/common/connection-circle";
|
||||||
import { formatDateLastContact } from "@/utils/date-formatting";
|
import { formatDateLastContact } from "@/utils/date-formatting";
|
||||||
import {Database} from "@/db/schema/06_database";
|
import {Database} from "@/db/schema/06_database";
|
||||||
|
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
|
||||||
|
|
||||||
export type projectDatabaseCardProps = {
|
export type projectDatabaseCardProps = {
|
||||||
data: Database;
|
data: Database;
|
||||||
@@ -17,7 +18,7 @@ export const ProjectDatabaseCard = (props: projectDatabaseCardProps) => {
|
|||||||
const { organizationSlug, data: database, extendedProps: extendedProps } = props;
|
const { organizationSlug, data: database, extendedProps: extendedProps } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link href={`/dashboard/projects/${extendedProps.id}/database/${database.id}`}>
|
<Link className="block transition-all duration-200 hover:scale-[1.01] hover:shadow-md" href={`/dashboard/projects/${extendedProps.id}/database/${database.id}`}>
|
||||||
<DatabaseCard data={database} />
|
<DatabaseCard data={database} />
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
@@ -31,15 +32,21 @@ export const DatabaseCard = (props: databaseCardProps) => {
|
|||||||
const { data: database } = props;
|
const { data: database } = props;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
||||||
<Card className="flex flex-row justify-between">
|
<Card className="flex flex-row justify-between">
|
||||||
<div className="flex flex-row items-center gap-2">
|
<div className="flex items-center space-x-4 px-4">
|
||||||
<Image src="/PostgreSQL.png" alt="Database type Icon" width={60} height={60} className="object-cover ml-4" />
|
<Image src="/PostgreSQL.png" alt="Database type Icon" width={60} height={60} className="object-cover ml-4" />
|
||||||
<div>
|
|
||||||
<CardHeader>Name : {database.name}</CardHeader>
|
<div className="justify-between">
|
||||||
<CardContent>Last contact: {formatDateLastContact(database.lastContact)}</CardContent>
|
<div className="font-medium">Name: {database.name}</div>
|
||||||
|
<div className="text-sm text-muted-foreground">Generated Id: {database.agentDatabaseId}</div>
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
Last contact: {formatDateLastContact(database.lastContact)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 mr-3">
|
|
||||||
|
<div className="flex items-center px-4">
|
||||||
<ConnectionCircle date={database.lastContact} />
|
<ConnectionCircle date={database.lastContact} />
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { z } from "zod";
|
|||||||
|
|
||||||
export const ProjectSchema = z.object({
|
export const ProjectSchema = z.object({
|
||||||
name: z.string(),
|
name: z.string(),
|
||||||
slug: z.string(),
|
|
||||||
databases: z.array(z.string()),
|
databases: z.array(z.string()),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -103,27 +103,6 @@ export const ProjectForm = (props: projectFormProps) => {
|
|||||||
</FormItem>
|
</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
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="databases"
|
name="databases"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { eq, inArray } from "drizzle-orm";
|
|||||||
import {Project} from "@/db/schema/05_project";
|
import {Project} from "@/db/schema/05_project";
|
||||||
import * as drizzleDb from "@/db";
|
import * as drizzleDb from "@/db";
|
||||||
import {Database} from "@/db/schema/06_database";
|
import {Database} from "@/db/schema/06_database";
|
||||||
|
import {slugify} from "@/utils/slugify";
|
||||||
|
|
||||||
export const createProjectAction = userAction
|
export const createProjectAction = userAction
|
||||||
.schema(
|
.schema(
|
||||||
@@ -19,11 +20,12 @@ export const createProjectAction = userAction
|
|||||||
)
|
)
|
||||||
.action(async ({ parsedInput }): Promise<ServerActionResult<Project>> => {
|
.action(async ({ parsedInput }): Promise<ServerActionResult<Project>> => {
|
||||||
try {
|
try {
|
||||||
|
const slug = slugify(parsedInput.data.name);
|
||||||
const [createdProject] = await db
|
const [createdProject] = await db
|
||||||
.insert(drizzleDb.schemas.project)
|
.insert(drizzleDb.schemas.project)
|
||||||
.values({
|
.values({
|
||||||
name: parsedInput.data.name,
|
name: parsedInput.data.name,
|
||||||
slug: parsedInput.data.slug,
|
slug: slug,
|
||||||
organizationId: parsedInput.organizationId,
|
organizationId: parsedInput.organizationId,
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
@@ -87,12 +89,13 @@ export const updateProjectAction = userAction
|
|||||||
if (databasesToRemove.length > 0) {
|
if (databasesToRemove.length > 0) {
|
||||||
await db.update(drizzleDb.schemas.database).set({ projectId: null }).where(inArray(drizzleDb.schemas.database.id, databasesToRemove));
|
await db.update(drizzleDb.schemas.database).set({ projectId: null }).where(inArray(drizzleDb.schemas.database.id, databasesToRemove));
|
||||||
}
|
}
|
||||||
|
const slug = slugify(parsedInput.data.name);
|
||||||
|
|
||||||
const [updatedProject] = await db
|
const [updatedProject] = await db
|
||||||
.update(drizzleDb.schemas.project)
|
.update(drizzleDb.schemas.project)
|
||||||
.set({
|
.set({
|
||||||
name: parsedInput.data.name,
|
name: parsedInput.data.name,
|
||||||
slug: parsedInput.data.slug,
|
slug: slug,
|
||||||
})
|
})
|
||||||
.where(eq(drizzleDb.schemas.project.id, parsedInput.projectId))
|
.where(eq(drizzleDb.schemas.project.id, parsedInput.projectId))
|
||||||
.returning();
|
.returning();
|
||||||
|
|||||||
@@ -1,15 +1,33 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ColumnDef } from "@tanstack/react-table";
|
import { ColumnDef } from "@tanstack/react-table";
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { MoreHorizontal } from "lucide-react";
|
import {MoreHorizontal, Trash2} from "lucide-react";
|
||||||
import { ReloadIcon } from "@radix-ui/react-icons";
|
import { ReloadIcon } from "@radix-ui/react-icons";
|
||||||
import { StatusBadge } from "@/components/wrappers/common/status-badge";
|
import { StatusBadge } from "@/components/wrappers/common/status-badge";
|
||||||
import {Restoration} from "@/db/schema/06_database";
|
import {Backup, Restoration} from "@/db/schema/06_database";
|
||||||
import {formatFrenchDate} from "@/utils/date-formatting";
|
import {formatFrenchDate} from "@/utils/date-formatting";
|
||||||
|
import {useMutation} from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
deleteBackupAction,
|
||||||
|
deleteRestoreAction,
|
||||||
|
rerunRestorationAction
|
||||||
|
} from "@/features/dashboard/restore/restore.action";
|
||||||
|
import {toast} from "sonner";
|
||||||
|
import {useRouter} from "next/navigation";
|
||||||
|
import {TooltipCustom} from "@/components/wrappers/common/tooltipCustom/TooltipCustom";
|
||||||
|
|
||||||
export const restoreColumns: ColumnDef<Restoration>[] = [
|
|
||||||
|
export function restoreColumns(isAlreadyRestore: boolean): ColumnDef<Restoration>[] {
|
||||||
|
return[
|
||||||
{
|
{
|
||||||
accessorKey: "id",
|
accessorKey: "id",
|
||||||
header: "Reference",
|
header: "Reference",
|
||||||
@@ -31,6 +49,58 @@ export const restoreColumns: ColumnDef<Restoration>[] = [
|
|||||||
{
|
{
|
||||||
id: "actions",
|
id: "actions",
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
|
const status = row.getValue("status");
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
const rowData: Restoration = row.original;
|
||||||
|
|
||||||
|
|
||||||
|
const mutationDeleteRestore = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const restoration = await deleteRestoreAction({
|
||||||
|
restorationId: rowData.id,
|
||||||
|
});
|
||||||
|
// @ts-ignore
|
||||||
|
if (restoration.data.success) {
|
||||||
|
// @ts-ignore
|
||||||
|
toast.success(restoration.data.actionSuccess.message);
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
// @ts-ignore
|
||||||
|
toast.error(restoration.data.actionError.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const mutationRerunRestore = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const restoration = await rerunRestorationAction({
|
||||||
|
restorationId: rowData.id,
|
||||||
|
});
|
||||||
|
// @ts-ignore
|
||||||
|
if (restoration.data.success) {
|
||||||
|
// @ts-ignore
|
||||||
|
toast.success(restoration.data.actionSuccess.message);
|
||||||
|
router.refresh();
|
||||||
|
} else {
|
||||||
|
// @ts-ignore
|
||||||
|
toast.error(restoration.data.actionError.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
await mutationDeleteRestore.mutateAsync();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRerunRestore = async () => {
|
||||||
|
await mutationRerunRestore.mutateAsync();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
@@ -42,8 +112,26 @@ export const restoreColumns: ColumnDef<Restoration>[] = [
|
|||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
<DropdownMenuLabel>Actions</DropdownMenuLabel>
|
||||||
|
|
||||||
<DropdownMenuItem onClick={() => {}}>
|
<TooltipCustom disabled={isAlreadyRestore} text="Already a restoration waiting">
|
||||||
<ReloadIcon /> Rerun
|
<DropdownMenuItem
|
||||||
|
disabled={mutationRerunRestore.isPending || isAlreadyRestore}
|
||||||
|
onClick={async () => {
|
||||||
|
await handleRerunRestore();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ReloadIcon/> Rerun
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</TooltipCustom>
|
||||||
|
<DropdownMenuSeparator/>
|
||||||
|
|
||||||
|
<DropdownMenuItem
|
||||||
|
disabled={status == "waiting"}
|
||||||
|
className="text-red-600"
|
||||||
|
onClick={async () => {
|
||||||
|
await handleDelete();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Trash2/> Delete
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
@@ -51,3 +139,5 @@ export const restoreColumns: ColumnDef<Restoration>[] = [
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,43 @@ import { db } from "@/db";
|
|||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import {Backup, Restoration} from "@/db/schema/06_database";
|
import {Backup, Restoration} from "@/db/schema/06_database";
|
||||||
|
|
||||||
|
export const deleteRestoreAction = userAction
|
||||||
|
.schema(
|
||||||
|
z.object({
|
||||||
|
restorationId: z.string(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.action(async ({ parsedInput }): Promise<ServerActionResult<Backup>> => {
|
||||||
|
try {
|
||||||
|
await db
|
||||||
|
.delete(drizzleDb.schemas.restoration)
|
||||||
|
.where(and(eq(drizzleDb.schemas.restoration.id, parsedInput.restorationId)))
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
actionSuccess: {
|
||||||
|
message: "Restoration deleted successfully.",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
actionError: {
|
||||||
|
message: "Failed to delete restoration.",
|
||||||
|
status: 500,
|
||||||
|
cause: error instanceof Error ? error.message : "Unknown error",
|
||||||
|
messageParams: { message: "Error deleting the restoration" },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export const deleteBackupAction = userAction
|
export const deleteBackupAction = userAction
|
||||||
.schema(
|
.schema(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -60,6 +97,58 @@ export const deleteBackupAction = userAction
|
|||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const rerunRestorationAction = userAction
|
||||||
|
.schema(
|
||||||
|
z.object({
|
||||||
|
restorationId: z.string(),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.action(async ({ parsedInput }): Promise<ServerActionResult<Restoration>> => {
|
||||||
|
try {
|
||||||
|
const updateResult = await db
|
||||||
|
.update(drizzleDb.schemas.restoration)
|
||||||
|
.set({ status: "waiting" })
|
||||||
|
.where(eq(drizzleDb.schemas.restoration.id, parsedInput.restorationId))
|
||||||
|
.returning()
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
const updatedRestoration = updateResult[0];
|
||||||
|
|
||||||
|
if (!updatedRestoration) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
actionError: {
|
||||||
|
message: "Restoration not found.",
|
||||||
|
status: 404,
|
||||||
|
cause: "No restoration with the given ID exists.",
|
||||||
|
messageParams: { message: "Restoration not found" },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
value: updatedRestoration,
|
||||||
|
actionSuccess: {
|
||||||
|
message: "Restoration has been requeued.",
|
||||||
|
messageParams: { restorationId: updatedRestoration.id },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
actionError: {
|
||||||
|
message: "Failed to rerun restoration.",
|
||||||
|
status: 500,
|
||||||
|
cause: error instanceof Error ? error.message : "Unknown error",
|
||||||
|
messageParams: { message: "Error updating the restoration" },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
// Create Restoration Action (Drizzle version)
|
// Create Restoration Action (Drizzle version)
|
||||||
export const createRestorationAction = userAction
|
export const createRestorationAction = userAction
|
||||||
.schema(
|
.schema(
|
||||||
|
|||||||
+22
-6
@@ -113,25 +113,41 @@ export const auth = betterAuth({
|
|||||||
before: async (session, context) => {
|
before: async (session, context) => {
|
||||||
const userId = session.userId;
|
const userId = session.userId;
|
||||||
|
|
||||||
const memberships = await db.query.member.findMany({
|
|
||||||
|
let memberships = await db.query.member.findMany({
|
||||||
where: eq(drizzleDb.schemas.member.userId, userId),
|
where: eq(drizzleDb.schemas.member.userId, userId),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!memberships.length) {
|
if (!memberships.length) {
|
||||||
// Fail the login attempt explicitly
|
const defaultOrgSlug = "default";
|
||||||
throw new Error("User is not part of any organization.");
|
const defaultOrg = await db.query.organization.findFirst({
|
||||||
}
|
where: eq(drizzleDb.schemas.organization.slug, defaultOrgSlug),
|
||||||
|
});
|
||||||
|
|
||||||
const firstOrgId = memberships[0].organizationId;
|
if (!defaultOrg) {
|
||||||
|
throw new Error("No organization found. Cannot assign member.");
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.insert(drizzleDb.schemas.member).values({
|
||||||
|
userId,
|
||||||
|
organizationId: defaultOrg.id,
|
||||||
|
role: "member",
|
||||||
|
});
|
||||||
|
|
||||||
|
memberships = await db.query.member.findMany({
|
||||||
|
where: eq(drizzleDb.schemas.member.userId, userId),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
data: {
|
data: {
|
||||||
activeOrganizationId: firstOrgId,
|
activeOrganizationId: memberships[0].organizationId,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
},
|
},
|
||||||
session: {
|
session: {
|
||||||
additionalFields: {
|
additionalFields: {
|
||||||
|
|||||||
Reference in New Issue
Block a user