Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { showMessage } from '@/components/reuseable/ShowMessage';
- import { config } from '@/configs';
- import { cookieExpirationMiddleware } from '@/middlewares/WithAuth';
- import { IRootState } from '@/store';
- import { userLoginAzure, userLogout } from '@/store/azure-auth/actions';
- import { setPageTitle } from '@/store/themeConfigSlice';
- import { deleteData, deleteFile, getData, previewFile } from '@/utils/fetch';
- import { PaginationType } from '@/utils/interface';
- import { LifeFriendActivityType } from '@/utils/interface/life-activity';
- import showDialog from '@/utils/showDialog';
- import showDialogAction from '@/utils/showDialogAction';
- import { getCookie } from 'cookies-next';
- import sortBy from 'lodash/sortBy';
- import { DataTable, DataTableSortStatus } from 'mantine-datatable';
- import { useRouter } from 'next/router';
- import { useEffect, useState } from 'react';
- import { BsPencilFill } from 'react-icons/bs';
- import { FaTrash } from 'react-icons/fa';
- import { useDispatch, useSelector } from 'react-redux';
- import { useDebounce } from 'use-debounce';
- const ActivityList = ({ token, name, username }: any) => {
- const router = useRouter();
- const dispatch = useDispatch();
- const { token: tokenBackup }: any = useSelector((state: IRootState) => state.azureAuth);
- useEffect(() => {
- if (token) {
- dispatch(userLoginAzure(token, name, username));
- }
- }, []);
- useEffect(() => {
- // const checkSession = async () => {
- const check = cookieExpirationMiddleware(token, tokenBackup);
- if (check) {
- showMessage('Sesi telah berakhir, Silahkan login kembali', 'error');
- dispatch(userLogout());
- router.push('/auth/login-v2');
- }
- // };
- // checkSession();
- }, []);
- const [page, setPage] = useState(1);
- const PAGE_SIZES = [10, 20, 30, 50, 100];
- const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
- const [initialRecords, setInitialRecords] = useState<LifeFriendActivityType[]>([]);
- const [recordsData, setRecordsData] = useState<LifeFriendActivityType[]>(initialRecords);
- const [selectedRecords, setSelectedRecords] = useState<any>([]);
- const [sortStatus, setSortStatus] = useState<DataTableSortStatus>({
- columnAccessor: 'id',
- direction: 'asc',
- });
- const [search, setSearch] = useState('');
- const [searchKey] = useDebounce(search, 500);
- const [pagination, setPagination] = useState<PaginationType>();
- const [indicator, setIndicator] = useState<boolean>(false);
- const [isLoading, setisLoading] = useState<boolean>(false);
- const formatDate = (dateString: any) => {
- const date = new Date(dateString);
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
- };
- const handleDeleteItem = async (id?: string, fileName?: string, fileName2?: string) => {
- if (selectedRecords?.length) {
- const payload = selectedRecords?.map((item: any) => item.id);
- const selectedDelete = selectedRecords.map((item: any) => item.desktop_link);
- const selectedDelete2 = selectedRecords.map((item: any) => item.mobile_link);
- //* delete all
- showDialogAction(async () => {
- try {
- await deleteData(`/lifefriend-activity/batch-delete`, payload);
- await deleteFile({ paths: selectedDelete });
- await deleteFile({ paths: selectedDelete2 });
- console.log(payload)
- console.log(selectedDelete)
- setIndicator(!indicator);
- setSelectedRecords([]);
- showDialog('delete', 'success');
- } catch (error: any) {
- error.response.data.message === 'Sesi Anda telah berakhir!' ? null : showDialog('delete', 'failed');
- }
- });
- } else {
- //* delete one
- showDialogAction(async () => {
- try {
- await deleteData(`/lifefriend-activity/delete/${id}`);
- await deleteFile({ paths: [fileName] });
- await deleteFile({ paths: [fileName2] });
- setIndicator(!indicator);
- showDialog('delete', 'success');
- } catch (error: any) {
- error.response.data.message === 'Sesi Anda telah berakhir!' ? null : error.response.data.message === 'Sesi Anda telah berakhir!' ? null : showDialog('delete', 'failed');
- }
- });
- }
- };
- //* get data
- useEffect(() => {
- if (token) {
- const getDataBanner = async () => {
- try {
- setisLoading(true);
- const { data } = await getData('/lifefriend-activity', { page: page, limit: pageSize, search: searchKey });
- setInitialRecords(data.activities);
- setPagination(data.pagination);
- setisLoading(false);
- } catch (error: any) {
- setisLoading(false);
- }
- };
- getDataBanner();
- }
- }, [indicator, page, pageSize, searchKey]);
- useEffect(() => {
- if (page == 1) return;
- if (initialRecords.length == 0) return setPage(page - 1);
- }, [initialRecords]);
- useEffect(() => {
- setPage(1);
- }, [pageSize]);
- useEffect(() => {
- setRecordsData([...initialRecords]);
- }, [page, pageSize, initialRecords]);
- useEffect(() => {
- const data = sortBy(initialRecords, sortStatus.columnAccessor);
- setInitialRecords(sortStatus.direction === 'desc' ? data.reverse() : data);
- }, [sortStatus]);
- useEffect(() => {
- dispatch(setPageTitle('Life Friend Activity List'));
- });
- return (
- <div className="banner">
- <div className="mb-4 flex justify-between">
- <div>
- <h5 className="title-banner text-lg dark:text-white-light">Activity List</h5>
- <div className="subtitle-banner">Daftar Activity List.</div>
- </div>
- <div className="flex gap-2">
- {selectedRecords.length >= 1 ? (
- <div
- className="btn-delete-item-banner flex items-center"
- onClick={() => {
- handleDeleteItem('yang terpilih');
- }}
- >
- Hapus Terpilih
- </div>
- ) : (
- <></>
- )}
- <div className="btn-add-item-banner flex items-center" onClick={() => router.push('activity-list/input')}>
- Tambah
- </div>
- </div>
- </div>
- <div className="mb-5 flex flex-col gap-5 md:flex-row md:items-center">
- <div className="flex items-center gap-2 ltr:ml-auto rtl:mr-auto">
- <label
- htmlFor="search"
- style={{
- marginBottom: '0',
- }}
- >
- Search :{' '}
- </label>
- <input type="text" name="search" className="form-input w-auto" placeholder="Search..." value={search} onChange={(e) => setSearch(e.target.value)} />
- </div>
- </div>
- <div className="datatables">
- <DataTable
- className="table-hover whitespace-normal"
- records={recordsData}
- columns={[
- {
- accessor: 'created_at',
- title: 'Tanggal',
- sortable: true,
- render: ({ created_at }) => (
- <div className="flex items-center gap-2">
- <div className="title-item-table font-semibold">{formatDate(created_at)}</div>
- </div>
- ),
- },
- {
- accessor: 'link_image',
- title: 'Cover Gambar',
- sortable: true,
- render: ({ link_image }) => (
- <div className="flex items-center gap-2">
- <div className="title-item-table font-semibold">
- <a href={config.BASE_URL_IMG + link_image} target='_blank' rel="noreferrer" className='text-blue-600'>
- image.jpeg
- </a>
- </div>
- </div>
- ),
- },
- {
- accessor: 'alt_text',
- title: 'Alternatif Teks',
- sortable: true,
- render: ({ alt_text }) => (
- <div className="flex items-center gap-2">
- <div className="title-item-table font-semibold">{alt_text}</div>
- </div>
- ),
- },
- {
- accessor: 'title',
- title: 'Title',
- sortable: true,
- },
- {
- accessor: 'description',
- title: 'Deskripsi',
- sortable: true,
- render: ({ description }) => <p className={`truncateTd whitespace-nowrap xl:whitespace-normal`}>{description}</p>,
- },
- {
- accessor: 'status',
- title: 'Status',
- sortable: true,
- render: ({ status }) => <div className={`flex justify-center ${status.toLocaleLowerCase() == 'active' ? 'active-status-tabel' : 'notactive-status-tabel'}`}>{status}</div>,
- },
- {
- accessor: 'item_activities',
- title: 'Content Image',
- sortable: true,
- render: ({item_activities}) => (
- <div className='text-center'>
- <p>{item_activities.map(item => item.link_image).length} image</p>
- </div>
- )
- },
- {
- accessor: '',
- title: 'Action',
- render: ({ id, title, description, alt_text, link_image, status }) => (
- <div className={`flex gap-3 `}>
- <BsPencilFill
- size={20}
- className="cursor-pointer"
- color="#0083F5"
- onClick={() => {
- router.push(
- {
- pathname: 'activity/input',
- query: { id, title, description, alt_text, link_image, status },
- },
- 'activity/input'
- );
- }}
- />
- <FaTrash
- size={20}
- className="cursor-pointer"
- color=" #E30008"
- onClick={() => {
- handleDeleteItem(id, link_image);
- }}
- />
- </div>
- ),
- },
- ]}
- fetching={isLoading}
- highlightOnHover
- totalRecords={pagination?.total}
- recordsPerPage={pageSize}
- page={page}
- onPageChange={(p) => setPage(p)}
- recordsPerPageOptions={PAGE_SIZES}
- onRecordsPerPageChange={setPageSize}
- sortStatus={sortStatus}
- onSortStatusChange={setSortStatus}
- selectedRecords={selectedRecords}
- onSelectedRecordsChange={setSelectedRecords}
- minHeight={200}
- paginationText={({ from, to, totalRecords }) => `Showing ${from} to ${to} of ${pagination?.total} entries`}
- />
- </div>
- </div>
- );
- };
- export default ActivityList;
- export async function getServerSideProps({ req }: any) {
- const token = getCookie('access_token', { req });
- const name = getCookie('name', { req });
- const username = getCookie('username', { req });
- // if (!token) {
- // return {
- // redirect: {
- // destination: '/auth/login-v2',
- // permanent: false,
- // },
- // };
- // }
- if (token) {
- return {
- props: { token, name, username },
- };
- }
- return {
- props: {},
- };
- }
Add Comment
Please, Sign In to add comment