Merge pull request #293 from bipproduction/nico/07-oktober-24

Tambahan API Edit, Delete, List Banner dan Validasi
This commit is contained in:
Amalia
2024-10-07 18:21:26 +08:00
committed by GitHub
5 changed files with 255 additions and 152 deletions

View File

@@ -1,11 +1,7 @@
import { EditBanner } from "@/module/banner"; import { EditBanner } from "@/module/banner";
import { Box } from "@mantine/core";
export default function Page() { export default function Page() {
return ( return (
<Box> <EditBanner />
<EditBanner/>
</Box>
); );
} }

View File

@@ -3,4 +3,4 @@ import ListBanner from "./ui/list_banner";
import CreateBanner from "./ui/create_banner"; import CreateBanner from "./ui/create_banner";
import EditBanner from "./ui/edit_banner"; import EditBanner from "./ui/edit_banner";
import ViewfileBanner from "./ui/viewfile_banner"; import ViewfileBanner from "./ui/viewfile_banner";
export {NavbarBanner, ListBanner, CreateBanner, EditBanner, ViewfileBanner} export { NavbarBanner, ListBanner, CreateBanner, EditBanner, ViewfileBanner }

View File

@@ -10,6 +10,7 @@ import { useRouter } from 'next/navigation';
import { useRef, useState } from 'react'; import { useRef, useState } from 'react';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import { funCreateBanner } from '../lib/api_banner'; import { funCreateBanner } from '../lib/api_banner';
import { title } from 'process';
function CreateBanner() { function CreateBanner() {
const router = useRouter(); const router = useRouter();
@@ -17,36 +18,49 @@ function CreateBanner() {
const tema = useHookstate(TEMA) const tema = useHookstate(TEMA)
const [loadingKonfirmasi, setLoadingKonfirmasi] = useState(false) const [loadingKonfirmasi, setLoadingKonfirmasi] = useState(false)
const [listData, setListData] = useState({ const [listData, setListData] = useState({
title: "", title: "",
image: ""
}); });
const [imgForm, setImgForm] = useState<any>() const [imgForm, setImgForm] = useState<any>()
const openRef = useRef<() => void>(null) const openRef = useRef<() => void>(null)
const [img, setIMG] = useState<any | null>() const [img, setIMG] = useState<any | null>()
// const [body, setBody] = useState<any>({ const [touched, setTouched] = useState({
// id: "", title: false,
// title: "", image: false
// }); })
// function onCheck() {
// const cek = checkAll()
// if (!cek)
// return false
// setModal(true)
// }
function onValidation(kategori: string, val: any) {
if (kategori == 'title') {
setListData({ ...listData, title: val })
if (val === "") {
setTouched({ ...touched, title: true })
} else {
setTouched({ ...touched, title: false })
}
} else if (kategori == 'image') {
if (imgForm) {
setTouched({ ...touched, image: false })
} else {
setTouched({ ...touched, image: true })
}
}
}
async function onSubmit(val: boolean) { async function onSubmit(val: boolean) {
if (!imgForm || !listData.title) {
toast.error("Mohon lengkapi semua data");
}
try { try {
console.log(listData)
setLoadingKonfirmasi(true) setLoadingKonfirmasi(true)
const fd = new FormData() const fd = new FormData()
fd.append("file", imgForm) fd.append("file", imgForm)
fd.append("data", JSON.stringify( fd.append("data", JSON.stringify(
{ {
title: listData.title title: listData.title,
image: listData.image
} }
)) ))
const res = await funCreateBanner(fd); const res = await funCreateBanner(fd);
@@ -80,10 +94,11 @@ function CreateBanner() {
onDrop={async (files) => { onDrop={async (files) => {
if (!files || _.isEmpty(files)) if (!files || _.isEmpty(files))
return toast.error('Tidak ada gambar yang dipilih') return toast.error('Tidak ada gambar yang dipilih')
setImgForm(files[0]) const file = files[0]
// const buffer = URL.createObjectURL(files[0]); setImgForm(file)
const buffer = URL.createObjectURL(new Blob([new Uint8Array(await files[0].arrayBuffer())])) const buffer = URL.createObjectURL(new Blob([new Uint8Array(await files[0].arrayBuffer())]))
setIMG(buffer) setIMG(buffer)
onValidation('image', files[0])
}} }}
activateOnClick={false} activateOnClick={false}
maxSize={1 * 1024 ** 2} maxSize={1 * 1024 ** 2}
@@ -96,7 +111,7 @@ function CreateBanner() {
{ {
img ? img ?
<Image radius="md" src={img} /> <Image radius="md" src={img} alt='' />
: :
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}> <Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}>
<Dropzone.Accept> <Dropzone.Accept>
@@ -123,7 +138,7 @@ function CreateBanner() {
Klik Untuk Upload Image Klik Untuk Upload Image
</Text> </Text>
<Text size="sm" c="dimmed" inline mt={7}> <Text size="sm" c="dimmed" inline mt={7}>
Ukuran Foto Tidak Boleh Lebih Dari 500MB Ukuran Foto Tidak Boleh Lebih Dari 1MB
</Text> </Text>
</div> </div>
</Group> </Group>
@@ -134,15 +149,21 @@ function CreateBanner() {
<Box> <Box>
<TextInput <TextInput
mt={10} mt={10}
label={<Text>Judul Banner</Text>} label={<Text >Judul Banner</Text>}
value={listData.title}
placeholder='Judul Banner' placeholder='Judul Banner'
onChange={(e) => {
setListData({ ...listData, title: e.target.value })
onValidation('title', e.target.value)
}}
styles={{ styles={{
input: { input: {
border: `1px solid ${"#D6D8F6"}`, border: `1px solid ${touched.title ? 'red' : "#D6D8F6"}`,
borderRadius: 10, borderRadius: 10,
}, },
}} }}
onChange={(val) => { setListData({ title: val.target.value })}}
/> />
</Box> </Box>
<Box pos={"fixed"} bottom={0} p={rem(20)} w={"100%"} style={{ <Box pos={"fixed"} bottom={0} p={rem(20)} w={"100%"} style={{
@@ -154,7 +175,13 @@ function CreateBanner() {
size='lg' size='lg'
color='white' color='white'
bg={tema.get().utama} radius={30} fullWidth bg={tema.get().utama} radius={30} fullWidth
onClick={ () => { setModal(true)}} onClick={() => {
if (touched.title || touched.image) {
toast.error("Mohon Isi Semua Data")
} else {
setModal(true)
}
}}
>Simpan</Button> >Simpan</Button>
</Box> </Box>
@@ -172,7 +199,7 @@ function CreateBanner() {
setModal(false); setModal(false);
} }
}} }}
/> />
</Box> </Box>
); );

View File

@@ -2,22 +2,101 @@
import { LayoutNavbarNew, TEMA, WARNA } from '@/module/_global'; import { LayoutNavbarNew, TEMA, WARNA } from '@/module/_global';
import LayoutModal from '@/module/_global/layout/layout_modal'; import LayoutModal from '@/module/_global/layout/layout_modal';
import { useHookstate } from '@hookstate/core'; import { useHookstate } from '@hookstate/core';
import { Box, Button, Group, Paper, rem, Text, TextInput } from '@mantine/core'; import { Box, Button, Image, Paper, rem, TextInput } from '@mantine/core';
import { Dropzone, DropzoneProps, IMAGE_MIME_TYPE } from '@mantine/dropzone'; import { Dropzone } from '@mantine/dropzone';
import { IconPhoto, IconUpload, IconX } from '@tabler/icons-react'; import { useShallowEffect } from '@mantine/hooks';
import _ from 'lodash';
import { useParams, useRouter } from 'next/navigation'; import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react'; import { useRef, useState } from 'react';
import toast from 'react-hot-toast';
import { funEditBanner, funGetOneBanner } from '../lib/api_banner';
import { IEditDataBanner } from '../lib/type_banner';
function EditBanner(props: Partial<DropzoneProps> ) { export default function EditBanner() {
const router = useRouter()
const param = useParams<{ id: string }>()
const tema = useHookstate(TEMA) const tema = useHookstate(TEMA)
const [title, setTitle] = useState("") const [isModal, setModal] = useState(false)
const [openModal, setOpenModal] = useState(false) const [data, setData] = useState<IEditDataBanner>({
id: "",
title: "",
extension: "",
image: "",
});
const openRef = useRef<() => void>(null)
const [img, setIMG] = useState<any | null>()
const [imgForm, setImgForm] = useState<any>()
const [loading, setLoading] = useState(false)
const [touched, setTouched] = useState({ const [touched, setTouched] = useState({
title: false, title: false,
}); image: false
})
function onValidation(kategori: string, val: any) {
if (kategori == 'title') {
setData({ ...data, title: val })
if (val === "") {
setTouched({ ...touched, title: true })
} else {
setTouched({ ...touched, title: false })
}
} else if (kategori == 'image') {
if (imgForm) {
setTouched({ ...touched, image: false })
} else {
setTouched({ ...touched, image: true })
}
}
}
async function getOneData() {
try {
const res = await funGetOneBanner(param.id)
console.log(res)
setData(res.data)
setIMG(`https://wibu-storage.wibudev.com/api/files/${res.data.image}`)
} catch (error) {
console.error(error)
}
}
async function onSubmit(val: boolean) {
try {
setLoading(true)
const fd = new FormData()
fd.append("file", imgForm)
fd.append("data", JSON.stringify(
{
id: data.id,
title: data.title,
image: data.image,
extension: data.extension
}
))
const res = await funEditBanner(param.id, fd)
if (res.success) {
toast.success(res.message)
router.push('/banner')
} else {
toast.error(res.message)
}
} catch (error) {
toast.error("Error");
} finally {
setLoading(false)
setModal(false)
}
}
useShallowEffect(() => {
getOneData()
}, [])
return ( return (
<Box> <Box>
<LayoutNavbarNew back='/banner' title='Edit Banner' menu={<></>} /> <LayoutNavbarNew back='/banner' title='Edit Banner' menu={<></>} />
@@ -25,41 +104,24 @@ function EditBanner(props: Partial<DropzoneProps> ) {
<Box> <Box>
<Paper withBorder radius={20}> <Paper withBorder radius={20}>
<Dropzone <Dropzone
onDrop={(files) => console.log('accepted files', files)} openRef={openRef}
onReject={(files) => console.log('rejected files', files)} onDrop={async (files) => {
maxSize={5 * 1024 ** 2} if (!files || _.isEmpty(files))
accept={IMAGE_MIME_TYPE} return toast.error("Tidak Ada Gambar Yang Dipilih")
{...props} setImgForm(files[0])
const buffer = URL.createObjectURL(new Blob([new Uint8Array(await files[0].arrayBuffer())]))
setIMG(buffer)
onValidation('image', files[0])
}}
activateOnClick={false}
maxSize={1 * 1024 ** 2}
accept={['image/png', 'image/jpeg', 'image/heic']}
onReject={(files) => {
return toast.error('File yang diizinkan: .png, .jpg, dan .heic dengan ukuran maksimal 1 MB')
}}
onClick={() => openRef.current?.()}
> >
<Group justify="center" gap="xl" mih={220} style={{ pointerEvents: 'none' }}> <Image radius={"md"} src={img} alt="" />
<Dropzone.Accept>
<IconUpload
style={{ width: rem(52), height: rem(52), color: 'var(--mantine-color-blue-6)' }}
stroke={1.5}
/>
</Dropzone.Accept>
<Dropzone.Reject>
<IconX
style={{ width: rem(52), height: rem(52), color: 'var(--mantine-color-red-6)' }}
stroke={1.5}
/>
</Dropzone.Reject>
<Dropzone.Idle>
<IconPhoto
style={{ width: rem(52), height: rem(52), color: 'var(--mantine-color-dimmed)' }}
stroke={1.5}
/>
</Dropzone.Idle>
<Box>
<Text size="xl" inline>
Upload File
</Text>
<Text size="sm" c="dimmed" inline mt={7}>
File Tidak Boleh Melebihi 500mb
</Text>
</Box>
</Group>
</Dropzone> </Dropzone>
</Paper> </Paper>
<Box> <Box>
@@ -67,20 +129,19 @@ function EditBanner(props: Partial<DropzoneProps> ) {
mt={10} mt={10}
label="Judul Banner" label="Judul Banner"
placeholder='Banner' placeholder='Banner'
value={data.title}
onChange={(e) => {
setData({ ...data, title: e.target.value })
onValidation('title', e.target.value)
}}
styles={{ styles={{
input: { input: {
border: `1px solid ${"#D6D8F6"}`, border: `1px solid ${touched.title ? 'red' : "#D6D8F6"}`,
borderRadius: 10, borderRadius: 10,
}, },
}} }}
required required
size='md' size='md'
value={title}
onChange={(e) => {
setTitle(e.currentTarget.value)
setTouched({...touched, title: false})
}}
/> />
</Box> </Box>
<Box pos={"fixed"} bottom={0} p={rem(20)} w={"100%"} style={{ <Box pos={"fixed"} bottom={0} p={rem(20)} w={"100%"} style={{
@@ -91,18 +152,31 @@ function EditBanner(props: Partial<DropzoneProps> ) {
<Button <Button
size='lg' size='lg'
color='white' color='white'
bg={WARNA.biruTua} bg={tema.get().utama}
radius={30} radius={30}
fullWidth fullWidth
> onClick={() => {
if (touched.title || touched.image) {
toast.error('Mohon Isi Semua Data')
} else {
setModal(true)
}
}}
>
Simpan Simpan
</Button> </Button>
<LayoutModal opened={openModal} onClose={() => setOpenModal(false)} <LayoutModal
loading={loading}
opened={isModal}
onClose={() => setModal(false)}
description="Apakah Anda yakin ingin mengedit banner ini?" description="Apakah Anda yakin ingin mengedit banner ini?"
onYes={(val) => { onYes={(val) => {
if (val) {
setOpenModal(false) onSubmit(val)
} else {
setModal(false)
}
}} }}
/> />
</Box> </Box>
@@ -112,4 +186,3 @@ function EditBanner(props: Partial<DropzoneProps> ) {
); );
} }
export default EditBanner;

View File

@@ -13,7 +13,7 @@ import { funDeleteBanner, funGetAllBanner, funGetOneBanner } from '../lib/api_ba
import { HiMagnifyingGlass } from 'react-icons/hi2'; import { HiMagnifyingGlass } from 'react-icons/hi2';
function ListBanner() { function ListBanner() {
const [isList, setIsList] = useState (false) const [isList, setIsList] = useState(false)
const tema = useHookstate(TEMA) const tema = useHookstate(TEMA)
const router = useRouter(); const router = useRouter();
const param = useParams<{ id: string }>() const param = useParams<{ id: string }>()
@@ -28,19 +28,18 @@ function ListBanner() {
const [isPage, setPage] = useState(1) const [isPage, setPage] = useState(1)
const [searchQuerry, setSearchQuerry] = useState('') const [searchQuerry, setSearchQuerry] = useState('')
// const { value: containerRef } = useHookstate(currentScroll); // const { value: containerRef } = useHookstate(currentScroll);
const handleList = () => { const handleList = () => {
setIsList(!isList) setIsList(!isList)
} }
const fetchData = async (loading: boolean) => { const fetchData = async (loading: boolean) => {
console.log('jallan')
try { try {
if (loading) if (loading)
setLoading(true) setLoading(true)
const response = await funGetAllBanner('?search=' + searchQuerry) const response = await funGetAllBanner('?search=' + searchQuerry)
if (response.success) { if (response.success) {
setData(response.data) setData(response.data.map((banner: { image: any; }) => ({ ...banner, image: banner.image })));
} else { } else {
toast.error(response.message) toast.error(response.message)
} }
@@ -57,8 +56,8 @@ function ListBanner() {
setSearchQuerry(search) setSearchQuerry(search)
setPage(1) setPage(1)
} }
useShallowEffect(() => { useShallowEffect(() => {
fetchData(true) fetchData(true)
}, [searchQuerry]) }, [searchQuerry])
@@ -68,28 +67,28 @@ function ListBanner() {
}, [isPage]) }, [isPage])
async function onDelete() { async function onDelete(id: string) {
try { try {
const res = await funDeleteBanner(idData); const res = await funDeleteBanner(id);
if (res.success) { if (res.success) {
toast.success(res.message) toast.success(res.message)
getOneData() setData(isData.filter((banner) => banner.id !== id));
setIdData("") setIdData("")
setIdDataStorage("") setIdDataStorage("")
setOpenDrawer(false) setOpenDrawer(false)
} else { } else {
toast.error(res.message); toast.error(res.message);
}
} catch (error) {
console.error(error);
toast.error("Gagal menghapus banner, coba lagi nanti");
} }
} catch (error) {
console.error(error);
toast.error("Gagal menghapus banner, coba lagi nanti");
} }
}
return ( return (
<Box pt={2}> <Box pt={2}>
<Box p={20}> <Box p={20}>
@@ -99,23 +98,28 @@ function ListBanner() {
color: tema.get().utama, color: tema.get().utama,
borderRadius: '#A3A3A3', borderRadius: '#A3A3A3',
borderColor: '#A3A3A3', borderColor: '#A3A3A3',
}, },
}} }}
size='md' size='md'
radius={30} radius={30}
leftSection={<HiMagnifyingGlass size={20} />} leftSection={<HiMagnifyingGlass size={20} />}
placeholder='pencarian' placeholder='pencarian'
value={searchQuerry} value={searchQuerry}
onChange={(val) => { searchBanner(val.target.value)}} onChange={(val) => { searchBanner(val.target.value) }}
/> />
</Box> </Box>
<Box p={20}> <Box p={20}>
<Anchor underline='never'> <Anchor underline='never'>
<Stack align='center' justify='center'> <Stack align='center' justify='center'>
{isData.map((_, index) => ( {isData.map((v, index) => (
<Paper radius={'md'} withBorder key={index} onClick={() => { setOpenDrawer(true) } <Paper radius={'md'} withBorder key={index} onClick={() => {
setIdData(v.id);
setIdDataStorage(v.image);
setExtension(v.extension);
setOpenDrawer(true)
}
} }
style={{ style={{
width: '100%', width: '100%',
@@ -127,11 +131,16 @@ function ListBanner() {
}}> }}>
<Group mt={"15"}> <Group mt={"15"}>
<ActionIcon variant='transparent' w={"100"}> <ActionIcon variant='transparent' w={"100"}>
<Image radius={"xs"} src={"/assets/img/banner/Banner-1.png"} alt='' w={76} h={38.9} /> <Image
radius={"xs"}
src={`https://wibu-storage.wibudev.com/api/files/${v.image}`}
alt=''
w={76}
h={38.9}
/>
</ActionIcon> </ActionIcon>
<Flex direction={"column"}> <Flex direction={"column"}>
<Text c={"dark"} >Banner {index + 1}</Text> <Text c={"dark"} fz={"h4"}>{v.title}</Text>
<Text fz={"h6"} fw={"inherit"} c={"dark"}>Banner</Text>
</Flex> </Flex>
</Group> </Group>
</Paper> </Paper>
@@ -141,6 +150,7 @@ function ListBanner() {
</Anchor> </Anchor>
</Box> </Box>
<LayoutDrawer opened={openDrawer} title={'Menu'} onClose={() => setOpenDrawer(false)}> <LayoutDrawer opened={openDrawer} title={'Menu'} onClose={() => setOpenDrawer(false)}>
<Box> <Box>
<Stack pt={10}> <Stack pt={10}>
@@ -151,14 +161,15 @@ function ListBanner() {
alignItems: "flex-start" alignItems: "flex-start"
}} }}
> >
<Flex onClick={() => router.push("/banner/edit/[id]")} direction="column" align="center" justify="center" pb={20}> <Flex onClick={() => router.push(`/banner/edit/${idData}`)} direction="column" align="center" justify="center" pb={20}>
<Box> <Box>
<FaPencil size={30} color={WARNA.biruTua} /> <FaPencil size={30} color={WARNA.biruTua} />
</Box> </Box>
<Box> <Box>
<Text c={tema.get().utama} fz={{ base: 'sm', md: 'md'}}>Edit</Text> <Text c={tema.get().utama} fz={{ base: 'sm', md: 'md' }}>Edit</Text>
</Box> </Box>
</Flex> </Flex>
<Flex onClick={() => { setOpenModalView(true) }} direction={"column"} align={"center"} justify={"center"}> <Flex onClick={() => { setOpenModalView(true) }} direction={"column"} align={"center"} justify={"center"}>
<Box> <Box>
@@ -181,50 +192,46 @@ function ListBanner() {
</Stack> </Stack>
</Box> </Box>
</LayoutDrawer> </LayoutDrawer>
<LayoutModal opened={isOpenModal} onClose={() => setOpenModal(false)}
<LayoutModal
opened={isOpenModal}
onClose={() => setOpenModal(false)}
description='Apakah Anda yakin ingin menghapus banner?' description='Apakah Anda yakin ingin menghapus banner?'
onYes={(val) => { onYes={(val) => {
if (val) { if (val) {
onDelete() onDelete(idData)
} }
setOpenModal(false) setOpenModal(false)
}} /> }} />
<LayoutModalViewFile opened={isOpenModalView} onClose={() => setOpenModalView(false)} file={idDataStorage} extension={isExtension} fitur='task' /> <LayoutModalViewFile opened={isOpenModalView} onClose={() => setOpenModalView(false)} file={idDataStorage} extension={isExtension} fitur="image" />
</Box> </Box>
); );
} }
export default ListBanner; export default ListBanner;
function funGetBanner(arg0: string) {
throw new Error('Function not implemented.');
}
function getOneData() {
throw new Error('Function not implemented.');
}
// useEffect(() => {
// const handleScroll = async () => {
// if (containerRef && containerRef.current) {
// const scrollTop = containerRef.current.scrollTop;
// const containerHeight = containerRef.current.clientHeight;
// const scrollHeight = containerRef.current.scrollHeight;
// if (scrollTop + containerHeight + 1 >= scrollHeight) {
// setPage(isPage + 1)
// }
// }
// };
// const container = containerRef?.current; // useEffect(() => {
// container?.addEventListener("scroll", handleScroll); // const handleScroll = async () => {
// if (containerRef && containerRef.current) {
// const scrollTop = containerRef.current.scrollTop;
// const containerHeight = containerRef.current.clientHeight;
// const scrollHeight = containerRef.current.scrollHeight;
// if (scrollTop + containerHeight + 1 >= scrollHeight) {
// setPage(isPage + 1)
// }
// }
// };
// const container = containerRef?.current;
// container?.addEventListener("scroll", handleScroll);
// return () => {
// container?.removeEventListener("scroll", handleScroll);
// };
// }, [containerRef, isPage]);
// return () => {
// container?.removeEventListener("scroll", handleScroll);
// };
// }, [containerRef, isPage]);