From 806eba3e79ff7b6a5c2216d02fafb0b287314df9 Mon Sep 17 00:00:00 2001 From: Bagasbanuna02 Date: Thu, 6 Feb 2025 17:43:54 +0800 Subject: [PATCH] fix API deskripsi: - fix api user search --- logs/backend/combined-2025-02-06.log | 5 + logs/backend/error-2025-02-06.log | 1 + src/app/api/user/route.ts | 138 ++++++++++++++++-- src/app/dev/user-search/page.tsx | 5 +- .../component/button_delete_new.tsx | 6 +- .../component/api_fetch_user_search.ts | 25 ++++ .../user_search/component/ui_user_search.tsx | 133 ++++++++++++----- .../user_search/view_user_seach.tsx | 11 +- 8 files changed, 253 insertions(+), 71 deletions(-) create mode 100644 src/app_modules/user_search/component/api_fetch_user_search.ts diff --git a/logs/backend/combined-2025-02-06.log b/logs/backend/combined-2025-02-06.log index 46f87cc7..2323c80c 100644 --- a/logs/backend/combined-2025-02-06.log +++ b/logs/backend/combined-2025-02-06.log @@ -1 +1,6 @@ {"digest":"DYNAMIC_SERVER_USAGE","level":"error","message":"Error get data detail event: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error","stack":"Error: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error\n at Object.e_ [as staticGenerationBailout] (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:27571)\n at i (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32508)\n at Object.get (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32604)\n at GET (/Users/bagasbanuna/Documents/BIP/hipmi/.next/server/app/api/event/check-peserta/route.js:1:1219)\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:39715\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/server/lib/trace/tracer.js:121:36\n at NoopContextManager.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7057)\n at ContextAPI.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:516)\n at NoopTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18086)\n at ProxyTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18847)","timestamp":"2025-02-06T02:37:33.036Z"} +{"level":"info","message":"Server status code: 201","timestamp":"2025-02-06T03:37:03.672Z"} +{"level":"info","message":"Success upload profile_foto: {\"id\":\"cm6ssdnr40039hcxk2bl8e3zd\",\"name\":\"56FE8EB6-BB7C-45BF-8879-A3EB7C59CA58.PNG\",\"path\":\"/cm0ur1yxw000056nsjlr6187p/2025/02/06/56FE8EB6-BB7C-45BF-8879-A3EB7C59CA58.PNG\",\"mime\":\"image/png\",\"ext\":\".PNG\",\"desc\":null,\"size\":2531618,\"active\":true,\"createdAt\":\"2025-02-06T03:37:03.614Z\",\"updatedAt\":\"2025-02-06T03:37:03.616Z\",\"userId\":\"cm0ur1yxw000056nsjlr6187p\",\"dirId\":\"cm0x93rgo000jbp5tj8baoaus\"}","timestamp":"2025-02-06T03:37:03.688Z"} +{"level":"info","message":"Server status code: 200","timestamp":"2025-02-06T03:37:17.334Z"} +{"level":"info","message":"Success delete profile_foto","timestamp":"2025-02-06T03:37:17.336Z"} +{"digest":"DYNAMIC_SERVER_USAGE","level":"error","message":"Error get data detail event: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error","stack":"Error: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error\n at Object.e_ [as staticGenerationBailout] (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:27571)\n at i (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32508)\n at Object.get (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32604)\n at GET (/Users/bagasbanuna/Documents/BIP/hipmi/.next/server/app/api/event/check-peserta/route.js:1:1219)\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:39715\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/server/lib/trace/tracer.js:121:36\n at NoopContextManager.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7057)\n at ContextAPI.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:516)\n at NoopTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18086)\n at ProxyTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18847)","timestamp":"2025-02-06T09:41:38.297Z"} diff --git a/logs/backend/error-2025-02-06.log b/logs/backend/error-2025-02-06.log index 46f87cc7..93871a69 100644 --- a/logs/backend/error-2025-02-06.log +++ b/logs/backend/error-2025-02-06.log @@ -1 +1,2 @@ {"digest":"DYNAMIC_SERVER_USAGE","level":"error","message":"Error get data detail event: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error","stack":"Error: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error\n at Object.e_ [as staticGenerationBailout] (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:27571)\n at i (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32508)\n at Object.get (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32604)\n at GET (/Users/bagasbanuna/Documents/BIP/hipmi/.next/server/app/api/event/check-peserta/route.js:1:1219)\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:39715\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/server/lib/trace/tracer.js:121:36\n at NoopContextManager.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7057)\n at ContextAPI.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:516)\n at NoopTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18086)\n at ProxyTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18847)","timestamp":"2025-02-06T02:37:33.036Z"} +{"digest":"DYNAMIC_SERVER_USAGE","level":"error","message":"Error get data detail event: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error","stack":"Error: Dynamic server usage: Page couldn't be rendered statically because it used `request.url`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error\n at Object.e_ [as staticGenerationBailout] (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:27571)\n at i (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32508)\n at Object.get (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:32604)\n at GET (/Users/bagasbanuna/Documents/BIP/hipmi/.next/server/app/api/event/check-peserta/route.js:1:1219)\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:14:39715\n at /Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/server/lib/trace/tracer.js:121:36\n at NoopContextManager.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7057)\n at ContextAPI.with (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:516)\n at NoopTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18086)\n at ProxyTracer.startActiveSpan (/Users/bagasbanuna/Documents/BIP/hipmi/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18847)","timestamp":"2025-02-06T09:41:38.297Z"} diff --git a/src/app/api/user/route.ts b/src/app/api/user/route.ts index 06f4d909..8946e7f8 100644 --- a/src/app/api/user/route.ts +++ b/src/app/api/user/route.ts @@ -1,25 +1,131 @@ - -import { decrypt } from "@/app/(auth)/_lib/decrypt"; -import _ from "lodash"; -import { cookies } from "next/headers"; +import { prisma } from "@/app/lib"; +import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { NextResponse } from "next/server"; export const dynamic = "force-dynamic"; -export async function GET() { - const c = cookies().get(process.env.NEXT_PUBLIC_BASE_SESSION_KEY!); - - if (!c || !c?.value || _.isEmpty(c?.value) || _.isUndefined(c?.value)) { - return NextResponse.json({ status: 401, message: "Unauthorized" }); +export async function GET(request: Request) { + if (request.method !== "GET") { + return NextResponse.json( + { success: false, message: "Method Not Allowed" }, + { + status: 405, + } + ); } - const token = c.value; - const dataUser = await decrypt({ - token: token, - encodedKey: process.env.NEXT_PUBLIC_BASE_TOKEN_KEY!, - }); + try { + let fixData; + const userLoginId = await funGetUserIdByToken(); + if (userLoginId == null) { + return NextResponse.json( + { + success: false, + message: "Gagal mendapatkan data, user id tidak ada", + }, + { status: 500 } + ); + } - const id = dataUser?.id + 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; - return NextResponse.json({ status: 200, message: "OK", data: id }); + if (!page) { + fixData = await prisma.user.findMany({ + orderBy: { + createdAt: "desc", + }, + where: { + MasterUserRole: { + name: "User", + }, + active: true, + NOT: { + Profile: null, + }, + Profile: { + name: { + contains: search ? search : "", + mode: "insensitive", + }, + }, + }, + include: { + Profile: { + select: { + id: true, + name: true, + imageId: true, + }, + }, + }, + }); + } else { + fixData = await prisma.user.findMany({ + take: takeData, + skip: skipData, + orderBy: { + createdAt: "desc", + }, + where: { + MasterUserRole: { + name: "User", + }, + active: true, + Profile: { + name: { + contains: search ? search : "", + mode: "insensitive", + }, + }, + NOT: { + Profile: null, + }, + // OR: [ + // { + // NOT: { + // id: userLoginId as string, + // }, + // }, + // ], + }, + include: { + Profile: { + select: { + id: true, + name: true, + imageId: true, + }, + }, + }, + }); + } + + return NextResponse.json( + { + success: true, + message: "Berhasil mendapatkan data", + data: fixData, + }, + { + status: 200, + } + ); + } catch (error) { + return NextResponse.json( + { + success: false, + message: "Gagal mendapatkan data", + reason: (error as Error).message, + }, + { + status: 500, + } + ); + } finally { + await prisma.$disconnect(); + } } diff --git a/src/app/dev/user-search/page.tsx b/src/app/dev/user-search/page.tsx index 7305259d..f534479b 100644 --- a/src/app/dev/user-search/page.tsx +++ b/src/app/dev/user-search/page.tsx @@ -1,8 +1,5 @@ import { UserSearch_MainView } from "@/app_modules/user_search"; -import { userSearch_getAllUser } from "@/app_modules/user_search/fun/get/get_all_user"; export default async function Page() { - const listUser = await userSearch_getAllUser({ page: 1 }); - - return ; + return ; } diff --git a/src/app_modules/katalog/portofolio/component/button_delete_new.tsx b/src/app_modules/katalog/portofolio/component/button_delete_new.tsx index 342d0bbe..2b0f3a4c 100644 --- a/src/app_modules/katalog/portofolio/component/button_delete_new.tsx +++ b/src/app_modules/katalog/portofolio/component/button_delete_new.tsx @@ -1,9 +1,10 @@ -import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; +import { MainColor } from "@/app_modules/_global/color"; import { ComponentGlobal_NotifikasiBerhasil, ComponentGlobal_NotifikasiGagal, } from "@/app_modules/_global/notif_global"; import { UIGlobal_Modal } from "@/app_modules/_global/ui"; +import { clientLogger } from "@/util/clientLogger"; import { Button } from "@mantine/core"; import { useShallowEffect } from "@mantine/hooks"; import { IconTrash } from "@tabler/icons-react"; @@ -14,9 +15,6 @@ import { apiGetOnePortofolioById, } from "../lib/api_portofolio"; import { IDetailPortofolioBisnis } from "../lib/type_portofolio"; -import { MainColor } from "@/app_modules/_global/color"; -import { apiGetUserId } from "@/app_modules/_global/lib/api_user"; -import { clientLogger } from "@/util/clientLogger"; export default function ComponentPortofolio_ButtonDeleteNew({ userLoginId, diff --git a/src/app_modules/user_search/component/api_fetch_user_search.ts b/src/app_modules/user_search/component/api_fetch_user_search.ts new file mode 100644 index 00000000..513f788b --- /dev/null +++ b/src/app_modules/user_search/component/api_fetch_user_search.ts @@ -0,0 +1,25 @@ +export const apiGetUserSearch = async ({ + page, + search, +}: { + 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}` : ""; + console.log("page", page); + const response = await fetch(`/api/user${isPage}${isSearch}`, { + method: "GET", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "Access-Control-Allow-Origin": "*", + Authorization: `Bearer ${token}`, + }, + }); + + return await response.json().catch(() => null); +}; diff --git a/src/app_modules/user_search/component/ui_user_search.tsx b/src/app_modules/user_search/component/ui_user_search.tsx index 56b3c28c..ad879d56 100644 --- a/src/app_modules/user_search/component/ui_user_search.tsx +++ b/src/app_modules/user_search/component/ui_user_search.tsx @@ -3,8 +3,9 @@ import { RouterProfile } from "@/app/lib/router_hipmi/router_katalog"; import { ComponentGlobal_LoaderAvatar } from "@/app_modules/_global/component"; import ComponentGlobal_IsEmptyData from "@/app_modules/_global/component/is_empty_data"; -import ComponentGlobal_Loader from "@/app_modules/_global/component/loader"; +import CustomSkeleton from "@/app_modules/components/CustomSkeleton"; import { MODEL_USER } from "@/app_modules/home/model/interface"; +import { clientLogger } from "@/util/clientLogger"; import { ActionIcon, Box, @@ -16,26 +17,83 @@ import { Text, TextInput, } from "@mantine/core"; +import { useShallowEffect } from "@mantine/hooks"; import { IconChevronRight, IconSearch } from "@tabler/icons-react"; import _ from "lodash"; import { ScrollOnly } from "next-scroll-loader"; import { useRouter } from "next/navigation"; import { useState } from "react"; import { userSearch_getAllUser } from "../fun/get/get_all_user"; +import { apiGetUserSearch } from "./api_fetch_user_search"; -export function UserSearch_UiView({ listUser }: { listUser: MODEL_USER[] }) { - const [data, setData] = useState(listUser); +export function UserSearch_UiView() { + const [data, setData] = useState([]); const [activePage, setActivePage] = useState(1); - const [isSearch, setIsSearch] = useState(""); + const [searchQuery, setSearchQuery] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const [hasMore, setHasMore] = useState(true); - async function onSearch(name: string) { - setIsSearch(name); - const loadData = await userSearch_getAllUser({ - page: activePage, - search: name, - }); - setData(loadData as any); + useShallowEffect(() => { + const initializeData = async () => { + setIsLoading(true); + try { + const response = await apiGetUserSearch({ + page: "1", // Selalu mulai dari page 1 untuk search baru + search: searchQuery, + }); + + if (response?.data) { + // Reset allData dan mulai dengan data baru + setData(response.data); + setActivePage(1); + // Jika data yang diterima kosong atau kurang dari yang diharapkan, + // berarti tidak ada data lagi + setHasMore(response.data.length > 0); + } + } catch (error) { + clientLogger.error("Error initializing data", error); + setData([]); + setHasMore(false); + } finally { + setIsLoading(false); + } + }; + + initializeData(); + }, [searchQuery]); // Dependency hanya pada searchQuery + + function handleSearch(value: string) { + setSearchQuery(value); + // Reset state pagination setActivePage(1); + setHasMore(true); + } + + // Function untuk load more data (infinite scroll) + async function loadMoreData() { + if (!hasMore || isLoading) return null; + + try { + const nextPage = activePage + 1; + const response = await apiGetUserSearch({ + page: `${nextPage}`, + search: searchQuery, + }); + + if (response?.data && response.data.length > 0) { + setActivePage(nextPage); + // Update hasMore berdasarkan apakah ada data yang diterima + setHasMore(response.data.length > 0); + return response.data; + } else { + setHasMore(false); + return null; + } + } catch (error) { + clientLogger.error("Error loading more data", error); + setHasMore(false); + return null; + } } return ( @@ -46,35 +104,32 @@ export function UserSearch_UiView({ listUser }: { listUser: MODEL_USER[] }) { style={{ zIndex: 99 }} icon={} placeholder="Masukan nama pengguna " - onChange={(val) => onSearch(val.target.value)} + onChange={(val) => handleSearch(val.target.value)} + // disabled={isLoading} /> - - {_.isEmpty(data) ? ( - - ) : ( - ( -
- -
- )} - data={data} - setData={setData} - moreData={async () => { - const loadData = await userSearch_getAllUser({ - page: activePage + 1, - search: isSearch, - }); - setActivePage((val) => val + 1); - - return loadData; - }} - > - {(item) => } -
- )} -
+ {!data && isLoading ? ( + + ) : ( + + {_.isEmpty(data) ? ( + + ) : ( + ( +
+ +
+ )} + data={data} + setData={setData as any} + moreData={loadMoreData} + > + {(item) => } +
+ )} +
+ )} ); diff --git a/src/app_modules/user_search/view_user_seach.tsx b/src/app_modules/user_search/view_user_seach.tsx index ebcd2f81..83d6b8b4 100644 --- a/src/app_modules/user_search/view_user_seach.tsx +++ b/src/app_modules/user_search/view_user_seach.tsx @@ -1,22 +1,17 @@ -import { MODEL_USER } from "@/app_modules/home/model/interface"; import UIGlobal_LayoutHeaderTamplate from "../_global/ui/ui_header_tamplate"; import UIGlobal_LayoutTamplate from "../_global/ui/ui_layout_tamplate"; import { UserSearch_UiView } from "./component/ui_user_search"; -export default function UserSearch_MainView({ - listUser, -}: { - listUser: MODEL_USER[]; -}) { +export default function UserSearch_MainView() { return ( <> } > - + - {/*
{JSON.stringify(data, null, 2)}
*/} + ); }