updated build add update delete
This commit is contained in:
@@ -27,17 +27,13 @@ const BuildTypesForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
|
||||
const mutation = useAddBuildTypesMutation();
|
||||
|
||||
function onSubmit(values: BuildTypesAdd) { mutation.mutate({ data: values }); setTimeout(() => refetchTable(), 400) };
|
||||
function onSubmit(values: BuildTypesAdd) { mutation.mutate({ data: values, refetchTable }) };
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
className="space-y-6 p-4"
|
||||
>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
|
||||
{/* TYPE + TOKEN */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="type"
|
||||
@@ -51,7 +47,6 @@ const BuildTypesForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="token"
|
||||
@@ -69,7 +64,6 @@ const BuildTypesForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
|
||||
{/* TYPE TOKEN + DESCRIPTION */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="typeToken"
|
||||
@@ -133,9 +127,7 @@ const BuildTypesForm = ({ refetchTable }: { refetchTable: () => void }) => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Update Build Type
|
||||
</Button>
|
||||
<Button type="submit" className="w-full">Add Build Type</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
|
||||
@@ -9,15 +9,10 @@ const PageAddBuildTypes = () => {
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
|
||||
const { data, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
const { data, isFetching, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
return (
|
||||
<>
|
||||
<BuildTypesDataTableAdd
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<BuildTypesDataTableAdd data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} tableIsLoading={isLoading || isFetching} />
|
||||
<BuildTypesForm refetchTable={refetch} />
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -3,22 +3,21 @@ import { useMutation } from '@tanstack/react-query'
|
||||
import { BuildTypesAdd } from './types'
|
||||
import { toISOIfNotZ } from '@/lib/utils';
|
||||
|
||||
const fetchGraphQlBuildTypesAdd = async (record: BuildTypesAdd): Promise<{ data: BuildTypesAdd | null; status: number }> => {
|
||||
const fetchGraphQlBuildTypesAdd = async (record: BuildTypesAdd, refetchTable: () => void): Promise<{ data: BuildTypesAdd | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
// record.birthDate = toISOIfNotZ(record.birthDate || "");
|
||||
// record.expiryStarts = toISOIfNotZ(record.expiryStarts || "");
|
||||
// record.expiryEnds = toISOIfNotZ(record.expiryEnds || "");
|
||||
record.expiryStarts = record?.expiryStarts ? toISOIfNotZ(record.expiryStarts || "") : undefined;
|
||||
record.expiryEnds = record?.expiryEnds ? toISOIfNotZ(record.expiryEnds || "") : undefined;
|
||||
try {
|
||||
const res = await fetch('/api/build-types/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();
|
||||
const data = await res.json(); refetchTable();
|
||||
return { data: data.data, status: res.status }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useAddBuildTypesMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data }: { data: BuildTypesAdd }) => fetchGraphQlBuildTypesAdd(data),
|
||||
mutationFn: ({ data, refetchTable }: { data: BuildTypesAdd, refetchTable: () => void }) => fetchGraphQlBuildTypesAdd(data, refetchTable),
|
||||
onSuccess: () => { console.log("Build Types created successfully") },
|
||||
onError: (error) => { console.error("Create build types failed:", error) },
|
||||
})
|
||||
|
||||
@@ -16,118 +16,6 @@ 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 (
|
||||
@@ -150,63 +38,20 @@ function getColumns(router: any, deleteHandler: (id: string) => void): ColumnDef
|
||||
cell: ({ getValue }) => (<div className="font-mono text-xs bg-muted px-2 py-1 rounded break-all">{String(getValue())}</div>),
|
||||
},
|
||||
{
|
||||
accessorKey: "firstName",
|
||||
header: "First Name",
|
||||
accessorKey: "type",
|
||||
header: "Type",
|
||||
},
|
||||
{
|
||||
accessorKey: "surname",
|
||||
header: "Surname",
|
||||
accessorKey: "token",
|
||||
header: "Token",
|
||||
},
|
||||
{
|
||||
accessorKey: "middleName",
|
||||
header: "Middle Name",
|
||||
accessorKey: "typeToken",
|
||||
header: "Type Token",
|
||||
},
|
||||
{
|
||||
accessorKey: "sexCode",
|
||||
header: "Sex",
|
||||
},
|
||||
{
|
||||
accessorKey: "personRef",
|
||||
header: "Person Ref",
|
||||
},
|
||||
{
|
||||
accessorKey: "personTag",
|
||||
header: "Person Tag",
|
||||
},
|
||||
{
|
||||
accessorKey: "fatherName",
|
||||
header: "Father Name",
|
||||
},
|
||||
{
|
||||
accessorKey: "motherName",
|
||||
header: "Mother Name",
|
||||
},
|
||||
{
|
||||
accessorKey: "countryCode",
|
||||
header: "Country",
|
||||
},
|
||||
{
|
||||
accessorKey: "nationalIdentityId",
|
||||
header: "National ID",
|
||||
},
|
||||
{
|
||||
accessorKey: "birthPlace",
|
||||
header: "Birth Place",
|
||||
},
|
||||
{
|
||||
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: "birthDate",
|
||||
header: "Birth Date",
|
||||
cell: ({ getValue }) => dateToLocaleString(getValue() as string),
|
||||
accessorKey: "description",
|
||||
header: "Description",
|
||||
},
|
||||
{
|
||||
accessorKey: "createdAt",
|
||||
|
||||
@@ -71,6 +71,7 @@ import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Home } from "lucide-react"
|
||||
import { useDeleteUserMutation } from "@/pages/users/queries"
|
||||
import { TableSkeleton } from "@/components/skeletons/tableSkeleton"
|
||||
|
||||
export function BuildTypesDataTableAdd({
|
||||
data,
|
||||
@@ -80,6 +81,7 @@ export function BuildTypesDataTableAdd({
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
tableIsLoading
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
@@ -87,7 +89,8 @@ export function BuildTypesDataTableAdd({
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
refetchTable: () => void,
|
||||
tableIsLoading: boolean
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
@@ -100,7 +103,7 @@ export function BuildTypesDataTableAdd({
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteUserMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
@@ -129,11 +132,7 @@ export function BuildTypesDataTableAdd({
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
})
|
||||
|
||||
const handlePageSizeChange = (value: string) => {
|
||||
const newSize = Number(value);
|
||||
onPageSizeChange(newSize);
|
||||
onPageChange(1);
|
||||
}
|
||||
const handlePageSizeChange = (value: string) => { const newSize = Number(value); onPageSizeChange(newSize); onPageChange(1) }
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
@@ -201,11 +200,9 @@ export function BuildTypesDataTableAdd({
|
||||
))}
|
||||
</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>
|
||||
)}
|
||||
{tableIsLoading ?
|
||||
<TableSkeleton columnCount={table.getAllColumns().length} rowCount={pageSize} hasActions={true} /> :
|
||||
<SortableContext items={dataIds} strategy={verticalListSortingStrategy}>{table.getRowModel().rows.map(row => <DraggableRow key={row.id} row={row} />)}</SortableContext>}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
|
||||
@@ -70,6 +70,7 @@ import { schemaType } from "./schema"
|
||||
import { getColumns, DraggableRow } from "./columns"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDeleteBuildTypeMutation } from "../queries"
|
||||
import { TableSkeleton } from "@/components/skeletons/tableSkeleton"
|
||||
|
||||
export function BuildTypesDataTable({
|
||||
data,
|
||||
@@ -78,7 +79,8 @@ export function BuildTypesDataTable({
|
||||
pageSize = 10,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable
|
||||
refetchTable,
|
||||
tableIsLoading
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
@@ -87,6 +89,7 @@ export function BuildTypesDataTable({
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void,
|
||||
tableIsLoading: boolean
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
@@ -99,7 +102,7 @@ export function BuildTypesDataTable({
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeleteBuildTypeMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
@@ -187,11 +190,9 @@ export function BuildTypesDataTable({
|
||||
))}
|
||||
</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>
|
||||
)}
|
||||
{tableIsLoading ?
|
||||
<TableSkeleton columnCount={table.getAllColumns().length} rowCount={pageSize} hasActions={true} /> :
|
||||
<SortableContext items={dataIds} strategy={verticalListSortingStrategy}>{table.getRowModel().rows.map(row => <DraggableRow key={row.id} row={row} />)}</SortableContext>}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</DndContext>
|
||||
|
||||
@@ -10,7 +10,7 @@ const PageBuildTypes = () => {
|
||||
const [sort, setSort] = useState({ createdAt: 'desc' });
|
||||
const [filters, setFilters] = useState({});
|
||||
|
||||
const { data, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
const { data, isFetching, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters });
|
||||
|
||||
const handlePageChange = (newPage: number) => { setPage(newPage) };
|
||||
const handlePageSizeChange = (newSize: number) => { setLimit(newSize); setPage(1) };
|
||||
@@ -18,7 +18,7 @@ const PageBuildTypes = () => {
|
||||
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 <BuildTypesDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} />;
|
||||
return <BuildTypesDataTable data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={handlePageChange} onPageSizeChange={handlePageSizeChange} refetchTable={refetch} tableIsLoading={isLoading || isFetching} />;
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -13,12 +13,12 @@ const fetchGraphQlBuildTypesList = async (params: ListArguments): Promise<any> =
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
const fetchGraphQlDeleteBuildType = async (uuid: string): Promise<boolean> => {
|
||||
const fetchGraphQlDeleteBuildType = async (uuid: string, refetchTable: () => void): Promise<boolean> => {
|
||||
console.log('Fetching test data from local API');
|
||||
try {
|
||||
const res = await fetch(`/api/build-types/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();
|
||||
const data = await res.json(); refetchTable()
|
||||
return data
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
@@ -29,7 +29,7 @@ export function useGraphQlBuildTypesList(params: ListArguments) {
|
||||
|
||||
export function useDeleteBuildTypeMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ uuid }: { uuid: string }) => fetchGraphQlDeleteBuildType(uuid),
|
||||
mutationFn: ({ uuid, refetchTable }: { uuid: string, refetchTable: () => void }) => fetchGraphQlDeleteBuildType(uuid, refetchTable),
|
||||
onSuccess: () => { console.log("Build type deleted successfully") },
|
||||
onError: (error) => { console.error("Delete build type failed:", error) },
|
||||
})
|
||||
|
||||
@@ -17,7 +17,7 @@ const BuildTypesForm = ({ refetchTable, initData, selectedUuid }: { refetchTable
|
||||
|
||||
const mutation = useUpdateBuildTypesMutation();
|
||||
|
||||
function onSubmit(values: BuildTypesUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid }); setTimeout(() => refetchTable(), 400) }
|
||||
function onSubmit(values: BuildTypesUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, refetchTable }) }
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
|
||||
@@ -19,15 +19,12 @@ const PageUpdateBuildTypes = () => {
|
||||
<Button onClick={() => router.push('/build-types')}>Back to Build Types</Button>
|
||||
</>
|
||||
if (!uuid) { return backToBuildTypes }
|
||||
const { data, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
||||
const { data, isFetching, isLoading, error, refetch } = useGraphQlBuildTypesList({ limit, skip: (page - 1) * limit, sort, filters: { ...filters, uuid } });
|
||||
const initData = data?.data?.[0] || null;
|
||||
if (!initData) { return backToBuildTypes }
|
||||
return (
|
||||
<>
|
||||
<BuildTypesDataTableUpdate
|
||||
data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit}
|
||||
onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch}
|
||||
/>
|
||||
<BuildTypesDataTableUpdate data={data?.data || []} totalCount={data?.totalCount || 0} currentPage={page} pageSize={limit} onPageChange={setPage} onPageSizeChange={setLimit} refetchTable={refetch} tableIsLoading={isLoading || isFetching} />
|
||||
<BuildTypesForm refetchTable={refetch} initData={initData} selectedUuid={uuid} />
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useMutation } from '@tanstack/react-query'
|
||||
import { BuildTypesUpdate } from './types';
|
||||
import { toISOIfNotZ } from '@/lib/utils';
|
||||
|
||||
const fetchGraphQlBuildTypesUpdate = async (record: BuildTypesUpdate, uuid: string): Promise<{ data: BuildTypesUpdate | null; status: number }> => {
|
||||
const fetchGraphQlBuildTypesUpdate = async (record: BuildTypesUpdate, uuid: string, refetchTable: () => void): Promise<{ data: BuildTypesUpdate | null; status: number }> => {
|
||||
console.log('Fetching test data from local API');
|
||||
record.expiryStarts = record.expiryStarts ? toISOIfNotZ(record.expiryStarts) : undefined;
|
||||
record.expiryEnds = record.expiryEnds ? toISOIfNotZ(record.expiryEnds) : undefined;
|
||||
@@ -11,14 +11,14 @@ const fetchGraphQlBuildTypesUpdate = async (record: BuildTypesUpdate, uuid: stri
|
||||
try {
|
||||
const res = await fetch(`/api/build-types/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();
|
||||
const data = await res.json(); refetchTable();
|
||||
return { data: data.data, status: res.status }
|
||||
} catch (error) { console.error('Error fetching test data:', error); throw error }
|
||||
};
|
||||
|
||||
export function useUpdateBuildTypesMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ data, uuid }: { data: BuildTypesUpdate, uuid: string }) => fetchGraphQlBuildTypesUpdate(data, uuid),
|
||||
mutationFn: ({ data, uuid, refetchTable }: { data: BuildTypesUpdate, uuid: string, refetchTable: () => void }) => fetchGraphQlBuildTypesUpdate(data, uuid, refetchTable),
|
||||
onSuccess: () => { console.log("Build Types updated successfully") },
|
||||
onError: (error) => { console.error("Update build types failed:", error) },
|
||||
})
|
||||
|
||||
@@ -80,6 +80,7 @@ export function BuildTypesDataTableUpdate({
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
refetchTable,
|
||||
tableIsLoading,
|
||||
}: {
|
||||
data: schemaType[],
|
||||
totalCount: number,
|
||||
@@ -87,7 +88,8 @@ export function BuildTypesDataTableUpdate({
|
||||
pageSize: number,
|
||||
onPageChange: (page: number) => void,
|
||||
onPageSizeChange: (size: number) => void,
|
||||
refetchTable: () => void
|
||||
refetchTable: () => void,
|
||||
tableIsLoading: boolean
|
||||
}) {
|
||||
|
||||
const router = useRouter();
|
||||
@@ -100,7 +102,7 @@ export function BuildTypesDataTableUpdate({
|
||||
const dataIds = React.useMemo<UniqueIdentifier[]>(() => data?.map(({ _id }) => _id) || [], [data])
|
||||
|
||||
const deleteMutation = useDeletePersonMutation()
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id }); setTimeout(() => { refetchTable() }, 400) }
|
||||
const deleteHandler = (id: string) => { deleteMutation.mutate({ uuid: id, refetchTable }) }
|
||||
const columns = getColumns(router, deleteHandler);
|
||||
const pagination = React.useMemo(() => ({ pageIndex: currentPage - 1, pageSize: pageSize, }), [currentPage, pageSize])
|
||||
const totalPages = Math.ceil(totalCount / pageSize)
|
||||
|
||||
Reference in New Issue
Block a user