fix admin

deskripsi:
- fix user access to API
This commit is contained in:
2025-02-24 12:17:06 +08:00
parent a6a27c239a
commit 8f80419eb2
5 changed files with 231 additions and 101 deletions

View File

@@ -0,0 +1,72 @@
import _ from "lodash";
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
export async function GET(request: Request) {
try {
let fixData;
const { searchParams } = new URL(request.url);
const search = searchParams.get("search");
const page = searchParams.get("page");
const takeData = 10;
const skipData = Number(page) * takeData - takeData;
if (!page) {
fixData = await prisma.user.findMany({
where: {
masterUserRoleId: "1",
username: {
contains: search || "",
mode: "insensitive",
},
},
});
} else {
const getData = await prisma.user.findMany({
skip: skipData,
take: takeData,
orderBy: {
active: "asc",
},
where: {
masterUserRoleId: "1",
username: {
contains: search || "",
mode: "insensitive",
},
},
});
const nCount = await prisma.user.count({
where: {
masterUserRoleId: "1",
username: {
contains: search || "",
mode: "insensitive",
},
},
});
fixData = {
data: getData,
nPage: _.ceil(nCount / takeData),
};
}
return NextResponse.json(
{
success: true,
message: "Success get data",
data: fixData,
},
{
status: 200,
}
);
} catch (error) {
return NextResponse.json(
{ success: false, message: "Internal Server Error" },
{ status: 500 }
);
}
}

View File

@@ -2,11 +2,11 @@ import { AdminUserAccess_View } from "@/app_modules/admin/user-access";
import adminUserAccess_getListUser from "@/app_modules/admin/user-access/fun/get/get_list_all_user"; import adminUserAccess_getListUser from "@/app_modules/admin/user-access/fun/get/get_list_all_user";
export default async function Page() { export default async function Page() {
const listUser = await adminUserAccess_getListUser({ page: 1 }); // const listUser = await adminUserAccess_getListUser({ page: 1 });
return ( return (
<> <>
<AdminUserAccess_View listUser={listUser as any} /> <AdminUserAccess_View />
</> </>
); );
} }

View File

@@ -0,0 +1,45 @@
export { apiGetUserAccess };
const apiGetUserAccess = async ({
page,
search,
}: {
page: string;
search?: string;
}) => {
try {
// Fetch token from cookie
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) {
console.error("No token found");
return null;
}
// Fetch data
const isPage = `?page=${page}`;
const isSearch = search ? `&search=${search}` : "";
const response = await fetch(`/api/admin/user${isPage}${isSearch}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Error get data user access:",
errorData?.message || "Unknown error"
);
return null;
}
return response.json();
} catch (error) {
console.error("Error get data user access:", error);
throw error;
}
};

View File

@@ -10,41 +10,50 @@ export default async function adminUserAccess_funEditAccess(
value: boolean, value: boolean,
nomor?: string nomor?: string
) { ) {
const updt = await prisma.user.update({ try {
where: { const updt = await prisma.user.update({
id: userId, where: {
}, id: userId,
data: { },
active: value, data: {
}, active: value,
}); },
});
const headersList = headers(); const headersList = headers();
const host = headersList.get("host"); const host = headersList.get("host");
const protocol = headersList.get("x-forwarded-proto") || "http"; const protocol = headersList.get("x-forwarded-proto") || "http";
const path = headersList.get("x-invoke-path"); const path = headersList.get("x-invoke-path");
const baseUrl = `${protocol}://${host}`; const baseUrl = `${protocol}://${host}`;
// const fullUrl = `${protocol}://${host}${path}`; // const fullUrl = `${protocol}://${host}${path}`;
if (value === true) { if (value === true) {
const message = `Hallo rekan HIPMI, Anda telah diberikan akses ke HIPMI Apps. Silakan mulai jelajahi fitur-fitur yang tersedia melalui link berikut: ${baseUrl}`; const message = `Hallo rekan HIPMI, Anda telah diberikan akses ke HIPMI Apps. Silakan mulai jelajahi fitur-fitur yang tersedia melalui link berikut: ${baseUrl}`;
const encodedMessage = encodeURIComponent(message); const encodedMessage = encodeURIComponent(message);
const res = await fetch( const res = await fetch(
`https://wa.wibudev.com/code?nom=${nomor}&text=${encodedMessage} `https://wa.wibudev.com/code?nom=${nomor}&text=${encodedMessage}
` `
); );
if (!res.ok) { if (!res.ok) {
backendLogger.error("Error send message", res); backendLogger.error("Error send message", res);
}
const result = await res.json();
backendLogger.info("Success send message", result);
} }
const result = await res.json(); if (!updt) return { status: 400, message: "Update gagal" };
revalidatePath("/dev/admin/user-access");
backendLogger.info("Success send message", result); return { status: 200, message: "Update berhasil" };
} catch (error) {
backendLogger.error("Error update user", error);
return {
status: 500,
message: "Error udpate user",
error: (error as Error).message,
};
} }
if (!updt) return { status: 400, message: "Update gagal" };
revalidatePath("/dev/admin/user-access");
return { status: 200, message: "Update berhasil" };
} }

View File

