Merge pull request #259 from bipproduction/bagas/30-jan-25

Bagas/30 jan 25
This commit is contained in:
Bagasbanuna02
2025-01-31 07:42:19 +08:00
committed by GitHub
5 changed files with 361 additions and 205 deletions

View File

@@ -0,0 +1,143 @@
import { prisma } from "@/app/lib";
import backendLogger from "@/util/backendLogger";
import _ from "lodash";
import { NextResponse } from "next/server";
export async function GET(
request: Request,
{ params }: { params: { status: string } }
) {
const method = request.method;
if (method !== "GET") {
return NextResponse.json(
{ success: false, message: "Method not allowed" },
{ status: 405 }
);
}
const { status } = params;
const { searchParams } = new URL(request.url);
const search = searchParams.get("search");
const page = searchParams.get("page");
const takeData = 1;
const skipData = Number(page) * takeData - takeData;
try {
let fixData;
const fixStatus = _.startCase(status);
if (!page && !search) {
fixData = await prisma.event.findMany({
orderBy: {
createdAt: "desc",
},
where: {
active: true,
isArsip: false,
EventMaster_Status: {
name: fixStatus,
},
},
});
} else if (!page && search) {
fixData = await prisma.event.findMany({
orderBy: {
createdAt: "desc",
},
where: {
active: true,
isArsip: false,
EventMaster_Status: {
name: fixStatus,
},
title: {
contains: search,
mode: "insensitive",
},
},
});
} else if (page && !search) {
const data = await prisma.event.findMany({
take: takeData,
skip: skipData,
orderBy: {
createdAt: "desc",
},
where: {
active: true,
isArsip: false,
EventMaster_Status: {
name: fixStatus,
},
},
});
const nCount = await prisma.event.count({
where: {
active: true,
eventMaster_StatusId: "1",
isArsip: false,
},
});
fixData = {
data: data,
nPage: _.ceil(nCount / takeData),
};
} else if (page && search) {
const data = await prisma.event.findMany({
take: takeData,
skip: skipData,
orderBy: {
createdAt: "desc",
},
where: {
active: true,
isArsip: false,
EventMaster_Status: {
name: fixStatus,
},
title: {
contains: search,
mode: "insensitive",
},
},
});
const nCount = await prisma.event.count({
where: {
active: true,
eventMaster_StatusId: "1",
isArsip: false,
title: {
contains: search,
mode: "insensitive",
},
},
});
fixData = {
data: data,
nPage: _.ceil(nCount / takeData),
};
}
return NextResponse.json({
success: true,
message: `Success get data table event ${status}`,
data: fixData,
});
} catch (error) {
backendLogger.error("Error get data table event dashboard >>", error);
return NextResponse.json(
{
success: false,
message: "Failed get data table event dashboard",
reason: (error as Error).message,
},
{ status: 500 }
);
} finally {
await prisma.$disconnect();
}
}

View File

