rework notification-table
This commit is contained in:
@@ -4,34 +4,205 @@ import { useTranslations } from 'next-intl';
|
||||
import { IconCheck, IconArrowLeft, IconArrowRight, IconDoubleArrowLeft, IconDoubleArrowRight } from '@/app/ui/icons/icons';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAllNotifications } from '@/app/hooks/react-query/useAllNotificationsList';
|
||||
import { notificationsMarkAsRead, notificationsDelete } from '@/app/actions/notificationActions';
|
||||
import { notificationsMarkAsRead, notificationsDelete, NotificationBody } from '@/app/actions/notificationActions';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { formatDate, formatDateTime } from '@/app/lib/formatDate';
|
||||
|
||||
import {
|
||||
useReactTable,
|
||||
getCoreRowModel,
|
||||
getPaginationRowModel,
|
||||
flexRender,
|
||||
createColumnHelper,
|
||||
RowSelectionState,
|
||||
} from '@tanstack/react-table';
|
||||
|
||||
|
||||
export function NotificationsList() {
|
||||
const t = useTranslations('Global');
|
||||
const norificationTranslate = useTranslations('Notifications');
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [selectedFiles, setSelectedFiles] = useState<Set<number>>(new Set());
|
||||
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
|
||||
const [loadingIds, setLoadingIds] = useState<Set<number>>(new Set());
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const [pageSize] = useState(10);
|
||||
const { data: allNotifications, isLoading } = useAllNotifications(currentPage, pageSize);
|
||||
const [pagination, setPagination] = useState({
|
||||
pageIndex: 0,
|
||||
pageSize: 10,
|
||||
});
|
||||
|
||||
const { data: allNotifications, isLoading } = useAllNotifications(
|
||||
pagination.pageIndex,
|
||||
pagination.pageSize
|
||||
);
|
||||
|
||||
const totalPages = allNotifications?.totalPages || 0;
|
||||
const currentPageNum = allNotifications?.currentPage || 0;
|
||||
const totalRecords = allNotifications?.totalElements || 0;
|
||||
|
||||
const goToFirstPage = () => setCurrentPage(0);
|
||||
const goToPrevPage = () => setCurrentPage(prev => Math.max(0, prev - 1));
|
||||
const goToNextPage = () => setCurrentPage(prev => Math.min(totalPages - 1, prev + 1));
|
||||
const goToLastPage = () => setCurrentPage(totalPages - 1);
|
||||
const goToPage = (page: number) => setCurrentPage(page);
|
||||
const columnHelper = createColumnHelper<NotificationBody>();
|
||||
|
||||
const columns = [
|
||||
columnHelper.display({
|
||||
id: 'select',
|
||||
header: ({ table }) => {
|
||||
const currentPageRows = table.getCoreRowModel().rows;
|
||||
const unreadRowsOnPage = currentPageRows.filter(row => row.original.status !== 'READIED');
|
||||
const allUnreadSelectedOnPage = unreadRowsOnPage.every(row => rowSelection[row.original.id]);
|
||||
|
||||
return (
|
||||
<div className="select-all-header">
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={() => {
|
||||
if (allUnreadSelectedOnPage) {
|
||||
|
||||
const newSelection = { ...rowSelection };
|
||||
unreadRowsOnPage.forEach(row => {
|
||||
delete newSelection[row.original.id];
|
||||
});
|
||||
setRowSelection(newSelection);
|
||||
} else {
|
||||
|
||||
const newSelection = { ...rowSelection };
|
||||
unreadRowsOnPage.forEach(row => {
|
||||
newSelection[row.original.id] = true;
|
||||
});
|
||||
setRowSelection(newSelection);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{allUnreadSelectedOnPage ? t('deselect') : t('select-all')}
|
||||
</button>
|
||||
|
||||
{Object.keys(rowSelection).length > 0 && (
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={() => {
|
||||
const selectedIds = Object.keys(rowSelection).map(Number);
|
||||
notificationActionHandler(selectedIds, 'mark-as-read');
|
||||
}}
|
||||
>
|
||||
{t('mark-as-read')} ({Object.keys(rowSelection).length})
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const isReadied = row.original.status === 'READIED';
|
||||
const isSelected = !!rowSelection[row.original.id];
|
||||
|
||||
return (
|
||||
<div className="notification-check">
|
||||
{!isReadied ? (
|
||||
<button
|
||||
onClick={() => {
|
||||
setRowSelection((prev) => ({
|
||||
...prev,
|
||||
[row.original.id]: !prev[row.original.id],
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{isSelected && <IconCheck />}
|
||||
</button>
|
||||
) : (
|
||||
<div className="empty-block"></div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor('message', {
|
||||
id: 'message',
|
||||
header: () => null, // No header text, using custom header above
|
||||
cell: ({ row }) => {
|
||||
const item = row.original;
|
||||
return (
|
||||
<div className="notification-body">
|
||||
<div className="notification-header">
|
||||
{/* Optional header content */}
|
||||
</div>
|
||||
<div className="notification-text">
|
||||
{norificationTranslate.has(item.message)
|
||||
? norificationTranslate(item.message)
|
||||
: item.message} ({item.id})
|
||||
</div>
|
||||
<div className="notification-footer">
|
||||
<div className="notification-date">
|
||||
{item.createdAt
|
||||
? `${formatDate(item.createdAt)}: ${formatDateTime(item.createdAt)}`
|
||||
: '---'}
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-remove"
|
||||
onClick={() => {
|
||||
notificationActionHandler([item.id], 'remove');
|
||||
}}
|
||||
disabled={loadingIds.has(item.id)}
|
||||
>
|
||||
{t('remove')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const table = useReactTable({
|
||||
data: allNotifications?.notifications || [],
|
||||
columns,
|
||||
state: {
|
||||
rowSelection,
|
||||
pagination,
|
||||
},
|
||||
enableRowSelection: true,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
onPaginationChange: setPagination,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
manualPagination: true,
|
||||
pageCount: totalPages,
|
||||
});
|
||||
|
||||
async function notificationActionHandler(ids: number[], action: 'remove' | 'mark-as-read') {
|
||||
setLoadingIds(prev => {
|
||||
const newSet = new Set(prev);
|
||||
ids.forEach(id => newSet.add(id));
|
||||
return newSet;
|
||||
});
|
||||
|
||||
try {
|
||||
let response;
|
||||
|
||||
if (action === 'mark-as-read') {
|
||||
response = await notificationsMarkAsRead(ids);
|
||||
} else if (action === 'remove') {
|
||||
response = await notificationsDelete(ids);
|
||||
}
|
||||
|
||||
if (response?.success) {
|
||||
await queryClient.invalidateQueries({ queryKey: ['activeNotifications'] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['allNotifications'] });
|
||||
|
||||
// Clear selection after successful action
|
||||
setRowSelection({});
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = action === 'mark-as-read' ? 'Failed to mark as read' : 'Failed to remove';
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setLoadingIds(prev => {
|
||||
const newSet = new Set(prev);
|
||||
ids.forEach(id => newSet.delete(id));
|
||||
return newSet;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const getPageNumbers = (): (number | string)[] => {
|
||||
const delta: number = 2;
|
||||
const currentPageNum = pagination.pageIndex;
|
||||
const range: number[] = [];
|
||||
const rangeWithDots: (number | string)[] = [];
|
||||
let l: number | undefined;
|
||||
@@ -57,85 +228,25 @@ export function NotificationsList() {
|
||||
return rangeWithDots;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
console.log(allNotifications);
|
||||
}, [allNotifications])
|
||||
|
||||
function selectHandler(fileId: number) {
|
||||
setSelectedFiles((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
|
||||
if (newSet.has(fileId)) {
|
||||
newSet.delete(fileId)
|
||||
} else {
|
||||
newSet.add(fileId)
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
}
|
||||
|
||||
function clearHandler() {
|
||||
setSelectedFiles(new Set());
|
||||
}
|
||||
|
||||
function selectAllHandler() {
|
||||
const idsToSelect = allNotifications?.notifications
|
||||
.filter(item => item.status !== 'READIED')
|
||||
.map(item => item.id);
|
||||
|
||||
setSelectedFiles(new Set(idsToSelect));
|
||||
}
|
||||
|
||||
async function notificationActionHandler(ids: number[], action: 'remove' | 'mark-as-read') {
|
||||
setLoadingIds(prev => {
|
||||
const newSet = new Set(prev);
|
||||
ids.forEach(id => newSet.add(id));
|
||||
return newSet;
|
||||
});
|
||||
|
||||
try {
|
||||
let response;
|
||||
|
||||
if (action === 'mark-as-read') {
|
||||
response = await notificationsMarkAsRead(ids);
|
||||
} else if (action === 'remove') {
|
||||
response = await notificationsDelete(ids);
|
||||
}
|
||||
|
||||
if (response?.success) {
|
||||
await queryClient.invalidateQueries({ queryKey: ['activeNotifications'] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['allNotifications'] });
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = action === 'mark-as-read' ? 'Failed to mark as read' : 'Failed to remove';
|
||||
setError(errorMessage);
|
||||
} finally {
|
||||
setLoadingIds(prev => {
|
||||
const newSet = new Set(prev);
|
||||
ids.forEach(id => newSet.delete(id));
|
||||
return newSet;
|
||||
});
|
||||
|
||||
setSelectedFiles(prev => {
|
||||
const newSet = new Set(prev);
|
||||
ids.forEach(id => newSet.delete(id));
|
||||
return newSet;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="notifications-list-wrapper"
|
||||
>
|
||||
<div
|
||||
className="notifications-list-header"
|
||||
>
|
||||
<h4>
|
||||
{t('all-notifications')}
|
||||
</h4>
|
||||
|
||||
<div
|
||||
<div className="notifications-list-wrapper">
|
||||
<div className="notifications-list-header">
|
||||
<h4>{t('all-notifications')}</h4>
|
||||
<div className="notifications-table-header">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<div key={headerGroup.id} className="table-row n-header">
|
||||
{headerGroup.headers.map((header) => (
|
||||
<div key={header.id} className="table-cell">
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{/* <div
|
||||
className="notifications-list-action"
|
||||
>
|
||||
{(selectedFiles.size !== 0) && (
|
||||
@@ -168,100 +279,49 @@ export function NotificationsList() {
|
||||
>
|
||||
{t('select-all')}
|
||||
</button>
|
||||
</div>
|
||||
</div> */}
|
||||
</div>
|
||||
<div
|
||||
className="notifications-list-body"
|
||||
>
|
||||
{(allNotifications?.notifications.length !== 0) && (
|
||||
allNotifications?.notifications.map(item => {
|
||||
return (
|
||||
<div
|
||||
className={`notification-item ${loadingIds.has(item.id) ? 'loading' : ''} ${item.status}`}
|
||||
key={item.id}
|
||||
>
|
||||
|
||||
<div className="notifications-list-body">
|
||||
{allNotifications?.notifications.length !== 0 ? (
|
||||
<div className="notifications-table">
|
||||
<div className="notifications-table-body">
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<div
|
||||
className="notification-check"
|
||||
key={row.id}
|
||||
className={`table-row ${loadingIds.has(row.original.id) ? 'loading' : ''} ${row.original.status}`}
|
||||
>
|
||||
{item.status !== 'READIED' ? (
|
||||
<button
|
||||
onClick={() => {
|
||||
selectHandler(item.id);
|
||||
}}
|
||||
>
|
||||
{selectedFiles.has(item.id) && (
|
||||
<IconCheck />
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<div key={cell.id} className="table-cell">
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<div className="empty-block"></div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="notification-body"
|
||||
>
|
||||
<div
|
||||
className="notification-header"
|
||||
>
|
||||
{/* <div
|
||||
className="notification-title"
|
||||
>
|
||||
{item.type} {item.id}
|
||||
</div> */}
|
||||
{/* <div
|
||||
className="notification-status"
|
||||
>
|
||||
{item.status}
|
||||
</div> */}
|
||||
</div>
|
||||
<div
|
||||
className="notification-text"
|
||||
>
|
||||
{norificationTranslate.has(item.message) ? norificationTranslate(item.message) : item.message}
|
||||
</div>
|
||||
<div
|
||||
className="notification-footer"
|
||||
>
|
||||
<div
|
||||
className="notification-date"
|
||||
>
|
||||
{item.createdAt ? `${formatDate(item.createdAt)}: ${formatDateTime(item.createdAt)}` : '---'}
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="btn btn-remove"
|
||||
onClick={() => {
|
||||
notificationActionHandler([item.id], 'remove');
|
||||
}}
|
||||
disabled={loadingIds.has(item.id)}
|
||||
>
|
||||
{t('remove')}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="no-notifications">{t('no-notifications')}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="notifications-list-footer"
|
||||
>
|
||||
<div className="notifications-list-footer">
|
||||
{totalPages > 0 && (
|
||||
<div className="pagination-controls">
|
||||
<button
|
||||
className="arrow"
|
||||
onClick={goToFirstPage}
|
||||
disabled={currentPageNum === 0}
|
||||
onClick={() => table.firstPage()}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<IconDoubleArrowLeft />
|
||||
</button>
|
||||
<button
|
||||
onClick={goToPrevPage}
|
||||
onClick={() => table.previousPage()}
|
||||
className="arrow"
|
||||
disabled={currentPageNum === 0}
|
||||
disabled={!table.getCanPreviousPage()}
|
||||
>
|
||||
<IconArrowLeft />
|
||||
</button>
|
||||
@@ -270,8 +330,8 @@ export function NotificationsList() {
|
||||
{getPageNumbers().map((pageNum, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => typeof pageNum === 'number' && goToPage(pageNum)}
|
||||
className={currentPageNum === pageNum ? 'current' : 'other'}
|
||||
onClick={() => typeof pageNum === 'number' && table.setPageIndex(pageNum)}
|
||||
className={pagination.pageIndex === pageNum ? 'current' : 'other'}
|
||||
disabled={pageNum === '...'}
|
||||
>
|
||||
{pageNum === '...' ? '...' : (pageNum as number) + 1}
|
||||
@@ -280,22 +340,24 @@ export function NotificationsList() {
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={goToNextPage}
|
||||
onClick={() => table.nextPage()}
|
||||
className="arrow"
|
||||
disabled={currentPageNum === totalPages - 1}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<IconArrowRight />
|
||||
</button>
|
||||
<button
|
||||
className="arrow"
|
||||
onClick={goToLastPage}
|
||||
disabled={currentPageNum === totalPages - 1}
|
||||
onClick={() => table.lastPage()}
|
||||
disabled={!table.getCanNextPage()}
|
||||
>
|
||||
<IconDoubleArrowRight />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user