'use client'; import { ChangeEventHandler, useEffect, useState } from 'react'; import useSWR from 'swr'; import { CellContext, ColumnDef, Row, SortingState, } from '@tanstack/react-table'; import toast from 'react-hot-toast'; import { Icon } from '@iconify/react'; import Table from '@/components/Table'; import DebouncedTextInput from '@/components/input/DebouncedTextInput'; import Button from '@/components/Button'; import { useModal } from '@/components/Modal'; import ConfirmationModal from '@/components/modal/ConfirmationModal'; import SelectInput, { OptionType, useSelect, } from '@/components/input/SelectInput'; import RowDropdownOptions from '@/components/table/RowDropdownOptions'; import RowCollapseOptions from '@/components/table/RowCollapseOptions'; import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper'; import RealizationStatusBadge from '@/components/pages/expense/RealizationStatusBadge'; import ExpenseStatusBadge from '@/components/pages/expense/ExpenseStatusBadge'; import CheckboxInput from '@/components/input/CheckboxInput'; import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes'; import DateInput from '@/components/input/DateInput'; import { Expense } from '@/types/api/expense'; import { ExpenseApi } from '@/services/api/expense'; import { cn, formatCurrency } from '@/lib/helper'; import { isResponseSuccess } from '@/lib/api-helper'; import { useTableFilter } from '@/services/hooks/useTableFilter'; import { ROWS_OPTIONS } from '@/config/constant'; import { LocationApi, SupplierApi } from '@/services/api/master-data'; import { Location } from '@/types/api/master-data/location'; import { Supplier } from '@/types/api/master-data/supplier'; const RowOptionsMenu = ({ type = 'dropdown', props, approveClickHandler, rejectClickHandler, deleteClickHandler, }: { type: 'dropdown' | 'collapse'; props: CellContext; approveClickHandler: () => void; rejectClickHandler: () => void; deleteClickHandler: () => void; }) => { const showEditButton = props.row.original.approval.action !== 'REJECTED' && props.row.original.approval.step_number !== 5 && props.row.original.approval.action !== 'APPROVED'; const showDeleteButton = showEditButton; // TODO: apply RBAC const showApproveButton = showEditButton; const showRejectButton = showEditButton; return ( {showEditButton && ( )} {/* TODO: apply RBAC */} {showApproveButton && ( )} {showRejectButton && ( )} {showDeleteButton && ( )} ); }; const ExpensesTable = () => { const { state: tableFilterState, updateFilter, setPage, setPageSize, toQueryString: getTableFilterQueryString, } = useTableFilter({ initial: { search: '', nameSort: '', transactionDate: '', realizationDate: '', locationId: '', vendorId: '', userId: '', }, paramMap: { page: 'page', pageSize: 'limit', nameSort: 'sort_name', transactionDate: 'transaction_date', realizationDate: 'realization_date', locationId: 'location_id', vendorId: 'vendor_id', userId: 'user_id', }, }); const { data: expenses, isLoading, mutate: refreshExpenses, } = useSWR( `${ExpenseApi.basePath}${getTableFilterQueryString()}`, ExpenseApi.getAllFetcher ); const deleteModal = useModal(); const approveModal = useModal(); const rejectModal = useModal(); const [selectedExpense, setSelectedExpense] = useState( undefined ); const [isDeleteLoading, setIsDeleteLoading] = useState(false); const [isApproveLoading, setIsApproveLoading] = useState(false); const [isRejectLoading, setIsRejectLoading] = useState(false); const [sorting, setSorting] = useState([]); const [rowSelection, setRowSelection] = useState>({}); const selectedRowIds = Object.keys(rowSelection).map((item) => parseInt(item) ); const expensesColumns: ColumnDef[] = [ { id: 'select', header: ({ table }) => (
), cell: ({ row }) => { const isCheckboxDisabled = !row.getCanSelect() || row.original.approval.action === 'REJECTED'; return (
); }, }, { accessorKey: 'transaction_date', header: 'Tanggal Pengajuan', }, { accessorKey: 'realization_date', header: 'Tanggal Realisasi', cell: (props) => props.getValue() ?? '-', }, { accessorKey: 'location', header: 'Lokasi', cell: (props) => props.row.original.location.name ?? '-', }, { accessorFn: (row) => row.created_user.name ?? '-', header: 'Nama Pengaju', }, { accessorFn: (row) => row.vendor.name ?? '-', header: 'Vendor', }, { accessorKey: 'nominal', header: 'Nominal', cell: (props) => props.row.original.nominal ? `Rp${formatCurrency(props.row.original.nominal)}` : '-', }, { accessorKey: 'paid', header: 'Sudah Bayar', cell: (props) => props.row.original.paid ? `Rp${formatCurrency(props.row.original.paid)}` : '-', }, { accessorKey: 'remaining_cost', header: 'Sisa Bayar', cell: (props) => props.row.original.remaining_cost ? `Rp${formatCurrency(props.row.original.remaining_cost)}` : '-', }, { header: 'Status Pencairan', cell: (props) => ( ), }, { header: 'Status BOP', cell: (props) => ( ), }, { header: 'Aksi', cell: (props) => { const currentPageSize = props.table.getPaginationRowModel().rows.length; const currentPageRows = props.table.getPaginationRowModel().flatRows; const currentRowRelativeIndex = currentPageRows.findIndex((r) => r.id === props.row.id) + 1; const isLast2Rows = currentRowRelativeIndex > currentPageSize - 2; const approveClickHandler = () => { setSelectedExpense(props.row.original); // Set row selection setRowSelection({ [String(props.row.original.id)]: true, }); approveModal.openModal(); }; const rejectClickHandler = () => { setSelectedExpense(props.row.original); // Set row selection setRowSelection({ [String(props.row.original.id)]: true, }); rejectModal.openModal(); }; const deleteClickHandler = () => { setSelectedExpense(props.row.original); deleteModal.openModal(); }; return ( <> {currentPageSize > 2 && ( )} {currentPageSize <= 2 && ( )} ); }, }, ]; const tableEnableRowSelectionHandler: (row: Row) => boolean = ( row ) => { return row.original.approval.action !== 'REJECTED'; }; const bulkApproveClickHandler = () => { approveModal.openModal(); }; const bulkRejectClickHandler = () => { rejectModal.openModal(); }; const confirmationModalDeleteClickHandler = async () => { setIsDeleteLoading(true); await ExpenseApi.delete(selectedExpense?.id as number); refreshExpenses(); deleteModal.closeModal(); toast.success('Berhasil menghapus biaya operasional!'); setIsDeleteLoading(false); }; const confirmationModalApproveClickHandler = async (notes: string) => { setIsApproveLoading(true); const bulkApproveResponse = await ExpenseApi.bulkApprove( selectedRowIds, notes ); if (isResponseSuccess(bulkApproveResponse)) { refreshExpenses(); approveModal.closeModal(); toast.success( `Berhasil approve ${selectedRowIds.length} data transfer ke laying!` ); setRowSelection({}); } else { approveModal.closeModal(); toast.error( `Gagal approve ${selectedRowIds.length} data transfer ke laying!` ); } setIsApproveLoading(false); }; const confirmationModalRejectClickHandler = async (notes: string) => { setIsRejectLoading(true); const bulkRejectResponse = await ExpenseApi.bulkReject( selectedRowIds, notes ); if (isResponseSuccess(bulkRejectResponse)) { refreshExpenses(); rejectModal.closeModal(); toast.success( `Berhasil reject ${selectedRowIds.length} data transfer ke laying!` ); setRowSelection({}); } else { rejectModal.closeModal(); toast.error( `Gagal reject ${selectedRowIds.length} data transfer ke laying!` ); } setIsRejectLoading(false); }; const { setInputValue: setLocationInputValue, options: locationOptions, isLoadingOptions: isLoadingLocationOptions, } = useSelect(LocationApi.basePath, 'id', 'name'); const [selectedLocation, setSelectedLocation] = useState( null ); const locationChangeHandler = (val: OptionType | OptionType[] | null) => { setSelectedLocation(val as OptionType); updateFilter( 'locationId', val ? ((val as OptionType).value as string) : '' ); }; const { setInputValue: setVendorInputValue, options: vendorOptions, isLoadingOptions: isLoadingVendorOptions, } = useSelect(SupplierApi.basePath, 'id', 'name'); const [selectedVendor, setSelectedVendor] = useState(null); const vendorChangeHandler = (val: OptionType | OptionType[] | null) => { setSelectedVendor(val as OptionType); updateFilter('vendorId', val ? ((val as OptionType).value as string) : ''); }; const searchChangeHandler: ChangeEventHandler = (e) => { updateFilter('search', e.target.value); }; const transactionDateChangeHandler: ChangeEventHandler = ( e ) => { updateFilter('transactionDate', e.target.value); }; const realizationDateChangeHandler: ChangeEventHandler = ( e ) => { updateFilter('realizationDate', e.target.value); }; const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => { const newVal = val as OptionType; setPageSize(newVal.value as number); }; // track sorting useEffect(() => { const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name'); if (!isNameSorted) { updateFilter('nameSort', ''); } else { updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc'); } }, [sorting, updateFilter]); return ( <>
{selectedRowIds.length > 0 && ( <> {/* TODO: apply RBAC */} )}
data={isResponseSuccess(expenses) ? expenses?.data : []} columns={expensesColumns} pageSize={tableFilterState.pageSize} page={isResponseSuccess(expenses) ? expenses?.meta?.page : 0} totalItems={ isResponseSuccess(expenses) ? expenses?.meta?.total_results : 0 } onPageChange={setPage} isLoading={isLoading} sorting={sorting} setSorting={setSorting} rowSelection={rowSelection} setRowSelection={setRowSelection} enableRowSelection={tableEnableRowSelectionHandler} className={{ containerClassName: cn({ 'mb-20': isResponseSuccess(expenses) && expenses?.data?.length === 0, }), tableWrapperClassName: 'overflow-x-auto min-h-full!', 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', }} />
); }; export default ExpensesTable;