wrapping some agent components.

This commit is contained in:
killian-larcher
2024-11-11 18:50:42 +01:00
parent 49e069c849
commit 09529fb701
23 changed files with 338 additions and 156 deletions
@@ -3,28 +3,12 @@ import {Page, PageActions, PageContent, PageDescription, PageHeader, PageTitle}
import {Button} from "@/components/ui/button";
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {backupColumns} from "@/features/backup/columns";
import {restoreColumns} from "@/features/restore/columns";
import {TablePagination} from "@/components/wrappers/table/table-pagination";
import {columns} from "@/features/backup/columns";
import {DataTableWithPagination} from "@/components/wrappers/table/data-table-with-pagination";
import {prisma} from "@/prisma";
import {GearIcon} from "@radix-ui/react-icons";
import Link from "next/link";
export default async function RoutePage(props: PageParams<{ agentId: string }>) {
// const agent = await prisma.agent.findUnique({
// where: {
// id: props.params.agentId,
// },
// })
const agent = {
"id": props.params.agentId,
"name": "Agent 1",
"description": "My beautiful project!",
"lastContact": null,
}
export default async function RoutePage(props: PageParams<{}>) {
const backups = [
{'id': 'backup-1', 'createdAt': '2023-11-27T11:26:54.870914Z', 'status': 'pending'},
@@ -62,81 +46,55 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>)
{'id': 'restore-10', 'backupId': 'backup-10', 'createdAt': '2023-11-25T11:26:54.871000Z', 'status': 'failed'}
]
const databaseId = 'db-123';
const totalBackups = await prisma.backup.count({
where: {
databaseId: databaseId,
},
});
const successfulBackups = await prisma.backup.count({
where: {
databaseId: databaseId,
status: 'success',
},
});
const successRate = totalBackups > 0 ? (successfulBackups / totalBackups) * 100 : null
return (
<Page>
<PageHeader>
<PageTitle>
{agent.name}
<Link href={`/dashboard/agents/${agent.id}/edit`}>
<GearIcon className="w-7 h-7"/>
</Link>
Agent 1
</PageTitle>
<PageActions>
<Button>Backup</Button>
<Button>Restore</Button>
</PageActions>
</PageHeader>
<PageDescription>{agent.description}</PageDescription>
<PageDescription>My beautiful project!</PageDescription>
<PageContent className="flex flex-col w-full h-full">
<div className="flex flex-row sm:justify-between gap-8 mb-6">
<PageContent>
<div className="flex flex-row sm:justify-between gap-6 mb-8">
<Card className="w-full">
<CardHeader className="font-bold text-xl">
<CardHeader>
Backups
</CardHeader>
<CardContent></CardContent>
</Card>
<Card className="w-full">
<CardHeader className="font-bold text-xl">
<CardHeader>
Success rate
</CardHeader>
<CardContent>
{successRate ?? "Unavailable for now."}
</CardContent>
<CardContent></CardContent>
</Card>
<Card className="w-full">
<CardHeader className="font-bold text-xl">
<CardHeader>
Last contact
</CardHeader>
<CardContent>
{agent.lastContact?.toDateString() ?? "Never connected"}
</CardContent>
<CardContent></CardContent>
</Card>
</div>
<Tabs className="flex flex-col flex-1" defaultValue="backup">
<Tabs defaultValue="backup">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="backup">Backup</TabsTrigger>
<TabsTrigger value="restore">Backup</TabsTrigger>
<TabsTrigger value="restore">Restore</TabsTrigger>
</TabsList>
<TabsContent className="h-full justify-between" value="backup">
<DataTableWithPagination columns={backupColumns} data={backups}/>
<TabsContent className="flex flex-col gap-6" value="backup">
<DataTableWithPagination columns={columns} data={backups}/>
</TabsContent>
<TabsContent className="h-full justify-between" value="restore">
<DataTableWithPagination columns={restoreColumns} data={restores}/>
<TabsContent className="flex flex-col gap-6" value="restore">
<DataTableWithPagination columns={columns} data={restores}/>
</TabsContent>
</Tabs>
</PageContent>
</Page>
+1 -1
View File
@@ -36,7 +36,7 @@ export default async function RoutePage(props: PageParams<{}>) {
</PageActions>
</PageHeader>
<PageContent className="mt-10">
<PageContent>
<CardsWithPagination
data={agents}
cardItem={AgentCard}
+1 -1
View File
@@ -17,7 +17,7 @@ export default async function Layout({children}: { children: React.ReactNode })
<AppSidebar/>
<SidebarInset>
<Header/>
<main className="h-full">
<main>
{children}
</main>
</SidebarInset>
+17 -3
View File
@@ -6,6 +6,11 @@ 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";
import Link from "next/link";
import {Button} from "@/components/ui/button";
import {ButtonWithConfirm} from "@/components/wrappers/Button/ButtonWithConfirm/ButtonWithConfirm";
import {ButtonDeleteAccount} from "@/components/wrappers/Dashboard/Profile/ButtonDeleteAccount/ButtonDeleteAccount";
import {useIsMobile} from "@/hooks/use-mobile";
export default async function RoutePage(props: PageParams<{}>) {
@@ -22,9 +27,14 @@ export default async function RoutePage(props: PageParams<{}>) {
console.log(userInfo)
const test = () => {
console.log("test")
}
return (
<Page>
<PageHeader>
{/*<PageHeader>*/}
<div className="justify-between gap-2 sm:flex">
<PageTitle className="flex items-center">
<Avatar className="size-14 mr-3">
<AvatarFallback>{user.name?.[0]}</AvatarFallback>
@@ -33,9 +43,13 @@ export default async function RoutePage(props: PageParams<{}>) {
) : null}
</Avatar>
{user.name}
<Badge className="ml-3">{userInfo.authMethod}</Badge>
<Badge className="ml-3 hidden lg:block">{userInfo.authMethod}</Badge>
</PageTitle>
</PageHeader>
<PageActions className={"mt-2"}>
<ButtonDeleteAccount/>
</PageActions>
</div>
{/*</PageHeader>*/}
<PageContent>
<UserForm userId={userInfo.id} defaultValues={userInfo}/>
</PageContent>
+47
View File
@@ -0,0 +1,47 @@
import {prisma} from "@/prisma";
import {NextResponse} from "next/server";
export async function POST(
request: Request,
{params}: { params: Promise<{ agentId: string }> }
) {
const agentId = (await params).agentId
const agent = await prisma.agent.findFirst({
where: {
id: agentId
}
})
if(!agent){
return NextResponse.json({error: "Agent not found"}, {status: 404})
}
await prisma.agent.update({
where: {
id: agent.id,
},
data: {
lastContact: new Date(),
}
});
const response = {
agent: {
id: agentId,
lastContact: agent.lastContact
},
backup: {
action: false,
cron : ""
},
restore: {
action: false,
file: ""
}
}
return Response.json({
message: response
})
}
+39
View File
@@ -0,0 +1,39 @@
import {NextRequest, NextResponse} from 'next/server'
import {loggingMiddleware} from "@/middleware/loggingMiddleware";
import {errorHandler} from "@/middleware/errorHandler";
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone();
if (url.pathname.startsWith('/api')) {
const routeExists = checkRouteExists(url.pathname);
// If the route does not exist, return a 404 JSON response
if (!routeExists) {
return new NextResponse(
JSON.stringify({ message: "This API route does not exist.", status: 404 }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
);
}
}
try{
loggingMiddleware(request);
}catch(err){
errorHandler(err)
}
}
// Function to check if the route exists (supports dynamic routes)
function checkRouteExists(pathname) {
// Define static and dynamic routes with patterns
const routePatterns = [
//do not delete
// /^\/api\/auth\/\d+$/, // Dynamic route with a number as a parameter (e.g., /api/dynamic/123)
// /^\/api\/auth\/\w+$/, // Dynamic route with a number as a parameter (e.g., /api/dynamic/123)
// /^\/api\/agent\/healthcheck\/\w+$/, // Dynamic route with an alphanumeric parameter (e.g., /api/user/username)
/^\/api\/agent\/[^/]+\/status\/?$/, // Dynamic route for /api/agent/[id]/status
];
return routePatterns.some(pattern => pattern.test(pathname));
}
export const config = {
matcher: ['/api/agent/:path*'],
};
+2 -1
View File
@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack -p 80",
"dev": "next dev -p 80",
"build": "next build",
"start": "next start",
"lint": "next lint"
@@ -67,6 +67,7 @@
"sonner": "^1.6.1",
"tailwind-merge": "^2.5.4",
"tailwindcss-animate": "^1.0.7",
"uuid": "^11.0.3",
"vaul": "^1.1.1",
"zod": "^3.23.8"
},
+9 -22
View File
@@ -61,12 +61,12 @@ model User {
image String?
role String?
password String?
authMethod String? @map("auth_method")
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")
}
@@ -78,22 +78,18 @@ model Agent {
description String?
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")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
name String
description String?
backupPolicy String? @map("backup_policy")
createdAt DateTime @default(now()) @map("created_at")
agentId String @map("agent_id")
agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade)
backups Backup[]
restaurations Restauration[]
}
enum Status {
@@ -105,24 +101,15 @@ enum Status {
model Backup {
id String @id @default(cuid())
databaseId String @map("database_id")
status Status @default(waiting)
file String?
createdAt DateTime @default(now()) @map("created_at")
databaseId String @map("database_id")
database Database @relation(fields: [databaseId], references: [id], onDelete: Cascade)
restaurations Restauration[]
}
model Restauration {
model Restore {
id String @id @default(cuid())
backupId String @map("backup_id")
status Status @default(waiting)
createdAt DateTime @default(now()) @map("created_at")
backupId String @map("backup_id")
backup Backup @relation(fields: [backupId], references: [id], onDelete: Cascade)
databaseId String? @map("database_id")
database Database? @relation(fields: [databaseId], references: [id], onDelete: Cascade)
}
@@ -0,0 +1,45 @@
"use client"
import {Button} from "@/components/ui/button";
import {useState} from "react";
import {Loader2} from "lucide-react";
export type VariantButton = {
secondary: string
default: string
outline: string
ghost: string
link: string
destructive: string
}
export type ButtonWithConfirmProps = {
icon?: any,
text: string,
variant?: keyof VariantButton ,
className?: string,
onClick?: () => void,
isPending? : boolean
};
export const ButtonWithConfirm = (props: ButtonWithConfirmProps) => {
const [isConfirming, setIsConfirming] = useState(false)
return(
<Button
onClick={() => {
if (isConfirming) {
props.onClick()
} else {
setIsConfirming(true);
}
}}
variant={props.variant ? props.variant : "default"}
className={props.className}
>
{props.isPending && <Loader2 className="animate-spin mr-4" size={16}/>}
{isConfirming ? "Are you sure ?" : `${props.text}`}
<>
{props.icon ? props.icon : null}
</>
</Button>
)
}
@@ -0,0 +1,32 @@
"use client"
import {useMutation} from "@tanstack/react-query";
import {useRouter} from "next/navigation";
import {signOutAction} from "@/features/auth/auth.action";
import {ButtonWithConfirm} from "@/components/wrappers/Button/ButtonWithConfirm/ButtonWithConfirm";
import {deleteUserAction} from "@/components/wrappers/Dashboard/Profile/ButtonDeleteAccount/delete-account.action";
import {Trash2} from "lucide-react";
export type ButtonDeleteAccountProps = {}
export const ButtonDeleteAccount = (props: ButtonDeleteAccountProps) => {
const mutation = useMutation({
mutationFn: () => deleteUserAction(""),
onSuccess: async () => {
await signOutAction();
},
})
return (
<ButtonWithConfirm
text={"Delete my account"}
onClick={() => {
mutation.mutate()
}}
variant={"destructive"}
isPending={mutation.isPending}
className="gap-2"
icon={<Trash2/>}
/>
)
}
@@ -0,0 +1,42 @@
"use server"
import {userAction} from "@/safe-actions";
import {prisma} from "@/prisma";
import {z} from "zod";
import {v4 as uuidv4} from "uuid";
export const deleteUserAction = userAction
.schema(z.string())
.action(async ({parsedInput, ctx}) => {
const uuid = uuidv4()
const user = await prisma.user.update({
where: {
id: ctx.user.id,
},
data: {
email: `${uuid}@portabase.com`,
name: `${uuid}`,
}
})
const account = await prisma.account.findFirst({
where: {
userId: ctx.user.id,
}
})
if(account){
await prisma.account.delete({
where: {
id: account.id
}
})
}
return {
data: user,
}
});
@@ -42,14 +42,14 @@ export const CardsWithPagination = (props: cardsWithPaginationProps) => {
return (
<div className={cn("flex flex-col h-full justify-between", className)}>
<div className={cn(`grid h-max auto-rows-min gap-4 md:grid-cols-${numberOfColumns}`)}>
<div className={cn("", className)}>
<div className={cn(`grid auto-rows-min gap-4 md:grid-cols-${numberOfColumns}`)}>
{currentCards.map((card, key) => (
<CardItem key={key} {...card}/>
))}
</div>
<PaginationNavigation
className="justify-end"
className="mt-8 justify-end"
totalPages={totalPages}
currentPage={currentPage}
goToPage={goToPage}
@@ -25,7 +25,7 @@ export const PaginationNavigation = (props: paginationNavigationProps) => {
const {className, totalPages, currentPage, goToPage, goToPrevPage, goToNextPage, maxVisiblePages = 3} = props
return (
<Pagination className={cn("", className)}>
<Pagination className={cn("w-auto m-0", className)}>
<PaginationContent>
<PaginationItem>
<PaginationPrevious onClick={goToPrevPage}/>
@@ -30,9 +30,9 @@ export function DataTableWithPagination<TData, TValue>({columns, data}: DataTabl
})
return (
<div className="flex flex-col justify-between h-full">
<div>
<DataTable table={table}/>
<TablePagination table={table} pageSizeOptions={[5, 10, 20, 50, 100]}/>
<TablePagination table={table}/>
</div>
)
}
@@ -1,4 +1,3 @@
import {useEffect} from "react";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {cn} from "@/lib/utils";
@@ -13,12 +12,8 @@ export const TablePaginationSize = (props: tablePaginationSizeProps) => {
const {className, table, pageSizeOptions = [10, 20, 30, 40, 50]} = props
useEffect(() => {
table.setPageSize(Number(pageSizeOptions[0]))
}, []);
return (
<div className={cn("flex items-center justify-center space-x-2", className)}>
<div className={cn("flex items-center space-x-2", className)}>
<p className="whitespace-nowrap text-sm font-medium">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
@@ -8,17 +8,16 @@ interface tablePaginationProps {
className?: string
table: any
maxVisiblePages?: number
pageSizeOptions?: number[]
}
export function TablePagination(props: tablePaginationProps) {
const {className, table, maxVisiblePages = 3, pageSizeOptions = [10, 20, 30, 40, 50]} = props
const {className, table, maxVisiblePages = 3} = props
return (
<div className={cn("flex mt-6", className)}>
<TablePaginationSize table={table} pageSizeOptions={pageSizeOptions}/>
<TablePaginationNavigation table={table} maxVisiblePages={maxVisiblePages} className="justify-end"/>
<div className={cn("flex justify-between mt-8", className)}>
<TablePaginationSize table={table}/>
<TablePaginationNavigation table={table} maxVisiblePages={maxVisiblePages}/>
</div>
)
}
+1 -4
View File
@@ -18,7 +18,7 @@ export type Backup = {
status: "pending" | "processing" | "success" | "failed"
}
export const backupColumns: ColumnDef<Backup>[] = [
export const columns: ColumnDef<Backup>[] = [
{
accessorKey: "id",
header: "Reference",
@@ -26,9 +26,6 @@ export const backupColumns: ColumnDef<Backup>[] = [
{
accessorKey: "createdAt",
header: "Created At",
cell: ({row}) => {
return new Date(row.getValue("createdAt")).toLocaleString("fr-FR");
},
},
{
accessorKey: "status",
+24 -16
View File
@@ -1,33 +1,41 @@
import {PropsWithChildren} from 'react';
import {twx} from "@/lib/twx";
import {cn} from "@/lib/utils";
export const Page = ({children}: PropsWithChildren<{}>) => {
return (
<div className="flex flex-1 flex-col gap-4 px-10 py-6">{children}</div>
);
};
export const Page = twx.div((props) => [
cn(`flex flex-col h-full px-10 py-6`, props.className),
])
export const PageHeader = twx.div((props) => [
cn(`flex justify-between`, props.className),
])
export const PageHeader = ({children}: PropsWithChildren<{}>) => {
return (
<div className="flex justify-between">{children}</div>
);
};
export const PageTitle = twx.h1((props)=>[
cn(`text-3xl font-bold mb-6 flex gap-4 items-center`, props.className),
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 = twx.h1((props) => [
cn(`flex gap-4 h-fit`, props.className),
])
export const PageContent = twx.div((props) => [
cn(`h-full`, props.className),
])
export const PageActions = ({children}: PropsWithChildren<{}>) => {
return (
<h1 className="flex gap-4">{children}</h1>
);
};
export const PageContent = ({children}: PropsWithChildren<{}>) => {
return (
<div className="">{children}</div>
);
};
+1 -4
View File
@@ -18,7 +18,7 @@ export type Restore = {
status: "pending" | "processing" | "success" | "failed"
}
export const restoreColumns: ColumnDef<Restore>[] = [
export const columns: ColumnDef<Restore>[] = [
{
accessorKey: "id",
header: "Reference",
@@ -26,9 +26,6 @@ export const restoreColumns: ColumnDef<Restore>[] = [
{
accessorKey: "createdAt",
header: "Created At",
cell: ({row}) => {
return new Date(row.getValue("createdAt")).toLocaleString("fr-FR");
},
},
{
accessorKey: "status",
+8
View File
@@ -0,0 +1,8 @@
import {NextResponse} from "next/server";
export const errorHandler = (error: any) => {
return new NextResponse(
JSON.stringify({ message: 'An error occurred while processing your request.', status: 500 }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
};
+8
View File
@@ -0,0 +1,8 @@
import { NextRequest, NextResponse } from 'next/server';
export function loggingMiddleware(request: NextRequest) {
if (request.url.includes('/api')) {
console.log(`[API] Received ${request.method} request : ${request.url} at ${new Date()}`);
}
return NextResponse.next();
}
+1 -1
View File
@@ -33,7 +33,7 @@
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
".next/types/**/*.ts",
],
"exclude": [
"node_modules"
+5
View File
@@ -4288,6 +4288,11 @@ util-deprecate@^1.0.1, util-deprecate@^1.0.2:
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==
uuid@^11.0.3:
version "11.0.3"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-11.0.3.tgz#248451cac9d1a4a4128033e765d137e2b2c49a3d"
integrity sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg==
vaul@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/vaul/-/vaul-1.1.1.tgz#93aceaad16f7c53aacf28a2609b2dd43b5a91fa0"