Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Spinner from '@/components/reuseable/Spinner';
- import { setPageTitle } from '@/store/themeConfigSlice';
- import { checkFile } from '@/utils/checkFile';
- import { deleteFile, postData, postFile, putData, getData, previewFile } from '@/utils/fetch';
- import showDialog from '@/utils/showDialog';
- import Link from 'next/link';
- import { useRouter } from 'next/router';
- import { Fragment, useEffect, useRef, useState } from 'react';
- import { useDispatch, useSelector } from 'react-redux';
- import TextInput from '@/components/reuseable/TextInput';
- import { maxCharacter, regexAlphanumeric, regexDescription } from '@/utils/regex';
- import { yupResolver } from '@hookform/resolvers/yup';
- import { useForm } from 'react-hook-form';
- import * as yup from 'yup';
- import CustomInputFile from '@/components/reuseable/core/input-file';
- import { showMessage } from '@/components/reuseable/ShowMessage';
- import { getCookie } from 'cookies-next';
- import { IRootState } from '@/store';
- import cookieExpirationMiddleware from '@/middlewares/WithAuth';
- import { userLoginAzure, userLogout } from '@/store/azure-auth/actions';
- import { PaginationType } from '@/utils/interface';
- // import { SpotlightCategoryType } from '@/utils/interface/spotlight-category';
- import { LifeFriendActivityType } from '@/utils/interface/life-activity';
- import { DataTable, DataTableSortStatus } from 'mantine-datatable';
- import { useDebounce } from 'use-debounce';
- import { config } from '@/configs';
- import { sortBy } from 'lodash';
- const schema = yup.object({
- });
- export default function AddData({ token, name, username }: any) {
- 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 selectedID = selectedRecords.map((item: any) => item.id)
- 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}`;
- };
- //* get data
- useEffect(() => {
- if (token) {
- const getDataCategory = async () => {
- try {
- setIsLoading(true);
- const { data } = await getData(`/lifefriend-activity`, { page: page, limit: pageSize, search: searchKey, priority: false });
- setInitialRecords(data.activities);
- setPagination(data.pagination);
- setIsLoading(false);
- } catch (error: any) {
- setIsLoading(false);
- }
- };
- getDataCategory();
- }
- }, [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]);
- 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 () => {
- try {
- await getData('/users', { page: 1, limit: 1 });
- } catch (error) {
- return false;
- }
- };
- checkSession();
- const check = cookieExpirationMiddleware(token, tokenBackup);
- if (check) {
- showMessage('Sesi telah berakhir, Silahkan login kembali', 'error');
- dispatch(userLogout());
- router.push('/auth/login-v2');
- }
- }, []);
- const { query } = useRouter();
- // const inputFileRef = useRef<any>();
- // const inputFileRef2 = useRef<any>();
- const {
- register,
- handleSubmit,
- formState: { errors },
- } = useForm({
- resolver: yupResolver(schema),
- });
- // const initialStateForm = {
- // title: query?.title || '',
- // type: query?.type || 'spotlight',
- // };
- // const [form, setForm] = useState(initialStateForm);
- const [isLoading, setIsLoading] = useState<boolean>(false);
- // const [isUpload, setIsUpload] = useState<boolean>(false);
- // const [isUploadMobile, setIsUploadMobile] = useState<boolean>(false);
- // const handleChangeInput = (e: any) => {
- // const { name, value } = e.target;
- // setForm((prevState) => ({
- // ...prevState,
- // [name]: value,
- // }));
- // };
- const submitForm = async (e: any) => {
- if (selectedID.length != 0) {
- //* Add Data
- try {
- setIsLoading(true);
- await postData('lifefriend-activity/update-priority', selectedID);
- setIsLoading(false);
- showDialog('add', 'success');
- router.replace('./');
- } catch (error: any) {
- showDialog('add', 'failed');
- setIsLoading(false);
- }
- }
- };
- useEffect(() => {
- dispatch(setPageTitle('Tambah Life Friend'));
- });
- return (
- <Fragment>
- <div className="font-inter">
- <div>
- <h5 className="title-banner text-lg dark:text-white-light">{!query.id ? 'Tambah Job Spotlight Content' : 'Atur Job Spotlight Content'}</h5>
- <div className="subtitle-banner">{!query.id ? 'Buat Job Spotlight Content' : 'Ubah Job Spotlight Content'}</div>
- </div>
- <form onSubmit={handleSubmit(submitForm)}>
- <div className="wrapper-form-addBanner mt-6">
- {/* <div className="input-banner mb-5">
- <label htmlFor="title" className="font-semibold text-[#787A7D]">
- <span className="text-[#ED1C24]">*</span> Title
- </label>
- <TextInput placeholder="Masukkan title" name="title" value={form.title} onChange={handleChangeInput} register={register} errors={errors} />
- </div> */}
- <div className="flex w-full justify-end items-center gap-2">
- <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 className="datatables mt-5">
- <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>
- )
- },
- ]}
- 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>
- <div className="mt-5 flex justify-end">
- <div className="flex gap-4">
- <Link href="./" className="btn-delete-item-banner flex items-center">
- Batal
- </Link>
- <button
- type="submit"
- className={`btn-add-item-banner flex items-center ${
- selectedID.length == 0 || isLoading ? 'btn-disabled ' : ''
- }`}
- disabled={selectedID.length == 0 || isLoading ? true : false}
- >
- {isLoading && <Spinner />}
- {query.id ? 'Ubah' : 'Simpan'}
- </button>
- </div>
- </div>
- </form>
- </div>
- </Fragment>
- );
- }
- 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