fix voting admin:

deskripsi:
- fix voting table review
This commit is contained in:
2025-02-24 16:55:34 +08:00
parent 8f80419eb2
commit f2d3930bd1
6 changed files with 771 additions and 724 deletions

View File

@@ -4,152 +4,215 @@ import _ from "lodash";
import moment from "moment"; import moment from "moment";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
export async function GET(request: Request, export async function GET(
{ params }: { params: { name: string } } request: Request,
{ params }: { params: { name: string } }
) { ) {
const { name } = params;
const { searchParams } = new URL(request.url);
const search = searchParams.get("search");
const page = searchParams.get("page");
const takeData = 2;
const skipData = Number(page) * takeData - takeData;
const { name } = params; try {
const { searchParams } = new URL(request.url); let fixData;
const search = searchParams.get("search"); const fixStatus = _.startCase(name);
const page = searchParams.get("page");
const takeData = 10;
const skipData = Number(page) * takeData - takeData;
try { if (!page) {
let fixData; fixData = await prisma.voting.findMany({
const fixStatus = _.startCase(name); orderBy: {
createdAt: "desc",
},
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
isArsip: false,
},
include: {
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
Voting_Kontributor: true,
Voting_DaftarNamaVote: true,
},
});
} else {
if (fixStatus === "Publish") {
const getAllData = await prisma.voting.findMany({
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
isArsip: false,
akhirVote: {
gte: new Date(),
},
},
});
if (!page) { for (let i of getAllData) {
fixData = await prisma.voting.findMany({ if (moment(i.akhirVote).diff(moment(), "minutes") < 0) {
orderBy: { await prisma.event.update({
createdAt: "desc", where: {
}, id: i.id,
where: { },
Voting_Status: { data: {
name: fixStatus, isArsip: true,
}, },
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
isArsip: false,
},
include: {
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
Voting_Kontributor: true,
Voting_DaftarNamaVote: true,
},
}); });
} else { }
fixData = await prisma.voting.findMany({
take: takeData,
skip: skipData,
orderBy: {
createdAt: "desc",
},
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
isArsip: false,
},
include: {
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
Voting_Kontributor: true,
Voting_DaftarNamaVote: true,
},
});
if (fixStatus === "Publish") {
const data = await prisma.voting.findMany({
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
isArsip: false,
},
});
for (let i of data) {
if (moment(i.akhirVote).diff(moment(), "minutes") < 0) {
await prisma.event.update({
where: {
id: i.id,
},
data: {
isArsip: true,
},
});
}
}
const nCount = await prisma.voting.count({
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
},
});
fixData = {
data: data,
count: _.ceil(nCount / takeData)
}
}
} }
return NextResponse.json({ const data = await prisma.voting.findMany({
success: true, take: takeData,
message: "Success get data voting dashboard", skip: skipData,
data: fixData orderBy: {
}, createdAt: "desc",
{ status: 200 } },
) where: {
} catch (error) { Voting_Status: {
backendLogger.error("Error get data voting dashboard >>", error); name: fixStatus,
return NextResponse.json({ },
success: false, isActive: true,
message: "Error get data voting dashboard", title: {
reason: (error as Error).message contains: search ? search : "",
}, mode: "insensitive",
{ status: 500 } },
) akhirVote: {
gte: new Date(),
},
isArsip: false,
},
include: {
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
Voting_Kontributor: true,
Voting_DaftarNamaVote: true,
},
});
const nCount = await prisma.voting.count({
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
akhirVote: {
gte: new Date(),
},
isArsip: false,
},
});
fixData = {
data: data,
nPage: _.ceil(nCount / takeData),
};
} else {
const data = await prisma.voting.findMany({
take: takeData,
skip: skipData,
orderBy: {
createdAt: "desc",
},
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
isArsip: false,
},
include: {
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
},
},
},
},
Voting_Kontributor: true,
Voting_DaftarNamaVote: true,
},
});
const nCount = await prisma.voting.count({
where: {
Voting_Status: {
name: fixStatus,
},
isActive: true,
title: {
contains: search ? search : "",
mode: "insensitive",
},
isArsip: false,
},
});
fixData = {
data: data,
nPage: _.ceil(nCount / takeData),
};
}
} }
}
return NextResponse.json(
{
success: true,
message: "Success get data voting status",
data: fixData,
},
{ status: 200 }
);
} catch (error) {
backendLogger.error("Error get data voting status ", error);
return NextResponse.json(
{
success: false,
message: "Error get data voting status",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -1,13 +1,9 @@
import { AdminVote_TablePublish } from "@/app_modules/admin/vote"; import { AdminVote_TablePublish } from "@/app_modules/admin/vote";
import { AdminVote_getListTableByStatusId } from "@/app_modules/admin/vote/fun/get/get_list_table_by_status_id";
import { adminVote_funGetListPublish } from "@/app_modules/admin/vote/fun/get/status/get_list_publish";
export default async function Page() { export default async function Page() {
const dataVote = await adminVote_funGetListPublish({page: 1}); return (
<>
return ( <AdminVote_TablePublish />
<> </>
<AdminVote_TablePublish dataVote={dataVote} /> );
</> }
);
}

View File

@@ -1,12 +1,9 @@
import { AdminVote_TableReview } from "@/app_modules/admin/vote"; import { AdminVote_TableReview } from "@/app_modules/admin/vote";
import { adminVote_funGetListReview } from "@/app_modules/admin/vote/fun";
export default async function Page() { export default async function Page() {
const listVote = await adminVote_funGetListReview({ page: 1 });
return ( return (
<> <>
<AdminVote_TableReview listVote={listVote as any} /> <AdminVote_TableReview />
</> </>
); );
} }

View File

@@ -18,8 +18,12 @@ import {
TextInput, TextInput,
Title, Title,
} from "@mantine/core"; } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks"; import { useDisclosure, useShallowEffect } from "@mantine/hooks";
import { IconCircleCheckFilled, IconEyeCheck, IconSearch } from "@tabler/icons-react"; import {
IconCircleCheckFilled,
IconEyeCheck,
IconSearch,
} from "@tabler/icons-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import ComponentAdminVote_DetailHasil from "../../component/detail_hasil"; import ComponentAdminVote_DetailHasil from "../../component/detail_hasil";
@@ -28,200 +32,224 @@ import { AdminVote_getListKontributorById } from "../../fun/get/get_list_kontrib
import { adminVote_funGetListPublish } from "../../fun/get/status/get_list_publish"; import { adminVote_funGetListPublish } from "../../fun/get/status/get_list_publish";
import { ComponentAdminGlobal_TitlePage } from "@/app_modules/admin/_admin_global/_component"; import { ComponentAdminGlobal_TitlePage } from "@/app_modules/admin/_admin_global/_component";
import { MainColor } from "@/app_modules/_global/color"; import { MainColor } from "@/app_modules/_global/color";
import { AccentColor, AdminColor } from "@/app_modules/_global/color/color_pallet"; import {
AccentColor,
AdminColor,
} from "@/app_modules/_global/color/color_pallet";
import { clientLogger } from "@/util/clientLogger";
import { apiGetAdminVotingByStatus } from "../../lib/api_fetch_admin_voting";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import _ from "lodash";
import ComponentAdminGlobal_IsEmptyData from "@/app_modules/admin/_admin_global/is_empty_data";
export default function AdminVote_TablePublish({ export default function AdminVote_TablePublish() {
dataVote,
}: {
dataVote: any;
}) {
return ( return (
<> <>
<Stack> <Stack>
<ComponentAdminGlobal_HeaderTamplate name="Voting" /> <ComponentAdminGlobal_HeaderTamplate name="Voting" />
<TableStatus listPublish={dataVote} /> <TableStatus />
</Stack> </Stack>
</> </>
); );
} }
function TableStatus({ listPublish }: { listPublish: any }) { function TableStatus() {
const router = useRouter(); const router = useRouter();
const [opened, { open, close }] = useDisclosure(false); const [opened, { open, close }] = useDisclosure(false);
const [data, setData] = useState<MODEL_VOTING[]>(listPublish.data);
const [hasil, setHasil] = useState<any[]>(); const [hasil, setHasil] = useState<any[]>();
const [kontributor, setKontributor] = useState<any[]>(); const [kontributor, setKontributor] = useState<any[]>();
const [voteId, setVoteId] = useState(""); const [voteId, setVoteId] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [isNPage, setNPage] = useState(listPublish.nPage); const [data, setData] = useState<MODEL_VOTING[] | null>(null);
const [isNPage, setNPage] = useState(1);
const [isActivePage, setActivePage] = useState(1); const [isActivePage, setActivePage] = useState(1);
const [isSearch, setSearch] = useState(""); const [isSearch, setSearch] = useState("");
useShallowEffect(() => {
handleLoadData();
}, [isActivePage, isSearch]);
const handleLoadData = async () => {
try {
const response = await apiGetAdminVotingByStatus({
name: "Publish",
page: `${isActivePage}`,
search: isSearch,
});
if (response?.success && response?.data?.data) {
setData(response.data.data);
setNPage(response.data.nPage || 1);
} else {
console.error("Invalid data format received:", response);
setData([]);
}
} catch (error) {
clientLogger.error("Error get data table publish", error);
setData([]);
}
};
async function onSearch(s: string) { async function onSearch(s: string) {
setSearch(s); setSearch(s);
const loadData = await adminVote_funGetListPublish({
page: 1,
search: s,
});
setData(loadData.data as any);
setNPage(loadData.nPage);
} }
async function onPageClick(p: any) { async function onPageClick(p: any) {
setActivePage(p); setActivePage(p);
const loadData = await adminVote_funGetListPublish({
search: isSearch,
page: p,
});
setData(loadData.data as any);
setNPage(loadData.nPage);
} }
const TableRows = data.map((e, i) => ( const renderTableBody = () => {
<tr key={i}> if (!Array.isArray(data) || data.length === 0) {
<td> return (
<Center> <tr>
<Button <td colSpan={12}>
loading={ <Center>
e?.id === voteId ? (loading === true ? true : false) : false <Text color={"gray"}>Tidak ada data</Text>
} </Center>
radius={"xl"} </td>
color="green" </tr>
leftIcon={<IconCircleCheckFilled />} );
onClick={async () => { }
setVoteId(e?.id);
setLoading(true); return data?.map((e, i) => (
await new Promise((r) => setTimeout(r, 500)); <tr key={i}>
onList(e?.id, setHasil, setKontributor, setLoading, open); <td>
}} <Center>
> <Button
Lihat Hasil loading={
</Button> e?.id === voteId ? (loading === true ? true : false) : false
</Center> }
</td> radius={"xl"}
<td> color="green"
<Center c={AccentColor.white}>{e?.Author?.username}</Center> leftIcon={<IconCircleCheckFilled />}
</td> onClick={async () => {
<td> setVoteId(e?.id);
<Center c={AccentColor.white}>{e?.title}</Center> setLoading(true);
</td> await new Promise((r) => setTimeout(r, 500));
<td> onList(e?.id, setHasil, setKontributor, setLoading, open);
<Center> }}
<Spoiler >
hideLabel="sembunyikan" Lihat Hasil
maw={400} </Button>
maxHeight={50} </Center>
showLabel="tampilkan" </td>
> <td>
{e?.deskripsi} <Center c={AccentColor.white}>{e?.Author?.username}</Center>
</Spoiler> </td>
</Center> <td>
</td> <Center c={AccentColor.white}>{e?.title}</Center>
<th> </td>
<Stack> <td>
{e?.Voting_DaftarNamaVote.map((v) => ( <Center c={"white"}>
<Box key={v?.id}> <Spoiler
<Text c={AccentColor.white}>- {v?.value}</Text> hideLabel="sembunyikan"
</Box> maw={400}
))} maxHeight={50}
</Stack> showLabel="tampilkan"
</th> >
<td> {e?.deskripsi}
<Center c={AccentColor.white}> </Spoiler>
{e?.awalVote.toLocaleDateString("id-ID", { dateStyle: "long" })} </Center>
</Center> </td>
</td> <th>
<td> <Stack>
<Center c={AccentColor.white}> {e?.Voting_DaftarNamaVote.map((v) => (
{e?.akhirVote.toLocaleDateString("id-ID", { dateStyle: "long" })} <Box key={v?.id}>
</Center> <Text c={AccentColor.white}>- {v?.value}</Text>
</td> </Box>
</tr> ))}
)); </Stack>
</th>
<td>
<Center c={AccentColor.white}>
{new Intl.DateTimeFormat("id-ID", {
dateStyle: "long",
}).format(new Date(e?.awalVote))}
</Center>
</td>
<td>
<Center c={AccentColor.white}>
{new Intl.DateTimeFormat("id-ID", {
dateStyle: "long",
}).format(new Date(e?.akhirVote))}
</Center>
</td>
</tr>
));
};
return ( return (
<> <>
<Stack spacing={"xs"} h={"100%"}> <Stack spacing={"xs"} h={"100%"}>
{/* <pre>{JSON.stringify(listUser, null, 2)}</pre> */}
<ComponentAdminGlobal_TitlePage <ComponentAdminGlobal_TitlePage
name="Publish" name="Publish"
color={AdminColor.softBlue} color={AdminColor.softBlue}
component={ component={
<TextInput <TextInput
icon={<IconSearch size={20} />} icon={<IconSearch size={20} />}
radius={"xl"} radius={"xl"}
placeholder="Masukan judul" placeholder="Masukan judul"
onChange={(val) => {
onSearch(val.currentTarget.value);
}}
/>
}
/>
{/* <Group
position="apart"
bg={"green.4"}
p={"xs"}
style={{ borderRadius: "6px" }}
>
<Title order={4}>Publish</Title>
<TextInput
icon={<IconSearch size={20} />}
radius={"xl"}
placeholder="Masukan judul"
onChange={(val) => {
onSearch(val.currentTarget.value);
}}
/>
</Group> */}
<Paper p={"md"} bg={AdminColor.softBlue} shadow="lg" h={"80vh"}>
<ScrollArea w={"100%"} h={"90%"}>
<Table
verticalSpacing={"md"}
horizontalSpacing={"md"}
p={"md"}
w={1500}
>
<thead>
<tr>
<th>
<Center c={AccentColor.white}>Aksi</Center>
</th>
<th>
<Center c={AccentColor.white}>Username</Center>
</th>
<th>
<Center c={AccentColor.white}>Judul</Center>
</th>
<th>
<Center c={AccentColor.white}>Deskripsi</Center>
</th>
<th>
<Center c={AccentColor.white}>Pilihan</Center>
</th>
<th>
<Center c={AccentColor.white}>Mulai Vote</Center>
</th>
<th>
<Center c={AccentColor.white}>Selesai Vote</Center>
</th>
</tr>
</thead>
<tbody>{TableRows}</tbody>
</Table>
</ScrollArea>
<Center mt={"xl"}>
<Pagination
value={isActivePage}
total={isNPage}
onChange={(val) => { onChange={(val) => {
onPageClick(val); onSearch(val.currentTarget.value);
}} }}
/> />
</Center> }
</Paper> />
{!data ? (
<CustomSkeleton height={"80vh"} width="100%" />
) : _.isEmpty(data) ? (
<ComponentAdminGlobal_IsEmptyData />
) : (
<Paper p={"md"} bg={AdminColor.softBlue} shadow="lg" h={"80vh"}>
<ScrollArea w={"100%"} h={"90%"}>
<Table
verticalSpacing={"md"}
horizontalSpacing={"md"}
p={"md"}
w={1500}
>
<thead>
<tr>
<th>
<Center c={AccentColor.white}>Aksi</Center>
</th>
<th>
<Center c={AccentColor.white}>Username</Center>
</th>
<th>
<Center c={AccentColor.white}>Judul</Center>
</th>
<th>
<Center c={AccentColor.white}>Deskripsi</Center>
</th>
<th>
<Center c={AccentColor.white}>Pilihan</Center>
</th>
<th>
<Center c={AccentColor.white}>Mulai Vote</Center>
</th>
<th>
<Center c={AccentColor.white}>Selesai Vote</Center>
</th>
</tr>
</thead>
<tbody>{renderTableBody()}</tbody>
</Table>
</ScrollArea>
<Center mt={"xl"}>
<Pagination
value={isActivePage}
total={isNPage}
onChange={(val) => {
onPageClick(val);
}}
/>
</Center>
</Paper>
)}
</Stack> </Stack>
<Modal <Modal

View File

@@ -48,28 +48,33 @@ import { AdminVote_funEditStatusPublishById } from "../../fun/edit/fun_edit_stat
import { AdminEvent_funEditCatatanById } from "../../fun/edit/fun_edit_status_reject_by_id"; import { AdminEvent_funEditCatatanById } from "../../fun/edit/fun_edit_status_reject_by_id";
import { ComponentAdminGlobal_TitlePage } from "@/app_modules/admin/_admin_global/_component"; import { ComponentAdminGlobal_TitlePage } from "@/app_modules/admin/_admin_global/_component";
import { AdminColor } from "@/app_modules/_global/color/color_pallet"; import { AdminColor } from "@/app_modules/_global/color/color_pallet";
import { clientLogger } from "@/util/clientLogger";
import { apiGetAdminVotingByStatus } from "../../lib/api_fetch_admin_voting";
import _ from "lodash";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import ComponentAdminGlobal_IsEmptyData from "@/app_modules/admin/_admin_global/is_empty_data";
export default function AdminVote_TableReview({ export default function AdminVote_TableReview() {
listVote,
}: {
listVote: MODEL_VOTING[];
}) {
return ( return (
<> <>
<Stack> <Stack>
<ComponentAdminGlobal_HeaderTamplate name="Voting" /> <ComponentAdminGlobal_HeaderTamplate name="Voting" />
<TableStatus listData={listVote} /> <TableStatus />
</Stack> </Stack>
</> </>
); );
} }
function TableStatus({ listData }: { listData: any }) { function TableStatus() {
const [openedReject, { open: openReject, close: closeReject }] = useDisclosure(false); const [openedReject, { open: openReject, close: closeReject }] =
const [openedPublish, { open: openPublish, close: closePublish }] = useDisclosure(false); useDisclosure(false);
const [data, setData] = useState<MODEL_VOTING[]>(listData.data); const [openedPublish, { open: openPublish, close: closePublish }] =
const [isNPage, setNPage] = useState(listData.nPage); useDisclosure(false);
const [votingId, setVotingId] = useState("");
const [data, setData] = useState<MODEL_VOTING[] | null>(null);
const [nPage, setNPage] = useState(1);
const [dataId, setDataId] = useState("");
const [tanggalMulai, setTanggalMulai] = useState<Date>();
const [catatan, setCatatan] = useState(""); const [catatan, setCatatan] = useState("");
const [isLoadingPublish, setLoadingPublish] = useState(false); const [isLoadingPublish, setLoadingPublish] = useState(false);
const [isSaveLoading, setSaveLoading] = useState(false); const [isSaveLoading, setSaveLoading] = useState(false);
@@ -90,11 +95,33 @@ function TableStatus({ listData }: { listData: any }) {
} }
}, [isAdminVoting_TriggerReview, setIsShowReload]); }, [isAdminVoting_TriggerReview, setIsShowReload]);
async function onLoadData() { useShallowEffect(() => {
const loadData = await adminVote_funGetListReview({ page: 1 }); handleLoadData();
}, [isActivePage, isSearch]);
setData(loadData.data as any); const handleLoadData = async () => {
setNPage(loadData.nPage); try {
const response = await apiGetAdminVotingByStatus({
name: "Review",
page: `${isActivePage}`,
search: isSearch,
});
if (response?.success && response?.data?.data) {
setData(response.data.data);
setNPage(response.data.nPage || 1);
} else {
console.error("Invalid data format received:", response);
setData([]);
}
} catch (error) {
clientLogger.error("Error get data table publish", error);
setData([]);
}
};
async function onLoadData() {
handleLoadData();
setIsLoading(false); setIsLoading(false);
setIsShowReload(false); setIsShowReload(false);
setIsAdminVoting_TriggerReview(false); setIsAdminVoting_TriggerReview(false);
@@ -102,114 +129,197 @@ function TableStatus({ listData }: { listData: any }) {
async function onSearch(s: string) { async function onSearch(s: string) {
setSearch(s); setSearch(s);
const loadData = await adminVote_funGetListReview({
page: 1,
search: s,
});
setData(loadData.data as any);
setNPage(loadData.nPage);
} }
async function onPageClick(p: any) { async function onPageClick(p: any) {
setActivePage(p); setActivePage(p);
const loadData = await adminVote_funGetListReview({
search: isSearch,
page: p,
});
setData(loadData.data as any);
setNPage(loadData.nPage);
} }
const TableRows = data.map((e, i) => ( async function onReject() {
<tr key={i}> const data = {
<td> id: dataId,
<Center c={AccentColor.white}>{e?.Author?.username}</Center> catatan: catatan,
</td> };
<td>
<Center c={AccentColor.white}>{e.title}</Center>
</td>
<td>
<Center c={AccentColor.white}>
<Spoiler
hideLabel="sembunyikan"
maw={400}
maxHeight={50}
showLabel="tampilkan"
>
{e.deskripsi}
</Spoiler>
</Center>
</td>
<th>
<Stack>
{e.Voting_DaftarNamaVote.map((v) => (
<Box key={v.id}>
<Text c={AccentColor.white}>- {v.value}</Text>
</Box>
))}
</Stack>
</th>
<td>
<Center c={AccentColor.white}>
{e.awalVote.toLocaleDateString("id-ID", { dateStyle: "long" })}
</Center>
</td>
<td>
<Center c={AccentColor.white}>
{e.akhirVote.toLocaleDateString("id-ID", { dateStyle: "long" })}
</Center>
</td>
<td> try {
<Stack align="center"> setSaveLoading(true);
<Button const res = await AdminEvent_funEditCatatanById(data as any);
// loaderPosition="center" if (res.status === 200) {
// loading={ const dataNotifikasi: IRealtimeData = {
// e?.id === votingId ? (isLoadingPublish ? true : false) : false appId: res.data?.id as string,
// } status: res.data?.Voting_Status?.name as any,
w={120} userId: res.data?.authorId as any,
color={"green"} pesan: res.data?.title as any,
leftIcon={<IconCircleCheck />} kategoriApp: "VOTING",
radius={"xl"} title: "Voting anda di tolak !",
onClick={() => { };
openPublish();
setVotingId(e.id); const notif = await adminNotifikasi_funCreateToUser({
} data: dataNotifikasi as any,
// onPublish({ });
// // voteId: e.id,
// // awalVote: e.awalVote, if (notif.status === 201) {
// // setLoadingPublish: setLoadingPublish, WibuRealtime.setData({
// // setVotingId: setVotingId, type: "notification",
// // setData(val) { pushNotificationTo: "USER",
// // setData(val.data); dataMessage: dataNotifikasi,
// // setNPage(val.nPage); });
// // }, }
// })
} handleLoadData();
> ComponentGlobal_NotifikasiBerhasil(res.message);
Publish } else {
</Button> ComponentGlobal_NotifikasiGagal(res.message);
<Button }
w={120} } catch (error) {
color={"red"} console.error("Error update voting admin", error);
leftIcon={<IconBan />} } finally {
radius={"xl"} closeReject();
onClick={() => { setSaveLoading(false);
openReject(); }
setVotingId(e.id); }
}}
> async function onPublish() {
Reject const hariIni = new Date();
</Button> const cekHari = moment(tanggalMulai).diff(hariIni, "days");
</Stack>
</td> if (cekHari < 0)
</tr> return ComponentGlobal_NotifikasiPeringatan("Tanggal Voting Lewat");
));
try {
setLoadingPublish(true);
const res = await AdminVote_funEditStatusPublishById(dataId);
if (res.status === 200) {
const dataNotifikasi: IRealtimeData = {
appId: res.data?.id as string,
status: res.data?.Voting_Status?.name as any,
userId: res.data?.authorId as any,
pesan: res.data?.title as any,
kategoriApp: "VOTING",
title: "Voting publish",
};
const notif = await adminNotifikasi_funCreateToUser({
data: dataNotifikasi as any,
});
if (notif.status === 201) {
WibuRealtime.setData({
type: "notification",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
WibuRealtime.setData({
type: "trigger",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
}
handleLoadData();
ComponentGlobal_NotifikasiBerhasil(res.message);
closePublish()
} else {
ComponentGlobal_NotifikasiGagal(res.message);
}
} catch (error) {
console.log("Error get data voting", error);
} finally {
setLoadingPublish(false);
}
}
const renderTableBody = () => {
if (!Array.isArray(data) || data.length === 0) {
return (
<tr>
<td colSpan={12}>
<Center>
<Text color={"gray"}>Tidak ada data</Text>
</Center>
</td>
</tr>
);
}
return data?.map((e, i) => (
<tr key={i}>
<td>
<Center c={AccentColor.white}>{e?.Author?.username}</Center>
</td>
<td>
<Center c={AccentColor.white}>{e.title}</Center>
</td>
<td>
<Center c={AccentColor.white}>
<Spoiler
hideLabel="sembunyikan"
maw={400}
maxHeight={50}
showLabel="tampilkan"
>
{e.deskripsi}
</Spoiler>
</Center>
</td>
<td>
<Stack>
{e.Voting_DaftarNamaVote.map((v) => (
<Box key={v.id}>
<Text c={AccentColor.white}>- {v.value}</Text>
</Box>
))}
</Stack>
</td>
<td>
<Center c={AccentColor.white}>
{new Intl.DateTimeFormat("id-ID", {
dateStyle: "long",
}).format(new Date(e?.awalVote))}
</Center>
</td>
<td>
<Center c={AccentColor.white}>
{new Intl.DateTimeFormat("id-ID", {
dateStyle: "long",
}).format(new Date(e?.akhirVote))}
</Center>
</td>
<td>
<Stack align="center">
<Button
w={120}
color={"green"}
leftIcon={<IconCircleCheck />}
radius={"xl"}
onClick={() => {
openPublish();
setDataId(e.id);
setTanggalMulai(e.awalVote);
}}
>
Publish
</Button>
<Button
w={120}
color={"red"}
leftIcon={<IconBan />}
radius={"xl"}
onClick={() => {
openReject();
setDataId(e.id);
}}
>
Reject
</Button>
</Stack>
</td>
</tr>
));
};
return ( return (
<> <>
<Stack spacing={"xs"} h={"100%"}> <Stack spacing={"xs"} h={"100%"}>
{/* <pre>{JSON.stringify(listUser, null, 2)}</pre> */}
<ComponentAdminGlobal_TitlePage <ComponentAdminGlobal_TitlePage
name="Review" name="Review"
color={AdminColor.softBlue} color={AdminColor.softBlue}
@@ -224,94 +334,82 @@ function TableStatus({ listData }: { listData: any }) {
/> />
} }
/> />
{/* <Group
position="apart"
bg={"orange.4"}
p={"xs"}
style={{ borderRadius: "6px" }}
>
<Title order={4}>Review</Title>
<TextInput
icon={<IconSearch size={20} />}
radius={"xl"}
placeholder="Masukan judul"
onChange={(val) => {
onSearch(val.currentTarget.value);
}}
/>
</Group> */}
<Paper p={"md"} bg={AdminColor.softBlue} shadow="lg" h={"80vh"}> {!data ? (
{isShowReload && ( <CustomSkeleton height={"80vh"} width="100%" />
<Affix position={{ top: rem(200) }} w={"100%"}> ) : _.isEmpty(data) ? (
<Center> <ComponentAdminGlobal_IsEmptyData />
<Button ) : (
style={{ <Paper p={"md"} bg={AdminColor.softBlue} shadow="lg" h={"80vh"}>
transition: "0.5s", {isShowReload && (
border: `1px solid ${AccentColor.skyblue}`, <Affix position={{ top: rem(200) }} w={"100%"}>
}} <Center>
bg={AccentColor.blue} <Button
loaderPosition="center" style={{
loading={isLoading} transition: "0.5s",
radius={"xl"} border: `1px solid ${AccentColor.skyblue}`,
opacity={0.8} }}
onClick={() => onLoadData()} bg={AccentColor.blue}
leftIcon={<IconRefresh />} loaderPosition="center"
> loading={isLoading}
Update Data radius={"xl"}
</Button> opacity={0.8}
</Center> onClick={() => onLoadData()}
</Affix> leftIcon={<IconRefresh />}
)} >
Update Data
</Button>
</Center>
</Affix>
)}
<ScrollArea w={"100%"} h={"90%"}> <ScrollArea w={"100%"} h={"90%"}>
<Table <Table
verticalSpacing={"md"} verticalSpacing={"md"}
horizontalSpacing={"md"} horizontalSpacing={"md"}
p={"md"} p={"md"}
w={1500} w={1500}
>
> <thead>
<thead> <tr>
<tr> <th>
<th> <Center c={AccentColor.white}>Username</Center>
<Center c={AccentColor.white}>Username</Center> </th>
</th> <th>
<th> <Center c={AccentColor.white}>Judul</Center>
<Center c={AccentColor.white}>Judul</Center> </th>
</th> <th>
<th> <Center c={AccentColor.white}>Deskripsi</Center>
<Center c={AccentColor.white}>Deskripsi</Center> </th>
</th> <th>
<th> <Center c={AccentColor.white}>Pilihan</Center>
<Center c={AccentColor.white}>Pilihan</Center> </th>
</th> <th>
<th> <Center c={AccentColor.white}>Mulai Vote</Center>
<Center c={AccentColor.white}>Mulai Vote</Center> </th>
</th> <th>
<th> <Center c={AccentColor.white}>Selesai Vote</Center>
<Center c={AccentColor.white}>Selesai Vote</Center> </th>
</th> <th>
<Center c={AccentColor.white}>Aksi</Center>
</th>
</tr>
</thead>
<tbody>{renderTableBody()}</tbody>
</Table>
</ScrollArea>
<th> <Center mt={"xl"}>
<Center c={AccentColor.white}>Aksi</Center> <Pagination
</th> value={isActivePage}
</tr> total={nPage}
</thead> onChange={(val) => {
<tbody>{TableRows}</tbody> onPageClick(val);
</Table> }}
</ScrollArea> />
</Center>
<Center mt={"xl"}> </Paper>
<Pagination )}
value={isActivePage}
total={isNPage}
onChange={(val) => {
onPageClick(val);
}}
/>
</Center>
</Paper>
</Stack> </Stack>
<Modal <Modal
@@ -342,23 +440,10 @@ function TableStatus({ listData }: { listData: any }) {
loading={isSaveLoading ? true : false} loading={isSaveLoading ? true : false}
radius={"xl"} radius={"xl"}
onClick={() => { onClick={() => {
onReject({ onReject();
catatan: catatan,
voteId: votingId,
setData(val) {
setData(val.data);
setNPage(val.nPage);
},
close: () => {
closeReject();
},
setSaveLoading(val) {
setSaveLoading(val);
},
});
}} }}
style={{ style={{
backgroundColor: MainColor.green backgroundColor: MainColor.green,
}} }}
> >
Simpan Simpan
@@ -384,23 +469,7 @@ function TableStatus({ listData }: { listData: any }) {
loading={isLoadingPublish ? true : false} loading={isLoadingPublish ? true : false}
radius={"xl"} radius={"xl"}
onClick={() => { onClick={() => {
onPublish({ onPublish();
awalVote: data[0].awalVote,
voteId: votingId,
setData(val) {
setData(val.data);
setNPage(val.nPage);
},
close: () => {
closePublish();
},
setLoadingPublish: (val) => {
setLoadingPublish(val);
},
setVotingId: (val) => {
setVotingId(val);
},
});
}} }}
style={{ style={{
backgroundColor: MainColor.green, backgroundColor: MainColor.green,
@@ -414,132 +483,3 @@ function TableStatus({ listData }: { listData: any }) {
</> </>
); );
} }
async function onPublish({
close,
voteId,
setData,
awalVote,
setLoadingPublish,
setVotingId,
}: {
close: any,
voteId: string;
setData: (val: { data: any[]; nPage: number }) => void;
awalVote: Date;
setLoadingPublish: (val: boolean) => void;
setVotingId: (val: string) => void;
}) {
const hariIni = new Date();
const cekHari = moment(awalVote).diff(hariIni, "days");
if (cekHari < 0)
return ComponentGlobal_NotifikasiPeringatan("Tanggal Voting Lewat");
setVotingId(voteId);
const res = await AdminVote_funEditStatusPublishById(voteId);
if (res.status === 200) {
setLoadingPublish(true);
const dataNotifikasi: IRealtimeData = {
appId: res.data?.id as string,
status: res.data?.Voting_Status?.name as any,
userId: res.data?.authorId as any,
pesan: res.data?.title as any,
kategoriApp: "VOTING",
title: "Voting publish",
};
const notif = await adminNotifikasi_funCreateToUser({
data: dataNotifikasi as any,
});
if (notif.status === 201) {
WibuRealtime.setData({
type: "notification",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
WibuRealtime.setData({
type: "trigger",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
}
const loadData = await adminVote_funGetListReview({ page: 1 });
setData({
data: loadData.data,
nPage: loadData.nPage,
});
ComponentGlobal_NotifikasiBerhasil(res.message);
setLoadingPublish(false);
} else {
ComponentGlobal_NotifikasiGagal(res.message);
}
}
async function onReject({
voteId,
catatan,
close,
setSaveLoading,
setData,
}: {
voteId: string;
catatan: string;
close: any;
setSaveLoading: (val: boolean) => void;
setData: (val: { data: any[]; nPage: number }) => void;
}) {
const data = {
id: voteId,
catatan: catatan,
};
const res = await AdminEvent_funEditCatatanById(data as any);
if (res.status === 200) {
setSaveLoading(true);
// const dataNotif = {
// appId: res.data?.id,
// status: res.data?.Voting_Status?.name as any,
// userId: res.data?.authorId as any,
// pesan: res.data?.title as any,
// kategoriApp: "VOTING",
// title: "Voting anda di tolak !",
// };
const dataNotifikasi: IRealtimeData = {
appId: res.data?.id as string,
status: res.data?.Voting_Status?.name as any,
userId: res.data?.authorId as any,
pesan: res.data?.title as any,
kategoriApp: "VOTING",
title: "Voting anda di tolak !",
};
const notif = await adminNotifikasi_funCreateToUser({
data: dataNotifikasi as any,
});
if (notif.status === 201) {
WibuRealtime.setData({
type: "notification",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
}
const loadData = await adminVote_funGetListReview({ page: 1 });
setData({
data: loadData.data,
nPage: loadData.nPage,
});
setSaveLoading(false);
ComponentGlobal_NotifikasiBerhasil(res.message);
close();
} else {
ComponentGlobal_NotifikasiGagal(res.message);
}
}

View File

@@ -1,64 +1,87 @@
export { export {
apiGetAdminVoteStatusCountDashboard, apiGetAdminVoteStatusCountDashboard,
apiGetAdminVoteRiwayatCount, apiGetAdminVoteRiwayatCount,
apiGetAdminVotingByStatus apiGetAdminVotingByStatus,
} };
const apiGetAdminVoteStatusCountDashboard = async ({ name }: { const apiGetAdminVoteStatusCountDashboard = async ({
name: "Publish" | "Review" | "Reject"; name,
}: {
name: "Publish" | "Review" | "Reject";
}) => { }) => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json()); const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null); if (!token) return await token.json().catch(() => null);
const response = await fetch(`/api/admin/vote/dashboard/${name}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
const response = await fetch(`/api/admin/vote/dashboard/${name}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
}
});
return await response.json().catch(() => null);
}
const apiGetAdminVoteRiwayatCount = async () => { const apiGetAdminVoteRiwayatCount = async () => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json()); const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null); if (!token) return await token.json().catch(() => null);
const response = await fetch(`/api/admin/vote/dashboard/riwayat`, { const response = await fetch(`/api/admin/vote/dashboard/riwayat`, {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Accept: "application/json", Accept: "application/json",
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
} },
}); });
return await response.json().catch(() => null); return await response.json().catch(() => null);
} };
const apiGetAdminVotingByStatus = async ({ const apiGetAdminVotingByStatus = async ({
name, name,
page, page,
search }: { search,
name: "Publish" | "Review" | "Reject"; }: {
page: string; name: "Publish" | "Review" | "Reject";
search: string; page: string;
}) => { search: string;
}) => {
try {
// Fetch token from cookie
const { token } = await fetch("/api/get-cookie").then((res) => res.json()); const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null); if (!token) {
console.error("No token found");
return null;
}
const isPage = page ? `?page=${page}` : ""; const isPage = page ? `?page=${page}` : "";
const isSearch = search ? `&search=${search}` : ""; const isSearch = search ? `&search=${search}` : "";
const response = await fetch( const response = await fetch(
`/api/admin/vote/status/${name}${isPage}${isSearch}`, `/api/admin/vote/status/${name}${isPage}${isSearch}`,
{ {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Accept: "application/json", Accept: "application/json",
"Access-Control-Allow-Origin": "*", Authorization: `Bearer ${token}`,
Authorization: `Bearer ${token}` },
} }
} );
)
return await response.json().catch(() => null); // Check if the response is OK
} if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Error get data voting admin",
errorData?.message || "Unknown error"
);
return null;
}
return response.json();
} catch (error) {
console.log("Error get data voting admin", error);
throw error;
}
};