upd: document

Deskripsi:
- rename

No Issues
This commit is contained in:
amel
2024-08-21 16:35:56 +08:00
parent a36fe88998
commit b7d67986c6
5 changed files with 240 additions and 35 deletions

View File

@@ -107,6 +107,22 @@ export async function POST(request: Request) {
} }
} }
const nameFile = await prisma.divisionDocumentFolderFile.count({
where: {
name,
idDivision,
path,
extension: "folder",
category: "FOLDER",
isActive: true
}
})
if (nameFile > 0) {
return NextResponse.json({ success: false, message: "Gagal membuat folder baru, folder sudah ada" }, { status: 400 });
}
const data = await prisma.divisionDocumentFolderFile.create({ const data = await prisma.divisionDocumentFolderFile.create({
data: { data: {
name, name,
@@ -123,4 +139,60 @@ export async function POST(request: Request) {
console.log(error); console.log(error);
return NextResponse.json({ success: false, message: "Gagal membuat folder, coba lagi nanti", reason: (error as Error).message, }, { status: 500 }); return NextResponse.json({ success: false, message: "Gagal membuat folder, coba lagi nanti", reason: (error as Error).message, }, { status: 500 });
} }
};
export async function PUT(request: Request) {
try {
const user = await funGetUserByCookies()
if (user.id == undefined) {
return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
}
const { name, id, path, idDivision, extension } = (await request.json());
const cekFile = await prisma.divisionDocumentFolderFile.count({
where: {
id: id,
isActive: true
}
})
if (cekFile == 0) {
return NextResponse.json({ success: false, message: "Gagal mendapatkan item, data tidak ditemukan" }, { status: 404 });
}
const nameFile = await prisma.divisionDocumentFolderFile.count({
where: {
name,
idDivision,
path,
extension,
isActive: true,
NOT: {
id: id
},
}
})
if (nameFile > 0) {
return NextResponse.json({ success: false, message: "Gagal mengubah nama item, item sudah ada" }, { status: 400 });
}
const update = await prisma.divisionDocumentFolderFile.update({
where: {
id: id
},
data: {
name,
}
})
return NextResponse.json({ success: true, message: "Berhasil mengubah nama item" }, { status: 200 });
} catch (error) {
console.log(error);
return NextResponse.json({ success: false, message: "Gagal mengubah nama item, coba lagi nanti", reason: (error as Error).message, }, { status: 500 });
}
}; };

View File

@@ -1,4 +1,4 @@
import { IFormFolder } from "./type_document"; import { IFormEditItem, IFormFolder } from "./type_document";
export const funGetAllDocument = async (path?: string) => { export const funGetAllDocument = async (path?: string) => {
const response = await fetch(`/api/document${(path) ? path : ''}`, { next: { tags: ['document'] } }); const response = await fetch(`/api/document${(path) ? path : ''}`, { next: { tags: ['document'] } });
@@ -18,4 +18,18 @@ export const funCreateFolder = async (data: IFormFolder) => {
body: JSON.stringify(data), body: JSON.stringify(data),
}); });
return await response.json().catch(() => null); return await response.json().catch(() => null);
};
export const funRenameDocument = async (data: IFormEditItem) => {
if (data.name == "")
return { success: false, message: 'Nama item tidak boleh kosong' }
const response = await fetch("/api/document", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
return await response.json().catch(() => null);
}; };

View File

@@ -14,4 +14,13 @@ export interface IFormFolder {
name: string; name: string;
path: string; path: string;
idDivision: string idDivision: string
}
export interface IFormEditItem {
id: string
name: string
path: string
idDivision: string
extension: string
} }

View File

