users update create delete tested
This commit is contained in:
@@ -26,10 +26,10 @@ export default function DashboardPage() {
|
||||
<div className="flex flex-1 flex-col">
|
||||
<div className="@container/main flex flex-1 flex-col gap-2">
|
||||
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
|
||||
<SectionCards />
|
||||
{/* <SectionCards />
|
||||
<div className="px-4 lg:px-6">
|
||||
<ChartAreaInteractive />
|
||||
</div>
|
||||
</div> */}
|
||||
<DataTable data={data} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
289
frontend/pages/users/add/form.tsx
Normal file
289
frontend/pages/users/add/form.tsx
Normal file
@@ -0,0 +1,289 @@
|
||||
"use client"
|
||||
import { useFieldArray, useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { userAddSchema, type UserAdd } from "./schema"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { useAddUserMutation } from "./queries"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
|
||||
const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
const form = useForm<UserAdd>({
|
||||
resolver: zodResolver(userAddSchema),
|
||||
defaultValues: {
|
||||
expiryStarts: "",
|
||||
expiryEnds: "",
|
||||
isConfirmed: false,
|
||||
isNotificationSend: false,
|
||||
password: "",
|
||||
rePassword: "",
|
||||
tag: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
collectionTokens: {
|
||||
default: "",
|
||||
tokens: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const { control, handleSubmit } = form
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control,
|
||||
name: "collectionTokens.tokens",
|
||||
})
|
||||
|
||||
const mutation = useAddUserMutation();
|
||||
|
||||
function onSubmit(values: UserAdd) {
|
||||
mutation.mutate(values as any);
|
||||
setTimeout(() => refetchTable(), 200);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
className="space-y-6 p-4"
|
||||
>
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="user@example.com" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="phone"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Phone</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="+901234567" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* PASSWORD / TAG */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" placeholder="•••••••" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="rePassword"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Re-Password</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" placeholder="•••••••" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="tag"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Tag</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="User tag..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* SWITCHES */}
|
||||
<div className="flex items-center gap-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isConfirmed"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center gap-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="mt-0!">Confirmed</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isNotificationSend"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center gap-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="mt-0!">Send Notification</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* COLLECTION TOKENS */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="collectionTokens.default"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Default Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Default token..." {...field} />
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-between items-center">
|
||||
<FormLabel>Tokens</FormLabel>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => append({ prefix: "", token: "" })}
|
||||
>
|
||||
+ Add Token
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{fields.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No tokens added.</p>
|
||||
)}
|
||||
|
||||
{fields.map((fieldItem, i) => (
|
||||
<div
|
||||
key={fieldItem.id}
|
||||
className="grid grid-cols-12 gap-2 items-end"
|
||||
>
|
||||
<div className="col-span-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`collectionTokens.tokens.${i}.prefix`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Prefix</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="prefix" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`collectionTokens.tokens.${i}.token`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="token" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
className="col-span-2 h-10"
|
||||
onClick={() => remove(i)}
|
||||
>
|
||||
✕
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Create User
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
)
|
||||
}
|
||||
|
||||
export { UserForm }
|
||||
26
frontend/pages/users/add/page.tsx
Normal file
26
frontend/pages/users/add/page.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useGraphQlUsersList } from '@/pages/users/queries';
|
||||
import { UserDataTableAdd } from '@/pages/users/add/table/data-table';
|
||||
import { UserForm } from '@/pages/users/add/form';
|
||||
|
||||
const PageAddUser = () => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
|
||||
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
return (
|
||||
<>
|
||||
<UserDataTableAdd
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<UserForm refetchTable={refetch} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageAddUser };
|
||||
21
frontend/pages/users/add/queries.tsx
Normal file
21
frontend/pages/users/add/queries.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { UserAdd } from './types'
|
||||
|
||||
const fetchGraphQlUsersAdd = async (record: UserAdd): Promise<{ data: UserAdd | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch('/api/users/add', { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, status: res.status }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useAddUserMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (data: UserAdd) => fetchGraphQlUsersAdd(data),
|
||||
onSuccess: () => { console.log("User created successfully") },
|
||||
onError: (error) => { console.error("Create user failed:", error) },
|
||||
})
|
||||
}
|
||||
29
frontend/pages/users/add/schema.ts
Normal file
29
frontend/pages/users/add/schema.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const tokenSchema = z.object({
|
||||
prefix: z.string().min(1, "Prefix is required"),
|
||||
token: z.string().min(1, "Token is required"),
|
||||
})
|
||||
|
||||
export const collectionTokensSchema = z.object({
|
||||
default: z.string().optional(),
|
||||
tokens: z.array(tokenSchema)
|
||||
})
|
||||
|
||||
export const userAddSchema = z.object({
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
|
||||
isConfirmed: z.boolean(),
|
||||
isNotificationSend: z.boolean(),
|
||||
|
||||
password: z.string().min(6),
|
||||
rePassword: z.string().min(6),
|
||||
tag: z.string().optional(),
|
||||
email: z.string().email(),
|
||||
phone: z.string().min(5),
|
||||
|
||||
collectionTokens: collectionTokensSchema,
|
||||
})
|
||||
|
||||
export type UserAdd = z.infer<typeof userAddSchema>
|
||||
267
frontend/pages/users/add/table/columns.tsx
Normal file
267
frontend/pages/users/add/table/columns.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
function TableCellViewer({ item }: { item: schemaType }) {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
return (
|
||||
<Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
<DrawerTrigger asChild>
|
||||
<Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
{item.email ?? "Unknown Email"}
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="gap-1">
|
||||
<h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
User details
|
||||
</p>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Email</Label>
|
||||
<Input value={item.email ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Phone</Label>
|
||||
<Input value={item.phone ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Tag</Label>
|
||||
<Input value={item.tag ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Active</Label>
|
||||
<Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Created At</Label>
|
||||
<Input
|
||||
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Updated At</Label>
|
||||
<Input
|
||||
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* TOKENS */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="w-full">
|
||||
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2 w-full">
|
||||
<Input value={t.prefix} readOnly />
|
||||
<Input value={t.token} readOnly />
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
</div>
|
||||
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
header: "Email",
|
||||
},
|
||||
{
|
||||
accessorKey: "phone",
|
||||
header: "Phone",
|
||||
},
|
||||
{
|
||||
accessorKey: "tag",
|
||||
header: "Tag",
|
||||
},
|
||||
{
|
||||
accessorKey: "active",
|
||||
header: "Active",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "isConfirmed",
|
||||
header: "Confirmed",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "crypUuId",
|
||||
header: "Encrypted UUID",
|
||||
},
|
||||
{
|
||||
accessorKey: "history",
|
||||
header: "History",
|
||||
cell: ({ getValue }) => (<div className="truncate max-w-[150px] text-xs text-muted-foreground">{String(getValue() ?? "")}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "collectionTokens.tokens",
|
||||
header: "Tokens",
|
||||
cell: ({ row }) => {
|
||||
const tokens = row.original.collectionTokens?.tokens ?? [];
|
||||
const defaultToken = row.original.collectionTokens?.default;
|
||||
if (!tokens.length) return "-";
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="h-8 px-2 text-xs">
|
||||
Tokens ({tokens.length})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Collection Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{defaultToken && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<div className="flex flex-col w-full">
|
||||
<span className="font-semibold">Default</span>
|
||||
<span className="font-mono text-xs text-muted-foreground break-all">
|
||||
{defaultToken}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{tokens.map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col items-start">
|
||||
<div className="w-full flex justify-between">
|
||||
<span className="font-medium">{t.prefix}</span>
|
||||
<span className="font-mono text-muted-foreground break-all">
|
||||
{t.token}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update/${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
287
frontend/pages/users/add/table/data-table.tsx
Normal file
287
frontend/pages/users/add/table/data-table.tsx
Normal file
@@ -0,0 +1,287 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeleteUserMutation } from "@/pages/users/queries"
|
||||
|
||||
export function UserDataTableAdd({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage: number,
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteUserMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
enableRowSelection: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const nextPagination = typeof updater === "function" ? updater(pagination) : updater;
|
||||
onPageChange(nextPagination.pageIndex + 1);
|
||||
onPageSizeChange(nextPagination.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => {
|
||||
const newSize = Number(value);
|
||||
onPageSizeChange(newSize);
|
||||
onPageChange(1);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
defaultValue="outline"
|
||||
className="w-full flex-col justify-start gap-6"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/users") }}>
|
||||
<Home />
|
||||
<span className="hidden lg:inline">Back to Users</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
47
frontend/pages/users/add/table/schema.tsx
Normal file
47
frontend/pages/users/add/table/schema.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string().nullable().optional(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
isConfirmed: z.boolean().nullable().optional(),
|
||||
deleted: z.boolean().nullable().optional(),
|
||||
active: z.boolean().nullable().optional(),
|
||||
crypUuId: z.string().nullable().optional(),
|
||||
createdCredentialsToken: z.string().nullable().optional(),
|
||||
updatedCredentialsToken: z.string().nullable().optional(),
|
||||
confirmedCredentialsToken: z.string().nullable().optional(),
|
||||
isNotificationSend: z.boolean().nullable().optional(),
|
||||
isEmailSend: z.boolean().nullable().optional(),
|
||||
refInt: z.number().nullable().optional(),
|
||||
refId: z.string().nullable().optional(),
|
||||
replicationId: z.number().nullable().optional(),
|
||||
expiresAt: z.string().nullable().optional(),
|
||||
resetToken: z.string().nullable().optional(),
|
||||
password: z.string().nullable().optional(),
|
||||
history: z.array(z.string()).optional(),
|
||||
tag: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
phone: z.string().nullable().optional(),
|
||||
|
||||
collectionTokens: z
|
||||
.object({
|
||||
default: z.string().nullable().optional(),
|
||||
tokens: z
|
||||
.array(
|
||||
z.object({
|
||||
prefix: z.string(),
|
||||
token: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
24
frontend/pages/users/add/types.ts
Normal file
24
frontend/pages/users/add/types.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
interface UserToken {
|
||||
prefix: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
interface CollectionTokens {
|
||||
default: string;
|
||||
tokens: UserToken[];
|
||||
}
|
||||
|
||||
interface UserAdd {
|
||||
expiryStarts: string;
|
||||
expiryEnds: string;
|
||||
isConfirmed: boolean;
|
||||
isNotificationSend: boolean;
|
||||
password: string;
|
||||
tag: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
collectionTokens: CollectionTokens;
|
||||
}
|
||||
|
||||
|
||||
export type { UserAdd };
|
||||
@@ -1,26 +1,32 @@
|
||||
'use client';
|
||||
import { useGraphQlUsersList } from './queries';
|
||||
import { useState } from 'react';
|
||||
import { UserDataTable } from '@/pages/users/table/data-table';
|
||||
|
||||
const PageUsers = () => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
const { data, isLoading, error } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
return (
|
||||
<div>
|
||||
<h1>Users</h1>
|
||||
{isLoading && <p>Loading...</p>}
|
||||
{error && <p>Error: {error.message}</p>}
|
||||
{data && <p>Total count: {data.totalCount}</p>}
|
||||
<div>
|
||||
{data && <p>Data: {JSON.stringify(data.data)}</p>}
|
||||
<button onClick={() => setPage(page - 1)}>Previous</button>
|
||||
<button onClick={() => setPage(page + 1)}>Next</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageUsers };
|
||||
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||
if (isLoading) { return <div className="flex items-center justify-center p-8">Loading...</div> }
|
||||
if (error) { return <div className="flex items-center justify-center p-8 text-red-500">Error loading users</div> }
|
||||
|
||||
return (
|
||||
<UserDataTable
|
||||
data={data?.data || []}
|
||||
totalCount={data?.totalCount || 0}
|
||||
currentPage={page}
|
||||
pageSize={limit}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
refetchTable={refetch}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export { PageUsers };
|
||||
@@ -1,5 +1,5 @@
|
||||
'use client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useQuery, useMutation } from '@tanstack/react-query'
|
||||
import { UsersListResponse } from './types'
|
||||
import { ListArguments } from '@/types/listRequest'
|
||||
|
||||
@@ -14,6 +14,26 @@ const fetchGraphQlUsersList = async (params: ListArguments): Promise<UsersListRe
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
const fetchGraphQlDeleteUser = async (uuid: string): Promise<boolean> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/users/delete?uuid=${uuid}`, { method: 'GET', cache: 'no-store', credentials: "include" });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return data
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useGraphQlUsersList(params: ListArguments) {
|
||||
return useQuery({ queryKey: ['graphql-users-list', params], queryFn: () => fetchGraphQlUsersList(params) })
|
||||
}
|
||||
|
||||
export function useDeleteUserMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteUser(uuid),
|
||||
onSuccess: () => { console.log("User deleted successfully") },
|
||||
onError: (error) => { console.error("Delete user failed:", error) },
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
267
frontend/pages/users/table/columns.tsx
Normal file
267
frontend/pages/users/table/columns.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
function TableCellViewer({ item }: { item: schemaType }) {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
return (
|
||||
<Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
<DrawerTrigger asChild>
|
||||
<Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
{item.email ?? "Unknown Email"}
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="gap-1">
|
||||
<h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
User details
|
||||
</p>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Email</Label>
|
||||
<Input value={item.email ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Phone</Label>
|
||||
<Input value={item.phone ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Tag</Label>
|
||||
<Input value={item.tag ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Active</Label>
|
||||
<Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Created At</Label>
|
||||
<Input
|
||||
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Updated At</Label>
|
||||
<Input
|
||||
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* TOKENS */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="w-full">
|
||||
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2 w-full">
|
||||
<Input value={t.prefix} readOnly />
|
||||
<Input value={t.token} readOnly />
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
</div>
|
||||
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
header: "Email",
|
||||
},
|
||||
{
|
||||
accessorKey: "phone",
|
||||
header: "Phone",
|
||||
},
|
||||
{
|
||||
accessorKey: "tag",
|
||||
header: "Tag",
|
||||
},
|
||||
{
|
||||
accessorKey: "active",
|
||||
header: "Active",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "isConfirmed",
|
||||
header: "Confirmed",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "crypUuId",
|
||||
header: "Encrypted UUID",
|
||||
},
|
||||
{
|
||||
accessorKey: "history",
|
||||
header: "History",
|
||||
cell: ({ getValue }) => (<div className="truncate max-w-[150px] text-xs text-muted-foreground">{String(getValue() ?? "")}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "collectionTokens.tokens",
|
||||
header: "Tokens",
|
||||
cell: ({ row }) => {
|
||||
const tokens = row.original.collectionTokens?.tokens ?? [];
|
||||
const defaultToken = row.original.collectionTokens?.default;
|
||||
if (!tokens.length) return "-";
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="h-8 px-2 text-xs">
|
||||
Tokens ({tokens.length})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Collection Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{defaultToken && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<div className="flex flex-col w-full">
|
||||
<span className="font-semibold">Default</span>
|
||||
<span className="font-mono text-xs text-muted-foreground break-all">
|
||||
{defaultToken}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{tokens.map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col items-start">
|
||||
<div className="w-full flex justify-between">
|
||||
<span className="font-medium">{t.prefix}</span>
|
||||
<span className="font-mono text-muted-foreground break-all">
|
||||
{t.token}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
<Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update?uuid=${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button>
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
280
frontend/pages/users/table/data-table.tsx
Normal file
280
frontend/pages/users/table/data-table.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
IconPlus,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDeleteUserMutation } from "@/pages/users/queries"
|
||||
|
||||
export function UserDataTable({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage = 1,
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage?: number,
|
||||
pageSize?: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteUserMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => { const nextPagination = typeof updater === "function" ? updater(pagination) : updater; onPageChange(nextPagination.pageIndex + 1); onPageSizeChange(nextPagination.pageSize) },
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
defaultValue="outline"
|
||||
className="w-full flex-col justify-start gap-6"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/users/add") }}>
|
||||
<IconPlus />
|
||||
<span className="hidden lg:inline">Add User</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
47
frontend/pages/users/table/schema.tsx
Normal file
47
frontend/pages/users/table/schema.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string().nullable().optional(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
isConfirmed: z.boolean().nullable().optional(),
|
||||
deleted: z.boolean().nullable().optional(),
|
||||
active: z.boolean().nullable().optional(),
|
||||
crypUuId: z.string().nullable().optional(),
|
||||
createdCredentialsToken: z.string().nullable().optional(),
|
||||
updatedCredentialsToken: z.string().nullable().optional(),
|
||||
confirmedCredentialsToken: z.string().nullable().optional(),
|
||||
isNotificationSend: z.boolean().nullable().optional(),
|
||||
isEmailSend: z.boolean().nullable().optional(),
|
||||
refInt: z.number().nullable().optional(),
|
||||
refId: z.string().nullable().optional(),
|
||||
replicationId: z.number().nullable().optional(),
|
||||
expiresAt: z.string().nullable().optional(),
|
||||
resetToken: z.string().nullable().optional(),
|
||||
password: z.string().nullable().optional(),
|
||||
history: z.array(z.string()).optional(),
|
||||
tag: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
phone: z.string().nullable().optional(),
|
||||
|
||||
collectionTokens: z
|
||||
.object({
|
||||
default: z.string().nullable().optional(),
|
||||
tokens: z
|
||||
.array(
|
||||
z.object({
|
||||
prefix: z.string(),
|
||||
token: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
250
frontend/pages/users/update/form.tsx
Normal file
250
frontend/pages/users/update/form.tsx
Normal file
@@ -0,0 +1,250 @@
|
||||
"use client"
|
||||
import { useFieldArray, useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { userUpdateSchema, type UserUpdate } from "./schema"
|
||||
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { DateTimePicker } from "@/components/ui/date-time-picker"
|
||||
import { useUpdateUserMutation } from "./queries"
|
||||
|
||||
const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: UserUpdate, selectedUuid: string }) => {
|
||||
const form = useForm<UserUpdate>({
|
||||
resolver: zodResolver(userUpdateSchema),
|
||||
defaultValues: {
|
||||
expiryStarts: initData.expiryStarts,
|
||||
expiryEnds: initData.expiryEnds,
|
||||
isConfirmed: initData.isConfirmed,
|
||||
isNotificationSend: initData.isNotificationSend,
|
||||
tag: initData.tag,
|
||||
email: initData.email,
|
||||
phone: initData.phone,
|
||||
collectionTokens: initData.collectionTokens,
|
||||
},
|
||||
})
|
||||
|
||||
const { control, handleSubmit } = form
|
||||
|
||||
const { fields, append, remove } = useFieldArray({ control, name: "collectionTokens.tokens" })
|
||||
|
||||
const mutation = useUpdateUserMutation();
|
||||
|
||||
function onSubmit(values: UserUpdate) {
|
||||
mutation.mutate({ data: values as any || initData, uuid: selectedUuid }); setTimeout(() => refetchTable(), 200)
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="user@example.com" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="phone"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Phone</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="+901234567" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* PASSWORD / TAG */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="tag"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Tag</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="User tag..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryStarts"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Starts</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="expiryEnds"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Expiry Ends</FormLabel>
|
||||
<FormControl>
|
||||
<DateTimePicker {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* SWITCHES */}
|
||||
<div className="flex items-center gap-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isConfirmed"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center gap-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="mt-0!">Confirmed</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isNotificationSend"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center gap-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormLabel className="mt-0!">Send Notification</FormLabel>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* COLLECTION TOKENS */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="collectionTokens.default"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Default Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Default token..." {...field} />
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-between items-center">
|
||||
<FormLabel>Tokens</FormLabel>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => append({ prefix: "", token: "" })}
|
||||
>
|
||||
+ Add Token
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{fields.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No tokens added.</p>
|
||||
)}
|
||||
|
||||
{fields.map((fieldItem, i) => (
|
||||
<div
|
||||
key={fieldItem.id}
|
||||
className="grid grid-cols-12 gap-2 items-end"
|
||||
>
|
||||
<div className="col-span-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`collectionTokens.tokens.${i}.prefix`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Prefix</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="prefix" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`collectionTokens.tokens.${i}.token`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Token</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="token" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
className="col-span-2 h-10"
|
||||
onClick={() => remove(i)}
|
||||
>
|
||||
✕
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Update User
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
)
|
||||
}
|
||||
|
||||
export { UserForm }
|
||||
46
frontend/pages/users/update/page.tsx
Normal file
46
frontend/pages/users/update/page.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { useGraphQlUsersList } from '@/pages/users/queries';
|
||||
import { UserDataTableUpdate } from '@/pages/users/update/table/data-table';
|
||||
import { UserForm } from '@/pages/users/update/form';
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
const PageUpdateUser = () => {
|
||||
const [page, setPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
|
||||
const uuid = searchParams?.get('uuid') || null
|
||||
if (!uuid) {
|
||||
return <>
|
||||
<div>UUID not found in search params</div>
|
||||
<Button onClick={() => router.push('/users')}>Back to Users</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
const { data, isLoading, error, refetch } = useGraphQlUsersList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
||||
const initData = data?.data?.[0] || null;
|
||||
|
||||
if (!initData) {
|
||||
return <>
|
||||
<div>Selected User is either deleted or not found</div>
|
||||
<Button onClick={() => router.push('/users')}>Back to Users</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<UserDataTableUpdate
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<UserForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageUpdateUser };
|
||||
21
frontend/pages/users/update/queries.tsx
Normal file
21
frontend/pages/users/update/queries.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
'use client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { UserUpdate } from './types';
|
||||
|
||||
const fetchGraphQlUsersUpdate = async (record: UserUpdate, uuid: string): Promise<{ data: UserUpdate | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/users/update?uuid=${uuid || ''}`, { method: 'POST', cache: 'no-store', credentials: "include", body: JSON.stringify(record) });
|
||||
if (!res.ok) { const errorText = await res.text(); console.error('Test data API error:', errorText); throw new Error(`API error: ${res.status} ${res.statusText}`) }
|
||||
const data = await res.json();
|
||||
return { data: data.data, status: res.status }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useUpdateUserMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data, uuid }: { data: UserUpdate, uuid: string }) => fetchGraphQlUsersUpdate(data, uuid),
|
||||
onSuccess: () => { console.log("User updated successfully") },
|
||||
onError: (error) => { console.error("Update user failed:", error) },
|
||||
})
|
||||
}
|
||||
27
frontend/pages/users/update/schema.ts
Normal file
27
frontend/pages/users/update/schema.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const tokenSchema = z.object({
|
||||
prefix: z.string().min(1, "Prefix is required"),
|
||||
token: z.string().min(1, "Token is required"),
|
||||
})
|
||||
|
||||
export const collectionTokensSchema = z.object({
|
||||
default: z.string().optional(),
|
||||
tokens: z.array(tokenSchema)
|
||||
})
|
||||
|
||||
export const userUpdateSchema = z.object({
|
||||
expiryStarts: z.string().optional(),
|
||||
expiryEnds: z.string().optional(),
|
||||
|
||||
isConfirmed: z.boolean(),
|
||||
isNotificationSend: z.boolean(),
|
||||
|
||||
tag: z.string().optional(),
|
||||
email: z.string().email(),
|
||||
phone: z.string().min(5),
|
||||
|
||||
collectionTokens: collectionTokensSchema,
|
||||
})
|
||||
|
||||
export type UserUpdate = z.infer<typeof userUpdateSchema>
|
||||
267
frontend/pages/users/update/table/columns.tsx
Normal file
267
frontend/pages/users/update/table/columns.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
"use client"
|
||||
import { z } from "zod"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Drawer, DrawerClose, DrawerContent, DrawerFooter, DrawerHeader, DrawerTrigger } from "@/components/ui/drawer"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { IconGripVertical } from "@tabler/icons-react"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { ColumnDef, flexRender, Row } from "@tanstack/react-table"
|
||||
import { TableCell, TableRow } from "@/components/ui/table"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import { schema, schemaType } from "./schema"
|
||||
import { dateToLocaleString } from "@/lib/utils"
|
||||
import { Pencil, Trash } from "lucide-react"
|
||||
|
||||
function TableCellViewer({ item }: { item: schemaType }) {
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
return (
|
||||
<Drawer direction={isMobile ? "bottom" : "right"}>
|
||||
<DrawerTrigger asChild>
|
||||
<Button variant="link" className="text-foreground w-fit px-0 text-left">
|
||||
{item.email ?? "Unknown Email"}
|
||||
</Button>
|
||||
</DrawerTrigger>
|
||||
|
||||
<DrawerContent>
|
||||
<DrawerHeader className="gap-1">
|
||||
<h2 className="text-lg font-semibold">{item.email}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
User details
|
||||
</p>
|
||||
</DrawerHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 overflow-y-auto px-4 text-sm">
|
||||
|
||||
{/* BASIC INFO */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Email</Label>
|
||||
<Input value={item.email ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Phone</Label>
|
||||
<Input value={item.phone ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Tag</Label>
|
||||
<Input value={item.tag ?? ""} readOnly />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Active</Label>
|
||||
<Input value={item.active ? "Active" : "Inactive"} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* DATES */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Created At</Label>
|
||||
<Input
|
||||
value={item.createdAt ? new Date(item.createdAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Updated At</Label>
|
||||
<Input
|
||||
value={item.updatedAt ? new Date(item.updatedAt).toLocaleString() : ""}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* TOKENS */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="w-full">
|
||||
Collection Tokens ({item.collectionTokens?.tokens?.length ?? 0})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{(item.collectionTokens?.tokens ?? []).length === 0 && (<DropdownMenuItem disabled>No tokens found</DropdownMenuItem>)}
|
||||
{(item.collectionTokens?.tokens ?? []).map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col gap-2">
|
||||
<div className="grid grid-cols-2 gap-2 w-full">
|
||||
<Input value={t.prefix} readOnly />
|
||||
<Input value={t.token} readOnly />
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
</div>
|
||||
|
||||
<DrawerFooter>
|
||||
<DrawerClose asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function DragHandle({ id }: { id: number }) {
|
||||
const { attributes, listeners } = useSortable({ id })
|
||||
return (
|
||||
<Button {...attributes} {...listeners} variant="ghost" size="icon" className="text-muted-foreground size-7 hover:bg-transparent">
|
||||
<IconGripVertical className="text-muted-foreground size-3" />
|
||||
<span className="sr-only">Drag to reorder</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function DraggableRow({ row }: { row: Row<z.infer<typeof schema>> }) {
|
||||
const { transform, transition, setNodeRef, isDragging } = useSortable({ id: row.original._id })
|
||||
return (
|
||||
<TableRow data-state={row.getIsSelected() && "selected"} data-dragging={isDragging} ref={setNodeRef}
|
||||
className="relative z-0 data-[dragging=true]:z-10 data-[dragging=true]:opacity-80"
|
||||
style={{ transform: CSS.Transform.toString(transform), transition: transition }}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
)
|
||||
}
|
||||
|
||||
function getColumns(deleteHandler: (id: string) => void): ColumnDef<schemaType>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "uuid",
|
||||
header: "UUID",
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
header: "Email",
|
||||
},
|
||||
{
|
||||
accessorKey: "phone",
|
||||
header: "Phone",
|
||||
},
|
||||
{
|
||||
accessorKey: "tag",
|
||||
header: "Tag",
|
||||
},
|
||||
{
|
||||
accessorKey: "active",
|
||||
header: "Active",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "isConfirmed",
|
||||
header: "Confirmed",
|
||||
cell: ({ getValue }) => getValue() ? (<div className="text-green-600 font-medium">Yes</div>) : (<div className="text-red-600 font-medium">No</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
header: "Created",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "updatedAt",
|
||||
header: "Updated",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryStarts",
|
||||
header: "Expiry Starts",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "expiryEnds",
|
||||
header: "Expiry Ends",
|
||||
cell: ({ getValue }) => getValue() ? dateToLocaleString(getValue() as string) : "-",
|
||||
},
|
||||
{
|
||||
accessorKey: "crypUuId",
|
||||
header: "Encrypted UUID",
|
||||
},
|
||||
{
|
||||
accessorKey: "history",
|
||||
header: "History",
|
||||
cell: ({ getValue }) => (<div className="truncate max-w-[150px] text-xs text-muted-foreground">{String(getValue() ?? "")}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "collectionTokens.tokens",
|
||||
header: "Tokens",
|
||||
cell: ({ row }) => {
|
||||
const tokens = row.original.collectionTokens?.tokens ?? [];
|
||||
const defaultToken = row.original.collectionTokens?.default;
|
||||
if (!tokens.length) return "-";
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="h-8 px-2 text-xs">
|
||||
Tokens ({tokens.length})
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-72">
|
||||
<DropdownMenuLabel>Collection Tokens</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{defaultToken && (
|
||||
<>
|
||||
<DropdownMenuItem>
|
||||
<div className="flex flex-col w-full">
|
||||
<span className="font-semibold">Default</span>
|
||||
<span className="font-mono text-xs text-muted-foreground break-all">
|
||||
{defaultToken}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
{tokens.map((t, i) => (
|
||||
<DropdownMenuItem key={i} className="flex flex-col items-start">
|
||||
<div className="w-full flex justify-between">
|
||||
<span className="font-medium">{t.prefix}</span>
|
||||
<span className="font-mono text-muted-foreground break-all">
|
||||
{t.token}
|
||||
</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: "Actions",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<div>
|
||||
{/* <Button className="bg-amber-400 text-black border-amber-400" variant="outline" size="sm" onClick={() => { router.push(`/users/update/${row.original.uuid}`) }}>
|
||||
<Pencil />
|
||||
</Button> */}
|
||||
<Button className="bg-red-700 text-white border-red-700 mx-4" variant="outline" size="sm" onClick={() => { deleteHandler(row.original.uuid || "") }}>
|
||||
<Trash />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export { getColumns };
|
||||
287
frontend/pages/users/update/table/data-table.tsx
Normal file
287
frontend/pages/users/update/table/data-table.tsx
Normal file
@@ -0,0 +1,287 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type UniqueIdentifier,
|
||||
} from "@dnd-kit/core"
|
||||
import { restrictToVerticalAxis } from "@dnd-kit/modifiers"
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable"
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconChevronsLeft,
|
||||
IconChevronsRight,
|
||||
IconLayoutColumns,
|
||||
} from "@tabler/icons-react"
|
||||
import {
|
||||
ColumnFiltersState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFacetedRowModel,
|
||||
getFacetedUniqueValues,
|
||||
getFilteredRowModel,
|
||||
getSortedRowModel,
|
||||
SortingState,
|
||||
useReactTable,
|
||||
VisibilityState,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@/components/ui/tabs"
|
||||
import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeleteUserMutation } from "@/pages/users/queries"
|
||||
|
||||
export function UserDataTableUpdate({
|
||||
data,
|
||||
totalCount,
|
||||
currentPage,
|
||||
pageSize,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
currentPage: number,
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
const [rowSelection, setRowSelection] = React.useState({})
|
||||
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
|
||||
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
const sortableId = React.useId()
|
||||
const sensors = useSensors(useSensor(MouseSensor, {}), useSensor(TouchSensor, {}), useSensor(KeyboardSensor, {}))
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteUserMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 200) }
|
||||
const columns = getColumns(deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
pageCount: totalPages,
|
||||
state: { sorting, columnVisibility, rowSelection, columnFilters, pagination },
|
||||
manualPagination: true,
|
||||
enableRowSelection: true,
|
||||
getRowId: (row) => row._id.toString(),
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onSortingChange: setSorting,
|
||||
onColumnFiltersChange: setColumnFilters,
|
||||
onColumnVisibilityChange: setColumnVisibility,
|
||||
onPaginationChange: (updater) => {
|
||||
const nextPagination = typeof updater === "function" ? updater(pagination) : updater;
|
||||
onPageChange(nextPagination.pageIndex + 1);
|
||||
onPageSizeChange(nextPagination.pageSize);
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => {
|
||||
const newSize = Number(value);
|
||||
onPageSizeChange(newSize);
|
||||
onPageChange(1);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
defaultValue="outline"
|
||||
className="w-full flex-col justify-start gap-6"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 lg:px-6">
|
||||
<Label htmlFor="view-selector" className="sr-only">
|
||||
View
|
||||
</Label>
|
||||
<Select defaultValue="outline">
|
||||
<SelectTrigger className="flex w-fit @4xl/main:hidden" size="sm" id="view-selector">
|
||||
<SelectValue placeholder="Select a view" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="outline">Outline</SelectItem>
|
||||
<SelectItem value="past-performance">Past Performance</SelectItem>
|
||||
<SelectItem value="key-personnel">Key Personnel</SelectItem>
|
||||
<SelectItem value="focus-documents">Focus Documents</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<IconLayoutColumns />
|
||||
<span className="hidden lg:inline">Customize Columns</span>
|
||||
<span className="lg:hidden">Columns</span>
|
||||
<IconChevronDown />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{table.getAllColumns().filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide()).map((column) => {
|
||||
return (
|
||||
<DropdownMenuCheckboxItem key={column.id} className="capitalize" checked={column.getIsVisible()} onCheckedChange={(value) => column.toggleVisibility(!!value)} >
|
||||
{column.id}
|
||||
</DropdownMenuCheckboxItem>
|
||||
)
|
||||
})}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="sm" onClick={() => { router.push("/users") }}>
|
||||
<Home />
|
||||
<span className="hidden lg:inline">Back to Users</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TabsContent value="outline"
|
||||
className="relative flex flex-col gap-4 overflow-auto px-4 lg:px-6"
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<DndContext collisionDetection={closestCenter} modifiers={[restrictToVerticalAxis]} sensors={sensors} id={sortableId} >
|
||||
<Table>
|
||||
<TableHeader className="bg-muted sticky top-0 z-10">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id} colSpan={header.colSpan}>
|
||||
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody className="**:data-[slot=table-cell]:first:w-8">
|
||||
{table.getRowModel().rows?.length ? (<SortableContext items={dataIds} strategy={verticalListSortingStrategy} >
|
||||
{table.getRowModel().rows.map((row) => <DraggableRow key={row.id} row={row} />)}
|
||||
</SortableContext>) : (
|
||||
<TableRow><TableCell colSpan={columns.length} className="h-24 text-center">No results.</TableCell></TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
</div>
|
||||
<div className="flex items-center justify-between px-4">
|
||||
<div className="text-muted-foreground hidden flex-1 text-sm lg:flex">
|
||||
{table.getFilteredSelectedRowModel().rows.length} of{" "}
|
||||
{table.getFilteredRowModel().rows.length} row(s) selected.
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-8 lg:w-fit">
|
||||
<div className="hidden items-center gap-2 lg:flex">
|
||||
<Label htmlFor="rows-per-page" className="text-sm font-medium">Rows per page</Label>
|
||||
<Select value={`${pageSize}`} onValueChange={handlePageSizeChange}>
|
||||
<SelectTrigger size="sm" className="w-20" id="rows-per-page">
|
||||
<SelectValue placeholder={pageSize} />
|
||||
</SelectTrigger>
|
||||
<SelectContent side="top">
|
||||
{[10, 20, 30].map((size) => <SelectItem key={size} value={`${size}`}>{size}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Page {currentPage} of {totalPages}
|
||||
</div>
|
||||
<div className="flex w-fit items-center justify-center text-sm font-medium">
|
||||
Total Count: {totalCount}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 lg:ml-0">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronsLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronRight />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => onPageChange(totalPages)}
|
||||
disabled={currentPage >= totalPages}
|
||||
>
|
||||
<IconChevronsRight />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="past-performance" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="key-personnel" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
<TabsContent value="focus-documents" className="flex flex-col px-4 lg:px-6">
|
||||
<div className="aspect-video w-full flex-1 rounded-lg border border-dashed"></div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)
|
||||
}
|
||||
47
frontend/pages/users/update/table/schema.tsx
Normal file
47
frontend/pages/users/update/table/schema.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const schema = z.object({
|
||||
_id: z.string(),
|
||||
uuid: z.string().nullable().optional(),
|
||||
expiryStarts: z.string().nullable().optional(),
|
||||
expiryEnds: z.string().nullable().optional(),
|
||||
isConfirmed: z.boolean().nullable().optional(),
|
||||
deleted: z.boolean().nullable().optional(),
|
||||
active: z.boolean().nullable().optional(),
|
||||
crypUuId: z.string().nullable().optional(),
|
||||
createdCredentialsToken: z.string().nullable().optional(),
|
||||
updatedCredentialsToken: z.string().nullable().optional(),
|
||||
confirmedCredentialsToken: z.string().nullable().optional(),
|
||||
isNotificationSend: z.boolean().nullable().optional(),
|
||||
isEmailSend: z.boolean().nullable().optional(),
|
||||
refInt: z.number().nullable().optional(),
|
||||
refId: z.string().nullable().optional(),
|
||||
replicationId: z.number().nullable().optional(),
|
||||
expiresAt: z.string().nullable().optional(),
|
||||
resetToken: z.string().nullable().optional(),
|
||||
password: z.string().nullable().optional(),
|
||||
history: z.array(z.string()).optional(),
|
||||
tag: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
phone: z.string().nullable().optional(),
|
||||
|
||||
collectionTokens: z
|
||||
.object({
|
||||
default: z.string().nullable().optional(),
|
||||
tokens: z
|
||||
.array(
|
||||
z.object({
|
||||
prefix: z.string(),
|
||||
token: z.string(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
|
||||
createdAt: z.string().nullable().optional(),
|
||||
updatedAt: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export type schemaType = z.infer<typeof schema>;
|
||||
24
frontend/pages/users/update/types.ts
Normal file
24
frontend/pages/users/update/types.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
interface UserToken {
|
||||
prefix: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
interface CollectionTokens {
|
||||
default: string;
|
||||
tokens: UserToken[];
|
||||
}
|
||||
|
||||
interface UserUpdate {
|
||||
expiryStarts: string;
|
||||
expiryEnds: string;
|
||||
isConfirmed: boolean;
|
||||
isNotificationSend: boolean;
|
||||
password: string;
|
||||
tag: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
collectionTokens: CollectionTokens;
|
||||
}
|
||||
|
||||
|
||||
export type { UserUpdate };
|
||||
Reference in New Issue
Block a user