@@ -24,28 +24,58 @@ import { WibuRealtime } from "wibu-pkg";
import { gs_access_user, IRealtimeData } from "@/lib/global_state"; import { gs_access_user, IRealtimeData } from "@/lib/global_state";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { AdminColor } from "@/app_modules/_global/color/color_pallet"; import { AdminColor } from "@/app_modules/_global/color/color_pallet";
import { useShallowEffect } from "@mantine/hooks";
import { apiGetUserAccess } from "../_lib/api_fetch_user_access";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function AdminUserAccess_View({ listUser }: { listUser: any }) { export default function AdminUserAccess_View() {
const [data, setData] = useState<MODEL_USER[]>(listUser.data); const [data, setData] = useState<MODEL_USER[]>([]);
const [nPage, setNPage] = useState(1);
const [isActivePage, setActivePage] = useState(1); const [isActivePage, setActivePage] = useState(1);
const [isNPage, setNPage] = useState(listUser.nPage);
const [isSearch, setSearch] = useState(""); const [isSearch, setSearch] = useState("");
const [isLoadingAccess, setIsLoadingAccess] = useState(false); const [isLoadingAccess, setIsLoadingAccess] = useState(false);
const [isLoadingDelete, setIsLoadingDelete] = useState(false); const [isLoadingDelete, setIsLoadingDelete] = useState(false);
const [userId, setUserId] = useState(""); const [userId, setUserId] = useState("");
useShallowEffect(() => {
handleLoadData();
}, [isActivePage, isSearch]);
const handleLoadData = async () => {
try {
const response = await apiGetUserAccess({
page: `${isActivePage}`,
search: isSearch,
});
if (response.success) {
setData(response.data.data);
setNPage(response.data.nPage);
} else {
setData([]);
}
} catch (error) {
console.error("Error get user access", error);
setData([]);
}
};
async function onSearch(s: any) {
setSearch(s);
}
async function onPageClick(p: any) {
setActivePage(p);
}
async function onAccess(id: string, nomor: string) { async function onAccess(id: string, nomor: string) {
try { try {
setUserId(id); setUserId(id);
setIsLoadingAccess(true); setIsLoadingAccess(true);
await adminUserAccess_funEditAccess(id, true, nomor).then(async (res) => { await adminUserAccess_funEditAccess(id, true, nomor).then(async (res) => {
if (res.status === 200) { if (res.status === 200) {
const value = await adminUserAccess_getListUser({ handleLoadData();
page: 1,
search: isSearch,
});
setData(value.data as any);
setNPage(value.nPage);
const dataNotifikasi: IRealtimeData = { const dataNotifikasi: IRealtimeData = {
status: true as any, status: true as any,
@@ -78,12 +108,8 @@ export default function AdminUserAccess_View({ listUser }: { listUser: any }) {
setIsLoadingDelete(true); setIsLoadingDelete(true);
await adminUserAccess_funEditAccess(id, false).then(async (res) => { await adminUserAccess_funEditAccess(id, false).then(async (res) => {
if (res.status === 200) { if (res.status === 200) {
const value = await adminUserAccess_getListUser({ handleLoadData();
page: 1,
search: isSearch,
});
setData(value.data as any);
setNPage(value.nPage);
ComponentGlobal_NotifikasiBerhasil(res.message); ComponentGlobal_NotifikasiBerhasil(res.message);
} else { } else {
ComponentGlobal_NotifikasiGagal(res.message); ComponentGlobal_NotifikasiGagal(res.message);
@@ -97,27 +123,6 @@ export default function AdminUserAccess_View({ listUser }: { listUser: any }) {
} }
} }
async function onSearch(s: any) {
setSearch(s);
setActivePage(1);
const loadData = await adminUserAccess_getListUser({
search: s,
page: 1,
});
setData(loadData.data as any);
setNPage(loadData.nPage);
}
async function onPageClick(p: any) {
setActivePage(p);
const loadData = await adminUserAccess_getListUser({
search: isSearch,
page: p,
});
setData(loadData.data as any);
setNPage(loadData.nPage);
}
const tableBody = data.map((e, i) => ( const tableBody = data.map((e, i) => (
<tr key={e.id}> <tr key={e.id}>
<td> <td>
@@ -181,40 +186,39 @@ export default function AdminUserAccess_View({ listUser }: { listUser: any }) {
/> />
</Group> </Group>
<Paper p={"md"} bg={AdminColor.softBlue} h={"80vh"}> {!data.length ? (
<ScrollArea w={"100%"} h={"90%"}> <CustomSkeleton height={"80vh"} width="100%" />
<Table ) : (
verticalSpacing={"xs"} <Paper p={"md"} bg={AdminColor.softBlue} h={"80vh"}>
horizontalSpacing={"md"} <ScrollArea w={"100%"} h={"90%"}>
p={"md"} <Table verticalSpacing={"xs"} horizontalSpacing={"md"} p={"md"}>
<thead>
> <tr>
<thead> <th>
<tr> <Center c={AdminColor.white}>Username</Center>
<th> </th>
<Center c={AdminColor.white}>Username</Center> <th>
</th> <Center c={AdminColor.white}>Nomor</Center>
<th> </th>
<Center c={AdminColor.white}>Nomor</Center> <th>
</th> <Center c={AdminColor.white}>Aksi</Center>
<th> </th>
<Center c={AdminColor.white}>Aksi</Center> </tr>
</th> </thead>
</tr> <tbody>{tableBody}</tbody>
</thead> </Table>
<tbody>{tableBody}</tbody> </ScrollArea>
</Table> <Center mt={"xl"}>
</ScrollArea> <Pagination
<Center mt={"xl"}> value={isActivePage}
<Pagination total={nPage}
value={isActivePage} onChange={(val) => {
total={isNPage} onPageClick(val);
onChange={(val) => { }}
onPageClick(val); />
}} </Center>
/> </Paper>
</Center> )}
</Paper>
</Stack> </Stack>
</> </>
); );