@@ -2,6 +2,7 @@ export {
apiGetEventStatusCountDashboard, apiGetEventStatusCountDashboard,
apiGetEventTipeAcara, apiGetEventTipeAcara,
apiGetEventRiwayatCount, apiGetEventRiwayatCount,
apiGetDataEventByStatus,
}; };
const apiGetEventStatusCountDashboard = async ({ const apiGetEventStatusCountDashboard = async ({
@@ -26,25 +27,25 @@ const apiGetEventStatusCountDashboard = async ({
}; };
const apiGetEventRiwayatCount = async () => { const apiGetEventRiwayatCount = 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/event/dashboard/riwayat`, { const response = await fetch(`/api/admin/event/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 apiGetEventTipeAcara = async () => { const apiGetEventTipeAcara = 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/event/dashboard/tipe-acara`, { const response = await fetch(`/api/admin/event/dashboard/tipe-acara`, {
method: "GET", method: "GET",
@@ -54,7 +55,33 @@ const apiGetEventTipeAcara = async () => {
"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 apiGetDataEventByStatus = async ({
status,
page,
search,
}: {
status: "Publish" | "Review" | "Reject";
page: string;
search: string;
}) => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null);
const isPage = page ? `?page=${page}` : "";
const isSearch = search ? `&search=${search}` : "";
const respone = await fetch(`/api/admin/event/${status}${isPage}${isSearch}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await respone.json().catch(() => null);
};

View File

@@ -2,11 +2,9 @@ import { AdminEvent_TablePublish } from "@/app_modules/admin/event";
import { adminEvent_funGetListPublish } from "@/app_modules/admin/event/fun"; import { adminEvent_funGetListPublish } from "@/app_modules/admin/event/fun";
async function Page() { async function Page() {
const listPublish = await adminEvent_funGetListPublish({ page: 1 });
return ( return (
<> <>
<AdminEvent_TablePublish listPublish={listPublish as any} /> <AdminEvent_TablePublish />
</> </>
); );
} }

View File

@@ -1,12 +1,12 @@
"use client"; "use client";
import { apiGetDataEventByStatus } from "@/app/dev/admin/event/_lib/api_fecth_admin_event";
import { RouterAdminEvent } from "@/app/lib/router_admin/router_admin_event"; import { RouterAdminEvent } from "@/app/lib/router_admin/router_admin_event";
import { MODEL_EVENT } from "@/app_modules/event/_lib/interface"; import { MODEL_EVENT } from "@/app_modules/event/_lib/interface";
import { clientLogger } from "@/util/clientLogger";
import { import {
Box,
Button, Button,
Center, Center,
Group,
Pagination, Pagination,
Paper, Paper,
ScrollArea, ScrollArea,
@@ -15,87 +15,115 @@ import {
Table, Table,
Text, Text,
TextInput, TextInput,
Title,
} from "@mantine/core"; } from "@mantine/core";
import { IconCircleCheck, IconDetails, IconEyeCheck, IconSearch } from "@tabler/icons-react"; import { useEffect } from "react";
import { IconEyeCheck, IconSearch } from "@tabler/icons-react";
import _ from "lodash"; import _ from "lodash";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import QRCode from "react-qr-code";
import { ComponentAdminGlobal_TitlePage } from "../../_admin_global/_component";
import ComponentAdminGlobal_HeaderTamplate from "../../_admin_global/header_tamplate"; import ComponentAdminGlobal_HeaderTamplate from "../../_admin_global/header_tamplate";
import { adminEvent_funGetListPublish } from "../fun"; import { adminEvent_funGetListPublish } from "../fun";
import QRCode from "react-qr-code"; import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { useShallowEffect } from "@mantine/hooks";
import { ComponentAdminGlobal_TitlePage } from "../../_admin_global/_component";
import { MainColor } from "@/app_modules/_global/color";
import { AdminColor } from "@/app_modules/_global/color/color_pallet";
export default function AdminEvent_TablePublish({ export default function AdminEvent_TablePublish() {
listPublish,
}: {
listPublish: any;
}) {
return ( return (
<> <Stack>
<Stack> <ComponentAdminGlobal_HeaderTamplate name="Event" />
<ComponentAdminGlobal_HeaderTamplate name="Event" /> <TableStatus />
<TableStatus listPublish={listPublish} /> </Stack>
</Stack>
</>
); );
} }
function TableStatus({ listPublish }: { listPublish: any }) { function TableStatus() {
const router = useRouter(); const router = useRouter();
const [data, setData] = useState<MODEL_EVENT[]>(listPublish.data); const [data, setData] = useState<MODEL_EVENT[] | null>(null);
const [isNPage, setNPage] = useState(listPublish.nPage); const [isNPage, setNPage] = useState<number>(1);
const [isActivePage, setActivePage] = useState(1); const [activePage, setActivePage] = useState(1);
const [isSearch, setSearch] = useState(""); const [isSearch, setSearch] = useState("");
const [eventId, setEventId] = useState(""); const [eventId, setEventId] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [origin, setOrigin] = useState(""); const [origin, setOrigin] = useState("");
useShallowEffect(() => { useEffect(() => {
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
// console.log(window.location.origin);
setOrigin(window.location.origin); setOrigin(window.location.origin);
} }
}, [setOrigin]); }, []);
// async function onLoadOrigin(setOrigin: any) { useEffect(() => {
// const res = await fetch("/api/origin-url"); const loadInitialData = async () => {
// const result = await res.json(); try {
// setOrigin(result.origin); const response = await apiGetDataEventByStatus({
// } status: "Publish",
page: `${activePage}`,
search: isSearch,
});
async function onSearch(s: string) { console.log("Received data:", response.data.data);
setSearch(s); console.log("Received nPage:", response.data.nPage);
const loadData = await adminEvent_funGetListPublish({
page: 1, if (response && Array.isArray(response.data)) {
search: s, setData(response.data.data);
}); setNPage(response.data.nPage || 1);
setData(loadData.data as any); } else {
setNPage(loadData.nPage); console.error("Invalid data format received:", response);
setData([]);
}
} catch (error) {
clientLogger.error("Error get data table publish", error);
setData([]);
}
};
loadInitialData();
}, [activePage, isSearch]);
const onSearch = async (searchTerm: string) => {
setSearch(searchTerm);
setActivePage(1);
};
const onPageClick = (page: number) => {
setActivePage(page);
};
const handleDownloadQR = (id: string, title: string) => {
const svg: any = document.getElementById(id);
const svgData = new XMLSerializer().serializeToString(svg);
const canvas = document.createElement("canvas");
const ctx: any = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const pngFile = canvas.toDataURL("image/png");
const downloadLink = document.createElement("a");
downloadLink.download = `QRCode ${title}`;
downloadLink.href = `${pngFile}`;
downloadLink.click();
};
img.src = `data:image/svg+xml;base64,${btoa(svgData)}`;
};
if (!data) {
return <CustomSkeleton height={100} width="100%" />;
} }
async function onPageClick(p: any) { const renderTableBody = () => {
setActivePage(p); if (!Array.isArray(data) || data.length === 0) {
const loadData = await adminEvent_funGetListPublish({ return (
search: isSearch, <tr>
page: p, <td colSpan={12}>
}); <Center>Belum Ada Data</Center>
setData(loadData.data as any); </td>
setNPage(loadData.nPage); </tr>
} );
}
const TableRows = _.isEmpty(data) ? ( return data.map((e, i) => (
<tr>
<td colSpan={12}>
<Center>Belum Ada Data</Center>
</td>
</tr>
) : (
data.map((e, i) => (
<tr key={i}> <tr key={i}>
<td> <td>
<Center w={200}> <Center w={200}>
@@ -108,28 +136,9 @@ function TableStatus({ listPublish }: { listPublish: any }) {
</td> </td>
<td> <td>
<Center w={200}> <Center w={200}>
<input <Button onClick={() => handleDownloadQR(e.id, e.title)}>
type="button" Download QR
value="Download QR" </Button>
onClick={() => {
const svg: any = document.getElementById(e.id);
const svgData = new XMLSerializer().serializeToString(svg);
const canvas = document.createElement("canvas");
const ctx: any = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const pngFile = canvas.toDataURL("image/png");
const downloadLink = document.createElement("a");
downloadLink.download = `QRCode ${e.title}`;
downloadLink.href = `${pngFile}`;
downloadLink.click();
};
img.src = `data:image/svg+xml;base64,${btoa(svgData)}`;
}}
/>
</Center> </Center>
</td> </td>
<td> <td>
@@ -152,19 +161,17 @@ function TableStatus({ listPublish }: { listPublish: any }) {
<Text>{e.EventMaster_TipeAcara.name}</Text> <Text>{e.EventMaster_TipeAcara.name}</Text>
</Center> </Center>
</td> </td>
<td> <td>
<Center w={200}> <Center w={200}>
<Text align="center"> <Text align="center">
{" "}
{new Intl.DateTimeFormat("id-ID", { {new Intl.DateTimeFormat("id-ID", {
dateStyle: "full", dateStyle: "full",
}).format(e?.tanggal)} }).format(new Date(e?.tanggal))}
,{" "} ,{" "}
<Text span inherit> <Text span inherit>
{new Intl.DateTimeFormat("id-ID", { {new Intl.DateTimeFormat("id-ID", {
timeStyle: "short", timeStyle: "short",
}).format(e?.tanggal)} }).format(new Date(e?.tanggal))}
</Text> </Text>
</Text> </Text>
</Center> </Center>
@@ -172,20 +179,18 @@ function TableStatus({ listPublish }: { listPublish: any }) {
<td> <td>
<Center w={200}> <Center w={200}>
<Text align="center"> <Text align="center">
{" "}
{new Intl.DateTimeFormat("id-ID", { {new Intl.DateTimeFormat("id-ID", {
dateStyle: "full", dateStyle: "full",
}).format(e?.tanggalSelesai)} }).format(new Date(e?.tanggalSelesai))}
,{" "} ,{" "}
<Text span inherit> <Text span inherit>
{new Intl.DateTimeFormat("id-ID", { {new Intl.DateTimeFormat("id-ID", {
timeStyle: "short", timeStyle: "short",
}).format(e?.tanggalSelesai)} }).format(new Date(e?.tanggalSelesai))}
</Text> </Text>
</Text> </Text>
</Center> </Center>
</td> </td>
<td> <td>
<Center w={400}> <Center w={400}>
<Spoiler <Spoiler
@@ -197,17 +202,14 @@ function TableStatus({ listPublish }: { listPublish: any }) {
</Spoiler> </Spoiler>
</Center> </Center>
</td> </td>
<td> <td>
<Button <Button
loaderPosition="center" loaderPosition="center"
loading={ loading={loading && e.id === eventId}
e.id === eventId ? (loading === true ? true : false) : false color="green"
} leftIcon={<IconEyeCheck size={20} />}
color={"green"} radius="xl"
leftIcon={<IconEyeCheck size={20}/>} onClick={() => {
radius={"xl"}
onClick={async () => {
setEventId(e.id); setEventId(e.id);
setLoading(true); setLoading(true);
router.push(RouterAdminEvent.detail_publish + e.id); router.push(RouterAdminEvent.detail_publish + e.id);
@@ -217,104 +219,81 @@ function TableStatus({ listPublish }: { listPublish: any }) {
</Button> </Button>
</td> </td>
</tr> </tr>
)) ));
); };
return ( return (
<> <Stack spacing="xs" h="100%">
<Stack spacing={"xs"} h={"100%"}> <ComponentAdminGlobal_TitlePage
<ComponentAdminGlobal_TitlePage name="Publish"
name="Publish" color="green"
color={AdminColor.green} component={
component={
<TextInput
icon={<IconSearch size={20} />}
radius={"xl"}
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 <TextInput
icon={<IconSearch size={20} />} icon={<IconSearch size={20} />}
radius={"xl"} radius="xl"
placeholder="Masukan judul" placeholder="Masukan judul"
onChange={(val) => { value={isSearch}
onSearch(val.currentTarget.value); onChange={(e) => onSearch(e.currentTarget.value)}
}}
/> />
</Group> */} }
/>
<Paper p={"md"} withBorder shadow="lg" h={"80vh"}> <Paper p="md" withBorder shadow="lg" h="80vh">
<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}
striped striped
highlightOnHover highlightOnHover
> >
<thead> <thead>
<tr> <tr>
<th> <th>
<Center>QR Code</Center> <Center>QR Code</Center>
</th> </th>
<th> <th>
<Center>Download QR</Center> <Center>Download QR</Center>
</th> </th>
<th>
<Center>Username</Center>
</th>
<th>
<Center>Judul</Center>
</th>
<th>
<Center>Lokasi</Center>
</th>
<th>
<Center>Tipe Acara</Center>
</th>
<th>
<Center>Tanggal & Waktu Mulai</Center>
</th>
<th>
<Center>Tanggal & Waktu Selesai</Center>
</th>
<th>
<Center>Deskripsi</Center>
</th>
<th>
<Center>Aksi</Center>
</th>
</tr>
</thead>
<tbody>{renderTableBody()}</tbody>
</Table>
</ScrollArea>
<th> <Center mt="xl">
<Center>Username</Center> <Pagination
</th> value={activePage}
<th> total={isNPage}
<Center>Judul</Center> onChange={onPageClick}
</th> />
<th> </Center>
<Center>Lokasi</Center> </Paper>
</th> </Stack>
<th>
<Center>Tipe Acara</Center>
</th>
<th>
<Center>Tanggal & Waktu Mulai</Center>
</th>
<th>
<Center>Tanggal & Waktu Selesai</Center>
</th>
<th>
<Center>Deskripsi</Center>
</th>
<th>
<Center>Aksi</Center>
</th>
</tr>
</thead>
<tbody>{TableRows}</tbody>
</Table>
</ScrollArea>
<Center mt={"xl"}>
<Pagination
value={isActivePage}
total={isNPage}
onChange={(val) => {
onPageClick(val);
}}
/>
</Center>
</Paper>
</Stack>
</>
); );
} }

9
test/coba.test.ts Normal file
View File

@@ -0,0 +1,9 @@
import { prisma } from "@/app/lib";
import { describe, test, expect } from "bun:test";
describe("coba test", () => {
test("coba", async () => {
const user = await prisma.user.findMany();
expect(user).not.toBeEmpty();
});
});