Merge pull request #218 from bipproduction/fix/bug/voting

Intergrasi server action to API
This commit is contained in:
Bagasbanuna02
2024-12-30 08:22:03 +08:00
committed by GitHub
16 changed files with 776 additions and 373 deletions

View File

@@ -2,6 +2,8 @@
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines. All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
## [1.2.36](https://github.com/bipproduction/hipmi/compare/v1.2.35...v1.2.36) (2024-12-30)
## [1.2.35](https://github.com/bipproduction/hipmi/compare/v1.2.34...v1.2.35) (2024-12-27) ## [1.2.35](https://github.com/bipproduction/hipmi/compare/v1.2.34...v1.2.35) (2024-12-27)
## [1.2.34](https://github.com/bipproduction/hipmi/compare/v1.2.33...v1.2.34) (2024-12-24) ## [1.2.34](https://github.com/bipproduction/hipmi/compare/v1.2.33...v1.2.34) (2024-12-24)

View File

@@ -1,6 +1,6 @@
{ {
"name": "hipmi", "name": "hipmi",
"version": "1.2.35", "version": "1.2.36",
"private": true, "private": true,
"prisma": { "prisma": {
"seed": "npx tsx prisma/seed.ts --yes" "seed": "npx tsx prisma/seed.ts --yes"

View File

@@ -0,0 +1,47 @@
import { prisma } from "@/app/lib";
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(
request: Request,
context: { params: { id: string } }
) {
try {
let fixData;
const { id } = context.params;
fixData = await prisma.voting.findFirst({
where: {
id: id,
},
include: {
Voting_DaftarNamaVote: {
orderBy: {
createdAt: "asc",
},
where: {
isActive: true,
},
},
Author: {
select: {
Profile: true,
},
},
},
});
return NextResponse.json(
{ success: true, message: "Berhasil mendapatkan data", data: fixData },
{ status: 200 }
);
} catch (error) {
backendLogger.error("Gagal mendapatkan data voting by id", error);
return NextResponse.json(
{ success: false, message: "Gagal mendapatkan data" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,76 @@
import { prisma } from "@/app/lib";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import backendLogger from "@/util/backendLogger";
import _ from "lodash";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
/**
*
* @param id | votingId
* @param kategori | kontribusi
* @returns
*/
export async function GET(request: Request) {
try {
let fixData;
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
const kategori = searchParams.get("kategori");
const userLoginId = await funGetUserIdByToken();
if (!userLoginId) {
return NextResponse.json(
{ success: false, message: "Gagal mendapatkan data, coba lagi nanti " },
{ status: 500 }
);
}
if (kategori == "isKontributor") {
const cek = await prisma.voting_Kontributor.count({
where: {
authorId: userLoginId,
votingId: id,
},
});
if (cek > 0) {
fixData = true;
} else {
fixData = false;
}
} else if (kategori == "pilihan") {
const cekPilihan = await prisma.voting_Kontributor.findFirst({
where: {
authorId: userLoginId,
votingId: id,
},
select: {
Voting_DaftarNamaVote: {
select: {
value: true,
},
},
},
});
fixData = cekPilihan?.Voting_DaftarNamaVote?.value
}
return NextResponse.json(
{ success: true, message: "Berhasil mendapatkan data", data: fixData },
{ status: 200 }
);
} catch (error) {
backendLogger.error("Error get hitung voting", error);
return NextResponse.json(
{
success: false,
message: "Gagal mendapatkan data",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,30 @@
import { prisma } from "@/app/lib";
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(request: Request) {
try {
let fixData;
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
fixData = await prisma.voting_DaftarNamaVote.findMany({
where: {
votingId: id,
},
});
return NextResponse.json(
{ success: true, message: "Berhasil mendapatkan data", data: fixData },
{ status: 200 }
);
} catch (error) {
backendLogger.error(error);
return NextResponse.json(
{ success: false, message: "Gagal mendapatkan data" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,46 @@
import { prisma } from "@/app/lib";
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export async function GET(request: Request) {
try {
let fixData;
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
const page = searchParams.get("page");
const takeData = 10;
const dataSkip = Number(page) * takeData - takeData;
fixData = await prisma.voting_Kontributor.findMany({
// take: takeData,
// skip: dataSkip,
orderBy: {
createdAt: "desc",
},
where: {
votingId: id,
},
include: {
Author: {
include: {
Profile: true,
},
},
Voting_DaftarNamaVote: {
select: {
value: true,
},
},
},
});
return NextResponse.json({ success: true, data: fixData }, { status: 200 });
} catch (error) {
backendLogger.error(error);
return NextResponse.json(
{ success: false, reason: (error as Error).message || (error as Error) },
{ status: 500 }
);
}
}

View File

@@ -1,13 +1,9 @@
import { Voting_UiDetailKontributorVoting } from "@/app_modules/vote/_ui"; import { Voting_UiDetailKontributorVoting } from "@/app_modules/vote/_ui";
import { Vote_getListKontributorById } from "@/app_modules/vote/fun/get/get_list_kontributor_by_id";
export default async function Page({ params }: { params: { id: string } }) {
const votingId = params.id;
const listKontributor = await Vote_getListKontributorById(votingId);
export default async function Page() {
return ( return (
<> <>
<Voting_UiDetailKontributorVoting listKontributor={listKontributor} /> <Voting_UiDetailKontributorVoting />
</> </>
); );
} }

View File

@@ -1,29 +1,12 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { Vote_MainDetail } from "@/app_modules/vote"; import { Vote_MainDetail } from "@/app_modules/vote";
import { Vote_cekKontributorById } from "@/app_modules/vote/fun/get/cek_kontributor_by_id";
import { voting_funGetOneVotingbyId } from "@/app_modules/vote/fun/get/fun_get_one_by_id";
import { Vote_getHasilVoteById } from "@/app_modules/vote/fun/get/get_list_hasil_by_id";
import { Vote_getListKontributorById } from "@/app_modules/vote/fun/get/get_list_kontributor_by_id";
import { Vote_getOnePilihanVotingByUserId } from "@/app_modules/vote/fun/get/get_one_pilihan_voting_by_user_id";
export default async function Page({ params }: { params: { id: string } }) { export default async function Page({ params }: { params: { id: string } }) {
const voteId = params.id; const voteId = params.id;
const userLoginId = await funGetUserIdByToken(); const userLoginId = await funGetUserIdByToken();
const dataVote = await voting_funGetOneVotingbyId(voteId);
const hasilVoting = await Vote_getHasilVoteById(voteId as any);
const isKontributor = await Vote_cekKontributorById(voteId);
const pilihanKontributor = await Vote_getOnePilihanVotingByUserId(voteId);
const listKontributor = await Vote_getListKontributorById(voteId);
return ( return (
<> <>
<Vote_MainDetail <Vote_MainDetail
dataVote={dataVote as any}
hasilVoting={hasilVoting}
isKontributor={isKontributor}
pilihanKontributor={pilihanKontributor as any}
listKontributor={listKontributor as any}
userLoginId={userLoginId as string} userLoginId={userLoginId as string}
/> />
</> </>

View File

@@ -14,93 +14,46 @@ import { useState } from "react";
import { DIRECTORY_ID } from "../lib"; import { DIRECTORY_ID } from "../lib";
export default function Page() { export default function Page() {
const [filePP, setFilePP] = useState<File | null>(null); const [data, setData] = useState({
const [imgPP, setImgPP] = useState<any | null>(); name: "bagas",
hobi: [
async function onSave() { {
const body = { id: "1",
file: filePP, name: "mancing",
dirId: DIRECTORY_ID.profile_foto, },
}; {
id: "2",
const token = name: "game",
"QWERTYUIOPLKJHGFDSAZXCVBNMQAZWSXEDCRFVTGBYHNUJMIKOLPPOIUYTREWQLKJHGFDSAMNBVCXZlghvftyguhijknhbgvcfytguu8okjnhbgvfty7u8oilkjnhgvtygu7u8ojilnkhbgvhujnkhghvjhukjnhb"; },
],
const formData = new FormData(); });
formData.append("file", filePP as any);
const res = await fetch("/api/image/upload", {
method: "POST",
body: formData,
});
console.log(await res.json());
}
return ( return (
<> <>
<Stack> <Stack align="center" justify="center" h={"100vh"}>
<Center> <pre>{JSON.stringify(data, null, 2)}</pre>
{imgPP ? (
<Paper shadow="lg" radius={"100%"}>
<Avatar
color={"cyan"}
sx={{
borderStyle: "solid",
borderColor: "gray",
borderWidth: "0.5px",
}}
src={imgPP ? imgPP : "/aset/global/avatar.png"}
size={150}
radius={"100%"}
/>
</Paper>
) : (
<Paper shadow="lg" radius={"100%"}>
<Avatar
variant="light"
color="blue"
size={150}
radius={"100%"}
sx={{
borderStyle: "solid",
borderColor: MainColor.darkblue,
borderWidth: "0.5px",
}}
/>
</Paper>
)}
</Center>
<FileButton <Button
onChange={async (files: any | null) => { onClick={() => {
try { const newData = [
const buffer = URL.createObjectURL( {
new Blob([new Uint8Array(await files.arrayBuffer())]) id: "1",
); name: "sepedah",
setImgPP(buffer); },
setFilePP(files); {
} catch (error) { id: "2",
console.log(error); name: "berenang",
} },
];
setData({
...data,
hobi: newData,
});
}} }}
accept="image/png,image/jpeg"
> >
{(props) => ( Ganti
<Button </Button>
{...props}
radius={"xl"}
leftIcon={<IconCamera />}
bg={MainColor.yellow}
color="yellow"
c={"black"}
>
Upload
</Button>
)}
</FileButton>
<Button onClick={() => onSave()}>Upload</Button>
</Stack> </Stack>
</> </>
); );

View File

@@ -11,40 +11,44 @@ export default function Voting_ComponentSkeletonViewPuh() {
return ( return (
<> <>
<UIGlobal_LayoutTamplate <UIGlobal_LayoutTamplate
header={<UIGlobal_LayoutHeaderTamplate title="Detail Publish" />} header={<UIGlobal_LayoutHeaderTamplate title="Skeleton Maker" />}
> >
<ComponentGlobal_CardStyles marginBottom={"0"}> <Stack>
<Stack spacing={"lg"}> <ComponentGlobal_CardStyles marginBottom={"0"}>
<Grid align="center"> <Stack spacing={"xl"}>
<Grid.Col span={"content"}> <Grid align="center" gutter={"md"}>
<Skeleton circle height={40} /> <Grid.Col span={"content"}>
</Grid.Col> <Skeleton circle height={40} />
<Grid.Col span={4}> </Grid.Col>
<Skeleton height={20} w={150} /> <Grid.Col span={3}>
</Grid.Col> <Skeleton height={20} w={150} />
</Grid> </Grid.Col>
<Grid.Col span={3} offset={3}>
<Stack align="center"> <Skeleton height={20} w={150} />
<Skeleton height={20} w={150} /> </Grid.Col>
<Skeleton height={20} w={300} /> </Grid>
</Stack> </Stack>
</ComponentGlobal_CardStyles>
<Group position="center" spacing={100}> {/* <ComponentGlobal_CardStyles>
<Stack align="center"> <Stack>
<Skeleton circle height={70} /> <Center>
<Skeleton height={20} w={50} /> <Skeleton h={20} w={"30%"} />
</Stack> </Center>
<Stack align="center">
<Skeleton circle height={70} />
<Skeleton height={20} w={50} />
</Stack>
</Group>
<Stack align="center"> <Group position="center" spacing={50}>
<Skeleton height={15} w={50} /> <Skeleton height={20} w={50} /> <Stack align="center">
<Skeleton circle height={70} />
<Skeleton height={20} w={50} />
</Stack>
<Stack align="center">
<Skeleton circle height={70} />
<Skeleton height={20} w={50} />
</Stack>
</Group>
</Stack> </Stack>
</Stack> </ComponentGlobal_CardStyles> */}
</ComponentGlobal_CardStyles> </Stack>
</UIGlobal_LayoutTamplate> </UIGlobal_LayoutTamplate>
</> </>
); );

View File

@@ -40,3 +40,37 @@ export const apiGetAllVoting = async ({
); );
return await respone.json().catch(() => null); return await respone.json().catch(() => null);
}; };
export const apiGetOneVotingById = async ({ id }: { id: string }) => {
const respone = await fetch(`/api/voting/${id}`);
return await respone.json().catch(() => null);
};
export const apiCheckKontributorToOneVoting = async ({
id,
kategori,
}: {
id: string;
kategori: "isKontributor" | "pilihan";
}) => {
const respone = await fetch(
`/api/voting/check?id=${id}&kategori=${kategori}`
);
return await respone.json().catch(() => null);
};
export const apiGetHasilVotingById = async ({ id }: { id: string }) => {
const respone = await fetch(`/api/voting/hasil?id=${id}`);
return await respone.json().catch(() => null);
};
export const apiGetKontributorById = async ({
id,
page,
}: {
id: string;
page: string;
}) => {
const respone = await fetch(`/api/voting/kontributor?id=${id}&page=${page}`);
return await respone.json().catch(() => null);
};

View File

@@ -6,17 +6,13 @@ import {
} from "@/app_modules/_global/ui"; } from "@/app_modules/_global/ui";
import { Voting_ViewDetailKontributorVoting } from "../../_view"; import { Voting_ViewDetailKontributorVoting } from "../../_view";
export function Voting_UiDetailKontributorVoting({ export function Voting_UiDetailKontributorVoting() {
listKontributor,
}: {
listKontributor: any[];
}) {
return ( return (
<> <>
<UIGlobal_LayoutTamplate <UIGlobal_LayoutTamplate
header={<UIGlobal_LayoutHeaderTamplate title="Daftar Kontributor" />} header={<UIGlobal_LayoutHeaderTamplate title="Daftar Kontributor" />}
> >
<Voting_ViewDetailKontributorVoting listKontributor={listKontributor} /> <Voting_ViewDetailKontributorVoting />
</UIGlobal_LayoutTamplate> </UIGlobal_LayoutTamplate>
</> </>
); );

View File

@@ -3,23 +3,107 @@ import {
ComponentGlobal_CardStyles, ComponentGlobal_CardStyles,
} from "@/app_modules/_global/component"; } from "@/app_modules/_global/component";
import ComponentGlobal_IsEmptyData from "@/app_modules/_global/component/is_empty_data"; import ComponentGlobal_IsEmptyData from "@/app_modules/_global/component/is_empty_data";
import { Badge, Group, Stack, Text } from "@mantine/core"; import {
Badge,
Center,
Group,
Stack,
Text,
Loader,
Paper,
Box,
} from "@mantine/core";
import _ from "lodash"; import _ from "lodash";
import { MODEL_VOTE_KONTRIBUTOR } from "../model/interface"; import { MODEL_VOTE_KONTRIBUTOR } from "../model/interface";
import { useShallowEffect } from "@mantine/hooks";
import { apiGetKontributorById } from "../_lib/api_voting";
import { useParams } from "next/navigation";
import { useState } from "react";
import { clientLogger } from "@/util/clientLogger";
import { Voting_ComponentSkeletonDaftarKontributor } from "../component/skeleton_view";
import { ScrollOnly } from "next-scroll-loader";
export function Voting_ViewDetailKontributorVoting() {
const params = useParams<{ id: string }>();
const [data, setData] = useState<MODEL_VOTE_KONTRIBUTOR[] | null>(null);
const [activePage, setActivePage] = useState(1);
useShallowEffect(() => {
onLoadData();
}, []);
async function onLoadData() {
try {
const respone = await apiGetKontributorById({
id: params.id,
page: `${activePage}`,
});
if (respone) {
setData(respone.data);
}
} catch (error) {
clientLogger.error("Error get data kontributor", error);
}
}
if (_.isNull(data)) {
return <Voting_ComponentSkeletonDaftarKontributor />;
}
export function Voting_ViewDetailKontributorVoting({
listKontributor,
}: {
listKontributor: MODEL_VOTE_KONTRIBUTOR[];
}) {
return ( return (
<> <>
<ComponentGlobal_CardStyles> {_.isEmpty(data) ? (
{_.isEmpty(listKontributor) ? ( <ComponentGlobal_IsEmptyData text="Tidak ada kontributor" />
<ComponentGlobal_IsEmptyData text="Tidak ada kontributor" /> ) : (
) : ( <Box>
<Stack spacing={"lg"}> <ScrollOnly
{listKontributor?.map((e, i) => ( height="75vh"
renderLoading={() => (
<Center mt={"lg"}>
<Loader color={"yellow"} />
</Center>
)}
data={data}
setData={setData as any}
moreData={async () => {
const respone = await apiGetKontributorById({
id: params.id,
page: `${activePage + 1}`,
});
setActivePage((val) => val + 1);
return respone.data;
}}
>
{(item) => (
<ComponentGlobal_CardStyles>
<ComponentGlobal_AvatarAndUsername
key={item}
profile={item.Author.Profile as any}
component={
<Group position="right">
<Badge w={130}>
<Text
lineClamp={1}
fz={
item.Voting_DaftarNamaVote.value.length > 10
? 8
: 10
}
>
{item.Voting_DaftarNamaVote.value}
</Text>
</Badge>
</Group>
}
/>
</ComponentGlobal_CardStyles>
)}
</ScrollOnly>
{/* {data?.map((e, i) => (
<ComponentGlobal_AvatarAndUsername <ComponentGlobal_AvatarAndUsername
key={e.id} key={e.id}
profile={e.Author.Profile as any} profile={e.Author.Profile as any}
@@ -36,10 +120,9 @@ export function Voting_ViewDetailKontributorVoting({
</Group> </Group>
} }
/> />
))} ))} */}
</Stack> </Box>
)} )}
</ComponentGlobal_CardStyles>
</> </>
); );
} }

View File

@@ -1,7 +1,15 @@
import { ComponentGlobal_CardStyles } from "@/app_modules/_global/component"; import { ComponentGlobal_CardStyles } from "@/app_modules/_global/component";
import { Grid, Group, Skeleton, Stack } from "@mantine/core"; import { Center, Grid, Group, Skeleton, Stack } from "@mantine/core";
export function Voting_ComponentSkeletonViewPublish() { export {
Voting_ComponentSkeletonDetail,
Voting_ComponentSkeletonViewKontribusi,
Voting_ComponentSkeletonViewPublish,
Voting_ComponentSkeletonViewStatus,
Voting_ComponentSkeletonDaftarKontributor,
};
function Voting_ComponentSkeletonViewPublish() {
return ( return (
<> <>
{Array.from({ length: 2 }).map((e, i) => ( {Array.from({ length: 2 }).map((e, i) => (
@@ -39,7 +47,7 @@ export function Voting_ComponentSkeletonViewPublish() {
); );
} }
export function Voting_ComponentSkeletonViewStatus() { function Voting_ComponentSkeletonViewStatus() {
return ( return (
<> <>
{Array.from({ length: 2 }).map((e, i) => ( {Array.from({ length: 2 }).map((e, i) => (
@@ -54,7 +62,7 @@ export function Voting_ComponentSkeletonViewStatus() {
); );
} }
export function Voting_ComponentSkeletonViewKontribusi() { function Voting_ComponentSkeletonViewKontribusi() {
return ( return (
<> <>
{Array.from({ length: 2 }).map((e, i) => ( {Array.from({ length: 2 }).map((e, i) => (
@@ -93,5 +101,85 @@ export function Voting_ComponentSkeletonViewKontribusi() {
))} ))}
</> </>
); );
}
function Voting_ComponentSkeletonDetail() {
return (
<>
<Stack>
<ComponentGlobal_CardStyles marginBottom={"0"}>
<Stack spacing={"xl"}>
<Grid align="center">
<Grid.Col span={"content"}>
<Skeleton circle height={40} />
</Grid.Col>
<Grid.Col span={4}>
<Skeleton height={20} w={150} />
</Grid.Col>
</Grid>
<Stack align="center">
<Skeleton height={20} w={150} />
<Skeleton height={20} w={"100%"} />
<Skeleton height={20} w={"100%"} />
<Skeleton height={20} w={"100%"} />
<Skeleton height={20} w={50} />
<Skeleton height={20} w={200} />
</Stack>
{/* <Stack>
<Skeleton height={20} w={70} />
<Skeleton height={20} w={150} />
<Skeleton height={20} w={150} />
</Stack> */}
<Stack align="center">
<Skeleton height={20} w={70} />
</Stack>
</Stack>
</ComponentGlobal_CardStyles>
<ComponentGlobal_CardStyles>
<Stack>
<Center>
<Skeleton h={20} w={"30%"} />
</Center>
<Group position="center" spacing={50}>
<Stack align="center">
<Skeleton circle height={70} />
<Skeleton height={20} w={50} />
</Stack>
<Stack align="center">
<Skeleton circle height={70} />
<Skeleton height={20} w={50} />
</Stack>
</Group>
</Stack>
</ComponentGlobal_CardStyles>
</Stack>
</>
);
}
function Voting_ComponentSkeletonDaftarKontributor(){
return (
<>
<ComponentGlobal_CardStyles marginBottom={"0"}>
<Stack spacing={"xl"}>
<Grid align="center" gutter={"md"}>
<Grid.Col span={"content"}>
<Skeleton circle height={40} />
</Grid.Col>
<Grid.Col span={3}>
<Skeleton height={20} w={150} />
</Grid.Col>
<Grid.Col span={3} offset={3}>
<Skeleton height={20} w={150} />
</Grid.Col>
</Grid>
</Stack>
</ComponentGlobal_CardStyles>
</>
);
} }

View File

@@ -1,5 +1,6 @@
"use client"; "use client";
import { IRealtimeData } from "@/app/lib/global_state";
import { import {
AccentColor, AccentColor,
MainColor, MainColor,
@@ -9,263 +10,324 @@ import {
ComponentGlobal_CardStyles, ComponentGlobal_CardStyles,
} from "@/app_modules/_global/component"; } from "@/app_modules/_global/component";
import ComponentGlobal_BoxInformation from "@/app_modules/_global/component/box_information"; import ComponentGlobal_BoxInformation from "@/app_modules/_global/component/box_information";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global";
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil"; import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global/notifikasi_peringatan"; import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global/notifikasi_peringatan";
import notifikasiToUser_funCreate from "@/app_modules/notifikasi/fun/create/create_notif_to_user"; import notifikasiToUser_funCreate from "@/app_modules/notifikasi/fun/create/create_notif_to_user";
import mqtt_client from "@/util/mqtt_client"; import { clientLogger } from "@/util/clientLogger";
import { import {
Badge, Badge,
Box, Box,
Button, Button,
Center, Center,
Group,
Radio, Radio,
Stack, Stack,
Text, Text,
Title, Title,
} from "@mantine/core"; } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import _ from "lodash"; import _ from "lodash";
import moment from "moment"; import moment from "moment";
import "moment/locale/id";
import { useParams } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import ComponentVote_HasilVoting from "../../component/detail/detail_hasil_voting";
import { Vote_funCreateHasil } from "../../fun/create/create_hasil";
import { voting_funGetOneVotingbyId } from "../../fun/get/fun_get_one_by_id";
import { MODEL_VOTING } from "../../model/interface";
import { IRealtimeData } from "@/app/lib/global_state";
import { WibuRealtime } from "wibu-pkg"; import { WibuRealtime } from "wibu-pkg";
import {
apiCheckKontributorToOneVoting,
apiGetHasilVotingById,
apiGetOneVotingById,
} from "../../_lib/api_voting";
import ComponentVote_HasilVoting from "../../component/detail/detail_hasil_voting";
import { Voting_ComponentSkeletonDetail } from "../../component/skeleton_view";
import { Vote_funCreateHasil } from "../../fun/create/create_hasil";
import { MODEL_VOTING } from "../../model/interface";
export default function Vote_MainDetail({ export default function Vote_MainDetail({
dataVote,
hasilVoting,
isKontributor,
pilihanKontributor,
listKontributor,
userLoginId, userLoginId,
}: { }: {
dataVote: MODEL_VOTING;
hasilVoting: any;
isKontributor: boolean;
pilihanKontributor: string;
listKontributor: any[];
userLoginId: string; userLoginId: string;
}) { }) {
const [data, setData] = useState(dataVote); const params = useParams<{ id: string }>();
const today = new Date(); const today = new Date();
const [data, setData] = useState<MODEL_VOTING | null>(null);
const [hasil, setHasil] = useState<any[] | null>(null);
const [pilihanVotingId, setPilihanVotingId] = useState("");
const [pilihanKontributor, setPilihanKontributor] = useState<string | null>(
null
);
const [isKontributor, setIsKontributor] = useState<boolean | null>(null);
useShallowEffect(() => {
onLoadData();
onLoadHasil();
}, []);
async function onLoadData() {
try {
const respone = await apiGetOneVotingById({
id: params.id,
});
if (respone) {
setData(respone.data);
}
} catch (error) {
clientLogger.error("Error get data detail", error);
}
}
async function onLoadHasil() {
try {
const respone = await apiGetHasilVotingById({
id: params.id,
});
if (respone) {
setHasil(respone.data);
}
} catch (error) {
clientLogger.error("Error get data hasil voting", error);
}
}
useShallowEffect(() => {
onCheckKontribusi();
onLoadPilihan();
}, []);
async function onCheckKontribusi() {
try {
const respone = await apiCheckKontributorToOneVoting({
id: params.id,
kategori: "isKontributor",
});
if (respone) {
setIsKontributor(respone.data);
}
} catch (error) {
clientLogger.error("Error check kontibusi", error);
}
}
async function onLoadPilihan() {
try {
const respone = await apiCheckKontributorToOneVoting({
id: params.id,
kategori: "pilihan",
});
if (respone) {
setPilihanKontributor(respone.data);
}
} catch (error) {
clientLogger.error("Error check pilihan", error);
}
}
async function onVote() {
try {
const res = await Vote_funCreateHasil({
pilihanVotingId: pilihanVotingId,
votingId: params.id,
});
if (res.status === 201) {
const respone = await apiGetHasilVotingById({
id: params.id,
});
if (respone) {
setHasil(respone.data);
ComponentGlobal_NotifikasiBerhasil(res.message);
const checkKontibutor = await apiCheckKontributorToOneVoting({
id: params.id,
kategori: "isKontributor",
});
if (checkKontibutor) {
setIsKontributor(checkKontibutor.data);
}
const checkPilihan = await apiCheckKontributorToOneVoting({
id: params.id,
kategori: "pilihan",
});
if (checkPilihan) {
setPilihanKontributor(checkPilihan.data);
}
}
if (userLoginId !== res?.data?.Voting?.authorId) {
const dataNotifikasi: IRealtimeData = {
appId: res?.data?.Voting?.id as string,
userId: res?.data?.Voting?.authorId as string,
pesan: res?.pilihan as string,
status: "Voting Masuk",
kategoriApp: "VOTING",
title: "User lain telah melakukan voting !",
};
const createNotifikasi = await notifikasiToUser_funCreate({
data: dataNotifikasi as any,
});
if (createNotifikasi.status === 201) {
WibuRealtime.setData({
type: "notification",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
}
}
} else {
ComponentGlobal_NotifikasiPeringatan(res.message);
}
} catch (error) {
clientLogger.error("Error vote", error);
ComponentGlobal_NotifikasiGagal("Gagal melakukan voting");
}
}
if (_.isNull(data) || _.isNull(hasil) || _.isNull(isKontributor)) {
return <Voting_ComponentSkeletonDetail />;
}
return ( return (
<> <>
<Stack pb={"md"}> <Stack pb={"md"}>
{moment(dataVote?.awalVote).diff(today, "hours") < 0 ? ( {moment(data?.awalVote).diff(today, "hours") < 0 ? (
"" ""
) : ( ) : (
<ComponentGlobal_BoxInformation informasi="Untuk sementara voting ini belum di buka. Voting akan dimulai sesuai dengan tanggal awal pemilihan, dan akan ditutup sesuai dengan tanggal akhir pemilihan." /> <ComponentGlobal_BoxInformation informasi="Untuk sementara voting ini belum di buka. Voting akan dimulai sesuai dengan tanggal awal pemilihan, dan akan ditutup sesuai dengan tanggal akhir pemilihan." />
)} )}
<TampilanDataVoting
dataVote={data}
setData={setData}
isKontributor={isKontributor}
pilihanKontributor={pilihanKontributor}
userLoginId={userLoginId}
/>
<ComponentVote_HasilVoting data={data.Voting_DaftarNamaVote} />
</Stack>
</>
);
}
function TampilanDataVoting({ <ComponentGlobal_CardStyles>
dataVote, <Stack>
setData, <ComponentGlobal_AvatarAndUsername
isKontributor, profile={data?.Author?.Profile as any}
pilihanKontributor, />
userLoginId,
}: {
dataVote?: MODEL_VOTING;
setData: any;
isKontributor: boolean;
pilihanKontributor: any;
userLoginId: string;
}) {
const [votingNameId, setVotingNameId] = useState("");
const today = new Date();
return ( <Stack spacing={"lg"}>
<> <Center>
<ComponentGlobal_CardStyles> <Title order={5} align="center">
<Stack> {data?.title}
<ComponentGlobal_AvatarAndUsername </Title>
profile={dataVote?.Author?.Profile as any} </Center>
/> <Text>{data?.deskripsi}</Text>
{/* <ComponentGlobal_AuthorNameOnHeader
authorName={dataVote?.Author.Profile.name}
imagesId={dataVote?.Author.Profile.imagesId}
profileId={dataVote?.Author.Profile.id}
/> */}
<Stack spacing={"lg"}>
<Center>
<Title order={5} align="center">
{dataVote?.title}
</Title>
</Center>
<Text>{dataVote?.deskripsi}</Text>
<Stack spacing={0}> <Stack spacing={0}>
<Stack align="center" spacing={"xs"}> <Stack align="center" spacing={"xs"}>
<Text fz={10} fw={"bold"}> <Text fz={10} fw={"bold"}>
Batas Voting Batas Voting
</Text> </Text>
<Badge <Badge
styles={{ styles={{
root: { root: {
backgroundColor: AccentColor.blue, backgroundColor: AccentColor.blue,
border: `1px solid ${AccentColor.skyblue}`, border: `1px solid ${AccentColor.skyblue}`,
color: "white", color: "white",
width: "80%", width: "80%",
}, },
}} }}
> >
<Group>
<Text> <Text>
{dataVote?.awalVote.toLocaleDateString(["id-ID"], { {data
dateStyle: "medium", ? moment(data.awalVote).format("ll")
})} : "tgl awal voting"}{" "}
-{" "}
{data
? moment(data.akhirVote).format("ll")
: "tgl akhir voting"}
</Text> </Text>
<Text>-</Text> </Badge>
<Text> </Stack>
{dataVote?.akhirVote.toLocaleDateString(["id-ID"], {
dateStyle: "medium",
})}
</Text>
</Group>
</Badge>
</Stack> </Stack>
</Stack> </Stack>
</Stack> {isKontributor ? (
{isKontributor ? ( <Stack
<Stack align="center"
align="center" spacing={0}
spacing={0} style={{
style={{ color: "white",
color: "white",
}}
>
<Text mb={"sm"} fw={"bold"} fz={"xs"}>
Pilihan anda:
</Text>
<Badge size="lg">
{pilihanKontributor.Voting_DaftarNamaVote.value}
</Badge>
</Stack>
) : (
<Stack
spacing={"xl"}
style={{
color: "white",
}}
>
<Radio.Group
styles={{
label: {
color: "white",
},
}} }}
value={votingNameId}
onChange={(val) => {
setVotingNameId(val);
}}
label={
<Text mb={"sm"} fw={"bold"} fz={"xs"}>
Pilihan :
</Text>
}
> >
<Stack px={"md"}> <Text mb={"sm"} fw={"bold"} fz={"xs"}>
{dataVote?.Voting_DaftarNamaVote.map((v) => ( Pilihan anda:
<Box key={v.id}> </Text>
<Radio <Badge size="lg">{pilihanKontributor}</Badge>
disabled={ </Stack>
moment(dataVote?.awalVote).diff(today, "hours") < 0 ) : (
? false <Stack
: true spacing={"xl"}
} style={{
color="yellow" color: "white",
styles={{ label: { color: "white" } }} }}
label={v.value} >
value={v.id} <Radio.Group
/> styles={{
</Box> label: {
))} color: "white",
</Stack> },
</Radio.Group> }}
<Center> value={pilihanVotingId}
{_.isEmpty(votingNameId) ? ( onChange={(val) => {
<Button radius={"xl"} disabled> setPilihanVotingId(val);
Vote }}
</Button> label={
) : ( <Text mb={"sm"} fw={"bold"} fz={"xs"}>
Pilihan :
</Text>
}
>
<Stack px={"md"}>
{_.isEmpty(data?.Voting_DaftarNamaVote) ? (
<Text>Pilihan Tidak Ditemukan</Text>
) : (
data?.Voting_DaftarNamaVote.map((v) => (
<Box key={v.id}>
<Radio
disabled={
moment(data?.awalVote).diff(today, "hours") < 0
? false
: true
}
color="yellow"
styles={{ label: { color: "white" } }}
label={v.value}
value={v.id}
/>
</Box>
))
)}
</Stack>
</Radio.Group>
<Center>
<Button <Button
style={{
transition: "all 0.3s ease-in-out",
}}
disabled={pilihanVotingId == ""}
radius={"xl"} radius={"xl"}
onClick={() =>
onVote(
votingNameId,
dataVote?.id as any,
setData,
userLoginId
)
}
bg={MainColor.yellow} bg={MainColor.yellow}
color="yellow" color="yellow"
c={"black"} c={"black"}
onClick={() => onVote()}
> >
Vote Vote
</Button> </Button>
)} </Center>
</Center> </Stack>
</Stack> )}
)} </Stack>
</Stack> </ComponentGlobal_CardStyles>
</ComponentGlobal_CardStyles>
<ComponentVote_HasilVoting data={hasil as any} />
</Stack>
</> </>
); );
} }
async function onVote(
pilihanVotingId: string,
voteId: string,
setData: any,
userLoginId: string
) {
const res = await Vote_funCreateHasil(pilihanVotingId, voteId);
if (res.status === 201) {
await voting_funGetOneVotingbyId(voteId).then((val) => {
setData(val);
ComponentGlobal_NotifikasiBerhasil(res.message);
});
if (userLoginId !== res?.data?.Voting?.authorId) {
const dataNotifikasi: IRealtimeData = {
appId: res?.data?.Voting?.id as string,
userId: res?.data?.Voting?.authorId as string,
pesan: res?.pilihan as string,
status: "Voting Masuk",
kategoriApp: "VOTING",
title: "User lain telah melakukan voting !",
};
const createNotifikasi = await notifikasiToUser_funCreate({
data: dataNotifikasi as any,
});
if (createNotifikasi.status === 201) {
WibuRealtime.setData({
type: "notification",
pushNotificationTo: "USER",
dataMessage: dataNotifikasi,
});
}
}
} else {
ComponentGlobal_NotifikasiPeringatan(res.message);
}
}

View File

@@ -4,10 +4,13 @@ import prisma from "@/app/lib/prisma";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
export async function Vote_funCreateHasil( export async function Vote_funCreateHasil({
pilihanVotingId: string, pilihanVotingId,
votingId: string votingId,
) { }: {
pilihanVotingId: string;
votingId: string;
}) {
const userLoginId = await funGetUserIdByToken(); const userLoginId = await funGetUserIdByToken();
const get = await prisma.voting_DaftarNamaVote.findFirst({ const get = await prisma.voting_DaftarNamaVote.findFirst({