@@ -29,17 +29,17 @@ export default function DrawerMenuDocumentDivision() {
async function onCreateFolder() { async function onCreateFolder() {
try { try {
const res = await funCreateFolder(bodyFolder) const res = await funCreateFolder(bodyFolder)
if (res.success) { if (!res.success) {
refresh.set(true) toast.error(res.message)
setOpenModal(false)
setOpenDrawerDocument(false)
} else {
toast.error(res.message);
} }
} catch (error) { } catch (error) {
console.error(error); console.error(error);
toast.error("Gagal membuat folder baru, coba lagi nanti"); toast.error("Gagal membuat folder baru, coba lagi nanti");
} }
refresh.set(true)
setOpenModal(false)
setOpenDrawerDocument(false)
} }
return ( return (

View File

@@ -4,11 +4,11 @@ import { ActionIcon, Box, Button, Checkbox, Divider, Flex, Grid, Group, Modal, S
import React, { useState } from 'react'; import React, { useState } from 'react';
import { HiMenu } from 'react-icons/hi'; import { HiMenu } from 'react-icons/hi';
import { FcDocument, FcFolder, FcImageFile } from 'react-icons/fc'; import { FcDocument, FcFolder, FcImageFile } from 'react-icons/fc';
import { BsDownload } from 'react-icons/bs'; import { BsDownload, BsListCheck } from 'react-icons/bs';
import { AiOutlineDelete } from 'react-icons/ai'; import { AiOutlineDelete } from 'react-icons/ai';
import { CgRename } from "react-icons/cg"; import { CgRename } from "react-icons/cg";
import { LuShare2 } from 'react-icons/lu'; import { LuShare2 } from 'react-icons/lu';
import { MdOutlineMoreHoriz } from 'react-icons/md'; import { MdClose, MdOutlineMoreHoriz } from 'react-icons/md';
import LayoutModal from '@/module/_global/layout/layout_modal'; import LayoutModal from '@/module/_global/layout/layout_modal';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import { useParams, useRouter, useSearchParams } from 'next/navigation'; import { useParams, useRouter, useSearchParams } from 'next/navigation';
@@ -16,13 +16,13 @@ import DrawerMenuDocumentDivision from './drawer_menu_document_division';
import DrawerMore from './drawer_more'; import DrawerMore from './drawer_more';
import { funGetDivisionById } from '@/module/division_new'; import { funGetDivisionById } from '@/module/division_new';
import { useShallowEffect } from '@mantine/hooks'; import { useShallowEffect } from '@mantine/hooks';
import { funGetAllDocument } from '../lib/api_document'; import { funGetAllDocument, funRenameDocument } from '../lib/api_document';
import { IDataDocument } from '../lib/type_document'; import { IDataDocument } from '../lib/type_document';
import { useHookstate } from '@hookstate/core'; import { useHookstate } from '@hookstate/core';
import { globalRefreshDocument } from '../lib/val_document'; import { globalRefreshDocument } from '../lib/val_document';
import { RiListCheck } from 'react-icons/ri';
export default function NavbarDocumentDivision() { export default function NavbarDocumentDivision() {
const [isChecked, setIsChecked] = useState(false);
const router = useRouter() const router = useRouter()
const param = useParams<{ id: string }>() const param = useParams<{ id: string }>()
const [name, setName] = useState('') const [name, setName] = useState('')
@@ -35,11 +35,70 @@ export default function NavbarDocumentDivision() {
const path = searchParams.get('path') const path = searchParams.get('path')
const [dataDocument, setDataDocument] = useState<IDataDocument[]>([]) const [dataDocument, setDataDocument] = useState<IDataDocument[]>([])
const refresh = useHookstate(globalRefreshDocument) const refresh = useHookstate(globalRefreshDocument)
const [selectedFiles, setSelectedFiles] = useState<any>([])
const [selectAll, setSelectAll] = useState(false)
const [dariSelectAll, setDariSelectAll] = useState(false)
const [bodyRename, setBodyRename] = useState({
id: '',
name: '',
path: '',
idDivision: param.id,
extension: ''
})
const handleCheckboxChange = (index: number) => {
setDariSelectAll(false)
if (selectedFiles.some((i: any) => i.id == dataDocument[index].id)) {
setSelectedFiles(selectedFiles.filter((i: any) => i.id != dataDocument[index].id))
} else {
setSelectedFiles([
...selectedFiles,
{
id: dataDocument[index].id,
name: dataDocument[index].name,
path: dataDocument[index].path,
extension: dataDocument[index].extension
}
])
}
const handleCheckboxChange = () => {
setIsChecked(!isChecked);
}; };
function cek() {
if (selectedFiles.length == dataDocument.length) {
setSelectAll(true)
} else {
setSelectAll(false)
}
}
const handleSelectAll = () => {
if (!selectAll) {
setDariSelectAll(false)
for (let index = 0; index < dataDocument.length; index++) {
if (!selectedFiles.some((i: any) => i.id == dataDocument[index].id)) {
const newArr = {
id: dataDocument[index].id,
name: dataDocument[index].name,
path: dataDocument[index].path,
extension: dataDocument[index].extension
}
setSelectedFiles((selectedFiles: any) => [...selectedFiles, newArr])
}
}
} else {
setDariSelectAll(true)
setSelectedFiles([]);
}
};
const handleBatal = () => {
setSelectedFiles([])
setSelectAll(false)
setDariSelectAll(false)
}
function onTrue(val: boolean) { function onTrue(val: boolean) {
if (val) { if (val) {
@@ -47,10 +106,22 @@ export default function NavbarDocumentDivision() {
} }
setIsDelete(false) setIsDelete(false)
} }
function onEdit(val: boolean) { async function onRenameSubmit() {
if (val) { try {
toast.success("Sukses! Edit Data"); const res = await funRenameDocument(bodyRename)
if (res.success) {
getOneData()
} else {
toast.error(res.message)
}
} catch (error) {
console.log(error)
toast.error("Gagal mengganti nama item, coba lagi nanti")
} }
setSelectedFiles([])
setDariSelectAll(false)
setRename(false) setRename(false)
} }
@@ -81,21 +152,48 @@ export default function NavbarDocumentDivision() {
setOpen(false) setOpen(false)
} }
useShallowEffect(() => {
cek()
}, [selectedFiles])
useShallowEffect(() => { useShallowEffect(() => {
getOneData() getOneData()
resetRefresh() resetRefresh()
}, [param.id, path, refresh.get()]) }, [param.id, path, refresh.get()])
function onChooseRename() {
setBodyRename({
...bodyRename,
id: selectedFiles[0].id,
name: selectedFiles[0].name,
path: selectedFiles[0].path,
extension: selectedFiles[0].extension,
})
setRename(true)
}
return ( return (
<Box> <Box>
{isChecked && ( {(selectedFiles.length > 0 || dariSelectAll) && (
<> <>
<Box h={90} w={{ base: "100%", md: "38.2%" }} bg={WARNA.biruTua} pos={'fixed'} top={0} style={{ <Box h={90} w={{ base: "100%", md: "38.2%" }} bg={WARNA.biruTua} pos={'fixed'} top={0} style={{
zIndex: 999, zIndex: 999,
}}> }}>
<Flex justify={'space-between'} ml={30} mr={30} align={'center'} h={"100%"}> <Flex justify={'space-between'} ml={30} mr={30} align={'center'} h={"100%"}>
<Text c={'white'}>Dibatalkan</Text> <ActionIcon variant="transparent" aria-label="Settings" onClick={() => handleBatal()}>
<Text c={'white'}>Pilih Semua</Text> <MdClose size={25} color='white' />
</ActionIcon>
<Text fz={15} c={'white'}>{(selectedFiles.length > 0) ? selectedFiles.length + " item terpilih" : "Pilih Item"}</Text>
<ActionIcon variant="transparent" aria-label="Settings" onClick={() => handleSelectAll()}>
{
(selectAll) ?
<RiListCheck size={25} color='white' /> :
<BsListCheck size={25} color='white' />
}
</ActionIcon>
</Flex> </Flex>
</Box> </Box>
<Box h={70} w={{ base: "100%", md: "38.2%" }} bg={WARNA.biruTua} pos={'fixed'} bottom={0} style={{ <Box h={70} w={{ base: "100%", md: "38.2%" }} bg={WARNA.biruTua} pos={'fixed'} bottom={0} style={{
@@ -104,24 +202,28 @@ export default function NavbarDocumentDivision() {
<Flex justify={"center"} align={"center"} h={"100%"} w={"100%"}> <Flex justify={"center"} align={"center"} h={"100%"} w={"100%"}>
<SimpleGrid cols={{ base: 5, sm: 5, lg: 5 }}> <SimpleGrid cols={{ base: 5, sm: 5, lg: 5 }}>
<Flex justify={'center'} align={'center'} direction={'column'}> <Flex justify={'center'} align={'center'} direction={'column'}>
<BsDownload size={20} color='white' /> <BsDownload size={20} color={(selectedFiles.length > 0) ? 'white' : 'grey'} />
<Text fz={12} c={'white'}>Unduh</Text> <Text fz={12} c={(selectedFiles.length > 0) ? 'white' : 'grey'}>Unduh</Text>
</Flex> </Flex>
<Flex onClick={() => setIsDelete(true)} justify={'center'} align={'center'} direction={'column'}> <Flex onClick={() => setIsDelete(true)} justify={'center'} align={'center'} direction={'column'}>
<AiOutlineDelete size={20} color='white' /> <AiOutlineDelete size={20} color={(selectedFiles.length > 0) ? 'white' : 'grey'} />
<Text fz={12} c={'white'}>Hapus</Text> <Text fz={12} c={(selectedFiles.length > 0) ? 'white' : 'grey'}>Hapus</Text>
</Flex> </Flex>
<Flex onClick={() => setRename(true)} justify={'center'} align={'center'} direction={'column'}> <Flex onClick={() => {
<CgRename size={20} color='white' /> if (selectedFiles.length == 1) {
<Text fz={12} c={'white'}>Ganti Name</Text> onChooseRename()
}
}} justify={'center'} align={'center'} direction={'column'}>
<CgRename size={20} color={(selectedFiles.length == 1) ? 'white' : 'grey'} />
<Text fz={12} c={(selectedFiles.length == 1) ? 'white' : 'grey'}>Ganti Nama</Text>
</Flex> </Flex>
<Flex onClick={() => setShare(true)} justify={'center'} align={'center'} direction={'column'}> <Flex onClick={() => setShare(true)} justify={'center'} align={'center'} direction={'column'}>
<LuShare2 size={20} color='white' /> <LuShare2 size={20} color={(selectedFiles.length > 0) ? 'white' : 'grey'} />
<Text fz={12} c={'white'}>Bagikan</Text> <Text fz={12} c={(selectedFiles.length > 0) ? 'white' : 'grey'}>Bagikan</Text>
</Flex> </Flex>
<Flex onClick={() => setMore(true)} justify={'center'} align={'center'} direction={'column'}> <Flex onClick={() => setMore(true)} justify={'center'} align={'center'} direction={'column'}>
<MdOutlineMoreHoriz size={20} color='white' /> <MdOutlineMoreHoriz size={20} color={(selectedFiles.length > 0) ? 'white' : 'grey'} />
<Text fz={12} c={'white'}>Lainnya</Text> <Text fz={12} c={(selectedFiles.length > 0) ? 'white' : 'grey'}>Lainnya</Text>
</Flex> </Flex>
</SimpleGrid> </SimpleGrid>
</Flex> </Flex>
@@ -139,6 +241,7 @@ export default function NavbarDocumentDivision() {
<Box> <Box>
<Box p={20} pb={60}> <Box p={20} pb={60}>
{dataDocument.map((v, i) => { {dataDocument.map((v, i) => {
const isSelected = selectedFiles.some((i: any) => i?.id == v.id);
return ( return (
<Box key={i}> <Box key={i}>
<Box mt={10} mb={10}> <Box mt={10} mb={10}>
@@ -171,8 +274,8 @@ export default function NavbarDocumentDivision() {
color="teal" color="teal"
radius="lg" radius="lg"
size="md" size="md"
checked={isChecked} checked={isSelected}
onChange={handleCheckboxChange} onChange={() => handleCheckboxChange(i)}
/> />
</Group> </Group>
</Grid.Col> </Grid.Col>
@@ -195,6 +298,8 @@ export default function NavbarDocumentDivision() {
<LayoutModal opened={isDelete} onClose={() => setIsDelete(false)} <LayoutModal opened={isDelete} onClose={() => setIsDelete(false)}
description="Apakah Anda yakin ingin menghapus data?" description="Apakah Anda yakin ingin menghapus data?"
onYes={(val) => { onTrue(val) }} /> onYes={(val) => { onTrue(val) }} />
<Modal styles={{ <Modal styles={{
body: { body: {
borderRadius: 20 borderRadius: 20
@@ -205,7 +310,7 @@ export default function NavbarDocumentDivision() {
} }
}} opened={rename} onClose={() => setRename(false)} centered withCloseButton={false}> }} opened={rename} onClose={() => setRename(false)} centered withCloseButton={false}>
<Box p={20}> <Box p={20}>
<Text ta={"center"} fw={"bold"}>Edit Folder</Text> <Text ta={"center"} fw={"bold"}>Ganti Nama Item</Text>
<Box mt={20} mb={20}> <Box mt={20} mb={20}>
<TextInput <TextInput
styles={{ styles={{
@@ -217,7 +322,9 @@ export default function NavbarDocumentDivision() {
}} }}
size="md" size="md"
radius={10} radius={10}
placeholder="Buat Folder Baru" placeholder="Nama item"
value={bodyRename.name}
onChange={(e) => setBodyRename({ ...bodyRename, name: e.target.value })}
/> />
</Box> </Box>
<Grid mt={40}> <Grid mt={40}>
@@ -225,11 +332,14 @@ export default function NavbarDocumentDivision() {
<Button variant="subtle" fullWidth color='#969494' onClick={() => setRename(false)}>Batalkan</Button> <Button variant="subtle" fullWidth color='#969494' onClick={() => setRename(false)}>Batalkan</Button>
</Grid.Col> </Grid.Col>
<Grid.Col span={6}> <Grid.Col span={6}>
<Button variant="subtle" fullWidth color={WARNA.biruTua} onClick={(val) => onEdit(true)}>Edit</Button> <Button variant="subtle" fullWidth color={WARNA.biruTua} onClick={(val) => onRenameSubmit()}>Simpan</Button>
</Grid.Col> </Grid.Col>
</Grid> </Grid>
</Box> </Box>
</Modal> </Modal>
<LayoutDrawer opened={share} title={'Bagikan'} onClose={() => setShare(false)} size='lg'> <LayoutDrawer opened={share} title={'Bagikan'} onClose={() => setShare(false)} size='lg'>
<Box pt={10}> <Box pt={10}>
<Select <Select