refactor(FE): Refactor ProductTable and RowOptionsMenu for improved

clarity
This commit is contained in:
rstubryan
2026-03-02 10:42:34 +07:00
parent 8397d76171
commit 7eaf6b7a3a
2 changed files with 233 additions and 272 deletions
+1 -5
View File
@@ -1,11 +1,7 @@
import ProductsTable from '@/components/pages/master-data/product/ProductTable'; import ProductsTable from '@/components/pages/master-data/product/ProductTable';
const Product = () => { const Product = () => {
return ( return <ProductsTable />;
<section className='w-full p-4'>
<ProductsTable />
</section>
);
}; };
export default Product; export default Product;
@@ -1,13 +1,8 @@
'use client'; 'use client';
import { ChangeEventHandler, useCallback, useEffect, useState } from 'react'; import { ChangeEventHandler, useMemo, useState } from 'react';
import useSWR from 'swr'; import useSWR from 'swr';
import { import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
CellContext,
ColumnDef,
ColumnSort,
SortingState,
} from '@tanstack/react-table';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import { Icon } from '@iconify/react'; import { Icon } from '@iconify/react';
@@ -16,37 +11,60 @@ import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button'; import Button from '@/components/Button';
import { useModal } from '@/components/Modal'; import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal'; import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import RequirePermission from '@/components/helper/RequirePermission'; import RequirePermission from '@/components/helper/RequirePermission';
import PopoverButton from '@/components/popover/PopoverButton';
import PopoverContent from '@/components/popover/PopoverContent';
import { Product } from '@/types/api/master-data/product'; import { Product } from '@/types/api/master-data/product';
import { ProductApi } from '@/services/api/master-data'; import { ProductApi } from '@/services/api/master-data';
import { cn, formatCurrency } from '@/lib/helper'; import { cn, formatCurrency } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper'; import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter'; import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant';
const RowOptionsMenu = ({ const RowOptionsMenu = ({
type = 'dropdown', popoverPosition = 'bottom',
props, props,
deleteClickHandler, deleteClickHandler,
}: { }: {
type: 'dropdown' | 'collapse'; popoverPosition: 'bottom' | 'top';
props: CellContext<Product, unknown>; props: CellContext<Product, unknown>;
deleteClickHandler: () => void; deleteClickHandler: () => void;
}) => ( }) => {
<RowOptionsMenuWrapper type={type}> const popoverId = `product#${props.row.original.id}`;
const popoverAnchorName = `--anchor-product#${props.row.original.id}`;
const closePopover = () => {
document.getElementById(popoverId)?.hidePopover();
};
return (
<div className='relative'>
<PopoverButton
tabIndex={0}
variant='ghost'
color='none'
popoverTarget={popoverId}
anchorName={popoverAnchorName}
>
<Icon icon='material-symbols:more-vert' width={16} height={16} />
</PopoverButton>
<PopoverContent
id={popoverId}
anchorName={popoverAnchorName}
position={popoverPosition === 'bottom' ? 'bottom-start' : 'left'}
className='w-full max-w-40 rounded-xl border border-base-content/5 shadow-sm'
>
<div className='flex flex-col bg-base-100 rounded-xl'>
<RequirePermission permissions='lti.master.products.detail'> <RequirePermission permissions='lti.master.products.detail'>
<Button <Button
href={`/master-data/product/detail/?productId=${props.row.original.id}`} href={`/master-data/product/detail/?productId=${props.row.original.id}`}
variant='ghost' variant='ghost'
color='primary' color='none'
className='justify-start text-sm' className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
> >
<Icon icon='mdi:eye-outline' width={16} height={16} /> <Icon icon='heroicons:eye' width={20} height={20} />
Detail Detail
</Button> </Button>
</RequirePermission> </RequirePermission>
@@ -54,31 +72,33 @@ const RowOptionsMenu = ({
<Button <Button
href={`/master-data/product/detail/edit/?productId=${props.row.original.id}`} href={`/master-data/product/detail/edit/?productId=${props.row.original.id}`}
variant='ghost' variant='ghost'
color='warning' color='none'
className='justify-start text-sm' className='p-3 justify-start text-sm font-semibold w-full'
onClick={closePopover}
> >
<Icon icon='material-symbols:edit-outline' width={16} height={16} /> <Icon icon='heroicons:pencil-square' width={20} height={20} />
Edit Edit
</Button> </Button>
</RequirePermission> </RequirePermission>
<RequirePermission permissions='lti.master.products.delete'> <RequirePermission permissions='lti.master.products.delete'>
<Button <Button
onClick={deleteClickHandler} onClick={() => {
deleteClickHandler();
closePopover();
}}
variant='ghost' variant='ghost'
color='error' color='none'
className='justify-start text-sm text-error focus-visible:text-error-content hover:text-error-content' className='p-3 justify-start text-sm font-semibold w-full text-error hover:text-error'
> >
<Icon <Icon icon='heroicons:trash' width={20} height={20} />
icon='material-symbols:delete-outline-rounded'
width={16}
height={16}
className='justify-start text-sm'
/>
Delete Delete
</Button> </Button>
</RequirePermission> </RequirePermission>
</RowOptionsMenuWrapper> </div>
); </PopoverContent>
</div>
);
};
const ProductsTable = () => { const ProductsTable = () => {
const { const {
@@ -90,21 +110,15 @@ const ProductsTable = () => {
} = useTableFilter({ } = useTableFilter({
initial: { initial: {
search: '', search: '',
nameSort: '',
skuSort: '',
brandSort: '',
categorySort: '',
}, },
paramMap: { paramMap: {
page: 'page', page: 'page',
pageSize: 'limit', pageSize: 'limit',
nameSort: 'sort_name',
skuSort: 'sort_sku',
brandSort: 'sort_brand',
categorySort: 'sort_category',
}, },
}); });
const [sorting, setSorting] = useState<SortingState>([]);
const { const {
data: products, data: products,
isLoading, isLoading,
@@ -119,11 +133,35 @@ const ProductsTable = () => {
undefined undefined
); );
const [isDeleteLoading, setIsDeleteLoading] = useState(false); const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [sorting, setSorting] = useState<SortingState>([]);
const productsColumns: ColumnDef<Product>[] = [ const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
const deleteResponse = await ProductApi.delete(
selectedProduct?.id as number
);
if (isResponseError(deleteResponse)) {
toast.error(deleteResponse.message);
setIsDeleteLoading(false);
return;
}
refreshProducts();
deleteModal.closeModal();
toast.success('Successfully delete Product!');
setIsDeleteLoading(false);
};
const productsColumns: ColumnDef<Product>[] = useMemo(
() => [
{ {
header: '#', header: 'No',
cell: (props) => cell: (props) =>
tableFilterState.pageSize * (tableFilterState.page - 1) + tableFilterState.pageSize * (tableFilterState.page - 1) +
props.row.index + props.row.index +
@@ -142,14 +180,12 @@ const ProductsTable = () => {
header: 'Merek', header: 'Merek',
}, },
{ {
accessorKey: 'product_category', accessorFn: (row) => row.product_category?.name ?? '-',
header: 'Kategori', header: 'Kategori',
cell: (props) => props.row.original.product_category?.name ?? '-',
}, },
{ {
accessorKey: 'uom', accessorFn: (row) => row.uom?.name ?? '-',
header: 'Satuan', header: 'Satuan',
cell: (props) => props.row.original.uom?.name ?? '-',
}, },
{ {
accessorKey: 'product_price', accessorKey: 'product_price',
@@ -178,10 +214,9 @@ const ProductsTable = () => {
cell: (props) => props.row.original.expiry_period ?? '-', cell: (props) => props.row.original.expiry_period ?? '-',
}, },
{ {
accessorKey: 'suppliers', accessorFn: (row) =>
row.suppliers?.map((s) => s.name).join(', ') || '-',
header: 'Supplier', header: 'Supplier',
cell: (props) =>
props.row.original.suppliers?.map((s) => s.name).join(', ') || '-',
}, },
{ {
accessorKey: 'flag', accessorKey: 'flag',
@@ -190,17 +225,15 @@ const ProductsTable = () => {
props.row.original.flag ? props.row.original.flag : '-', props.row.original.flag ? props.row.original.flag : '-',
}, },
{ {
accessorKey: 'subs_flags', accessorFn: (row) =>
row.sub_flags?.length ? row.sub_flags.join(', ') : '-',
header: 'Kategori Flags', header: 'Kategori Flags',
cell: (props) =>
props.row.original.sub_flags?.length
? props.row.original.sub_flags.join(', ')
: '-',
}, },
{ {
header: 'Aksi', header: 'Aksi',
cell: (props) => { cell: (props: CellContext<Product, unknown>) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length; const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows; const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex = const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1; currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
@@ -213,127 +246,63 @@ const ProductsTable = () => {
}; };
return ( return (
<>
{currentPageSize > 2 && (
<RowDropdownOptions isLast2Rows={isLast2Rows}>
<RowOptionsMenu <RowOptionsMenu
type='dropdown'
props={props} props={props}
popoverPosition={isLast2Rows ? 'top' : 'bottom'}
deleteClickHandler={deleteClickHandler} deleteClickHandler={deleteClickHandler}
/> />
</RowDropdownOptions>
)}
{currentPageSize <= 2 && (
<RowCollapseOptions>
<RowOptionsMenu
type='collapse'
props={props}
deleteClickHandler={deleteClickHandler}
/>
</RowCollapseOptions>
)}
</>
); );
}, },
}, },
]; ],
[tableFilterState.pageSize, tableFilterState.page, deleteModal]
const confirmationModalDeleteClickHandler = async () => {
setIsDeleteLoading(true);
const deleteResponse = await ProductApi.delete(
selectedProduct?.id as number
); );
if (isResponseError(deleteResponse)) {
toast.error(deleteResponse.message);
setIsDeleteLoading(false);
return;
}
refreshProducts();
deleteModal.closeModal();
toast.success('Successfully delete Product!');
setIsDeleteLoading(false);
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
updateFilter('search', e.target.value);
};
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType;
setPageSize(newVal.value as number);
};
const updateSortingFilter = useCallback(
(
sortName: Exclude<keyof typeof tableFilterState, 'page' | 'pageSize'>,
sortFilter: ColumnSort | undefined
) => {
if (!sortFilter) {
updateFilter(sortName, '');
} else {
updateFilter(sortName, sortFilter.desc ? 'desc' : 'asc');
}
},
[updateFilter]
);
useEffect(() => {
const nameSortFilter = sorting.find((sortItem) => sortItem.id === 'name');
const skuSortFilter = sorting.find((sortItem) => sortItem.id === 'sku');
const brandSortFilter = sorting.find((sortItem) => sortItem.id === 'brand');
const categorySortFilter = sorting.find(
(sortItem) => sortItem.id === 'product_category'
);
updateSortingFilter('nameSort', nameSortFilter);
updateSortingFilter('skuSort', skuSortFilter);
updateSortingFilter('brandSort', brandSortFilter);
updateSortingFilter('categorySort', categorySortFilter);
}, [sorting, updateSortingFilter]);
return ( return (
<> <>
<div className='w-full p-0 sm:p-4'> <div className='w-full'>
<div className='flex flex-col gap-2 mb-4'> {/* Header Section */}
<div className='w-full flex flex-col sm:flex-row justify-between items-end sm:items-center gap-2'> <div className='w-full p-3 flex flex-row justify-between gap-3 flex-wrap border-b border-base-content/10'>
<div className='w-full flex flex-row'> {/* Action Buttons */}
<div className='w-fit flex flex-row gap-3 flex-wrap'>
<RequirePermission permissions='lti.master.products.create'> <RequirePermission permissions='lti.master.products.create'>
<Button <Button
href='/master-data/product/add' href='/master-data/product/add'
variant='outline'
className='w-full sm:w-fit'
color='primary' color='primary'
className='px-3 py-2.5 w-fit text-sm text-base-100 rounded-lg shadow-sm'
> >
<Icon icon='ic:round-plus' width={24} height={24} /> <Icon icon='heroicons:plus' width={20} height={20} />
Tambah Tambah Produk
</Button> </Button>
</RequirePermission> </RequirePermission>
</div> </div>
{/* Search */}
<div className='flex flex-1 flex-row justify-start sm:justify-end items-center gap-3 flex-wrap'>
<DebouncedTextInput <DebouncedTextInput
name='search' name='search'
placeholder='Cari Produk' placeholder='Cari Produk'
value={tableFilterState.search} value={tableFilterState.search ?? ''}
onChange={searchChangeHandler} onChange={searchChangeHandler}
className={{ wrapper: 'sm:max-w-3xs' }} startAdornment={
<Icon
icon='heroicons:magnifying-glass'
width={20}
height={20}
/> />
</div> }
<div className='flex flex-row justify-end'> className={{
<SelectInput wrapper: 'w-full min-w-24 max-w-3xs',
label='Baris' inputWrapper: 'rounded-xl! shadow-button-soft',
options={ROWS_OPTIONS} input:
value={{ 'placeholder:font-semibold placeholder:text-base-content/50',
label: String(tableFilterState.pageSize),
value: tableFilterState.pageSize,
}} }}
onChange={pageSizeChangeHandler}
className={{ wrapper: 'max-w-28' }}
/> />
</div> </div>
</div> </div>
{/* Table Section */}
<div className='flex flex-col mb-4'>
<Table<Product> <Table<Product>
data={isResponseSuccess(products) ? products?.data : []} data={isResponseSuccess(products) ? products?.data : []}
columns={productsColumns} columns={productsColumns}
@@ -343,25 +312,21 @@ const ProductsTable = () => {
isResponseSuccess(products) ? products?.meta?.total_results : 0 isResponseSuccess(products) ? products?.meta?.total_results : 0
} }
onPageChange={setPage} onPageChange={setPage}
onPageSizeChange={setPageSize}
isLoading={isLoading} isLoading={isLoading}
sorting={sorting} sorting={sorting}
setSorting={setSorting} setSorting={setSorting}
className={{ className={{
containerClassName: cn({ containerClassName: cn('p-3 mb-0', {
'mb-20': 'w-full':
isResponseSuccess(products) && products?.data?.length === 0, isResponseSuccess(products) && products?.data?.length === 0,
}), }),
tableWrapperClassName: 'overflow-x-auto min-h-full!', headerColumnClassName: 'text-nowrap',
tableClassName: 'font-inter w-full table-auto min-h-full!',
headerRowClassName: 'border-b border-b-gray-200',
headerColumnClassName:
'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
bodyRowClassName: 'border-b border-b-gray-200',
bodyColumnClassName:
'px-6 py-3 last:flex last:flex-row last:justify-end',
}} }}
/> />
</div> </div>
</div>
<ConfirmationModal <ConfirmationModal
ref={deleteModal.ref} ref={deleteModal.ref}
type='error' type='error'