'use client' // React Imports import { useCallback, useEffect, useMemo, useState } from 'react' // Next Imports // MUI Imports import Button from '@mui/material/Button' import Card from '@mui/material/Card' import CardHeader from '@mui/material/CardHeader' import Checkbox from '@mui/material/Checkbox' import Chip from '@mui/material/Chip' import Divider from '@mui/material/Divider' import MenuItem from '@mui/material/MenuItem' import TablePagination from '@mui/material/TablePagination' import type { TextFieldProps } from '@mui/material/TextField' import Typography from '@mui/material/Typography' // Third-party Imports import type { RankingInfo } from '@tanstack/match-sorter-utils' import { rankItem } from '@tanstack/match-sorter-utils' import type { ColumnDef, FilterFn } from '@tanstack/react-table' import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table' import classnames from 'classnames' // Type Imports // Component Imports import TablePaginationComponent from '@components/TablePaginationComponent' import CustomTextField from '@core/components/mui/TextField' import OptionMenu from '@core/components/option-menu' // Util Imports // Style Imports import tableStyles from '@core/styles/table.module.css' import { Box, CircularProgress } from '@mui/material' import ConfirmDeleteDialog from '../../../../components/dialogs/confirm-delete' import Loading from '../../../../components/layout/shared/Loading' import { useInventoriesMutation } from '../../../../services/mutations/inventories' import { useInventories } from '../../../../services/queries/inventories' import { Inventory } from '../../../../types/services/inventory' import AddStockDrawer from './AddStockDrawer' declare module '@tanstack/table-core' { interface FilterFns { fuzzy: FilterFn } interface FilterMeta { itemRank: RankingInfo } } type InventoryWithActionsType = Inventory & { actions?: string } const fuzzyFilter: FilterFn = (row, columnId, value, addMeta) => { // Rank the item const itemRank = rankItem(row.getValue(columnId), value) // Store the itemRank info addMeta({ itemRank }) // Return if the item should be filtered in/out return itemRank.passed } const DebouncedInput = ({ value: initialValue, onChange, debounce = 500, ...props }: { value: string | number onChange: (value: string | number) => void debounce?: number } & Omit) => { // States const [value, setValue] = useState(initialValue) useEffect(() => { setValue(initialValue) }, [initialValue]) useEffect(() => { const timeout = setTimeout(() => { onChange(value) }, debounce) return () => clearTimeout(timeout) // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]) return setValue(e.target.value)} /> } // Column Definitions const columnHelper = createColumnHelper() const StockListTable = () => { const [rowSelection, setRowSelection] = useState({}) const [currentPage, setCurrentPage] = useState(1) const [pageSize, setPageSize] = useState(10) const [openConfirm, setOpenConfirm] = useState(false) const [productId, setProductId] = useState('') const [addInventoryOpen, setAddInventoryOpen] = useState(false) // Fetch products with pagination and search const { data, isLoading, error, isFetching } = useInventories({ page: currentPage, limit: pageSize }) const { mutate: deleteInventory, isPending: isDeleting } = useInventoriesMutation().deleteInventory const inventories = data?.inventory ?? [] const totalCount = data?.total_count ?? 0 const handlePageChange = useCallback((event: unknown, newPage: number) => { setCurrentPage(newPage) }, []) // Handle page size change const handlePageSizeChange = useCallback((event: React.ChangeEvent) => { const newPageSize = parseInt(event.target.value, 10) setPageSize(newPageSize) setCurrentPage(0) // Reset to first page }, []) const handleDelete = () => { deleteInventory(productId, { onSuccess: () => setOpenConfirm(false) }) } const columns = useMemo[]>( () => [ { id: 'select', header: ({ table }) => ( ), cell: ({ row }) => ( ) }, columnHelper.accessor('product_id', { header: 'Product', cell: ({ row }) => {row.original.product_id} }), columnHelper.accessor('quantity', { header: 'Quantity', cell: ({ row }) => {row.original.quantity} }), columnHelper.accessor('reorder_level', { header: 'Reorder Level', cell: ({ row }) => {row.original.reorder_level} }), columnHelper.accessor('is_low_stock', { header: 'Status', cell: ({ row }) => ( ) }), columnHelper.accessor('actions', { header: 'Actions', cell: ({ row }) => (
{ setOpenConfirm(true) setProductId(row.original.id) } } }, { text: 'Duplicate', icon: 'tabler-copy' } ]} />
), enableSorting: false }) ], // eslint-disable-next-line react-hooks/exhaustive-deps [] ) const table = useReactTable({ data: inventories as Inventory[], columns, filterFns: { fuzzy: fuzzyFilter }, state: { rowSelection, pagination: { pageIndex: currentPage, // <= penting! pageSize } }, enableRowSelection: true, //enable row selection for all rows onRowSelectionChange: setRowSelection, getCoreRowModel: getCoreRowModel(), // Disable client-side pagination since we're handling it server-side manualPagination: true, pageCount: Math.ceil(totalCount / pageSize) }) return ( <> {/* {}} productData={[]} /> */}
console.log(value)} placeholder='Search Product' className='max-sm:is-full' />
table.setPageSize(Number(e.target.value))} className='flex-auto is-[70px] max-sm:is-full' > 10 25 50
{isLoading ? ( ) : ( {table.getHeaderGroups().map(headerGroup => ( {headerGroup.headers.map(header => ( ))} ))} {table.getFilteredRowModel().rows.length === 0 ? ( ) : ( {table .getRowModel() .rows.slice(0, table.getState().pagination.pageSize) .map(row => { return ( {row.getVisibleCells().map(cell => ( ))} ) })} )}
{header.isPlaceholder ? null : ( <>
{flexRender(header.column.columnDef.header, header.getContext())} {{ asc: , desc: }[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
)}
No data available
{flexRender(cell.column.columnDef.cell, cell.getContext())}
)} {isFetching && !isLoading && ( )}
( )} count={totalCount} rowsPerPage={pageSize} page={currentPage} onPageChange={handlePageChange} onRowsPerPageChange={handlePageSizeChange} rowsPerPageOptions={[10, 25, 50]} disabled={isLoading} />
setAddInventoryOpen(!addInventoryOpen)} /> setOpenConfirm(false)} onConfirm={handleDelete} isLoading={isDeleting} title='Delete Inventory' message='Are you sure you want to delete this inventory? This action cannot be undone.' /> ) } export default StockListTable