Merge pull request #229 from bipproduction/fix/bug/middleware

Fix/bug/middleware
This commit is contained in:
Bagasbanuna02
2025-01-08 17:46:01 +08:00
committed by GitHub
26 changed files with 746 additions and 517 deletions

View File

@@ -4,8 +4,6 @@ import { NextResponse } from "next/server";
export async function DELETE(req: Request) { export async function DELETE(req: Request) {
const data = await req.json(); const data = await req.json();
console.log("data request =>", data);
const id = data.fileId; const id = data.fileId;
const dirId = data.dirId; const dirId = data.dirId;

View File

@@ -14,7 +14,8 @@ export async function GET(request: Request) {
const kategori = searchParams.get("cat") const kategori = searchParams.get("cat")
const status = searchParams.get("status") const status = searchParams.get("status")
const page = searchParams.get("page") const page = searchParams.get("page")
const dataSkip = Number(page) * 5 - 5; const dataTake = 10
const dataSkip = Number(page) * dataTake - dataTake;
if (kategori == "bursa") { if (kategori == "bursa") {
const data = await prisma.investasi.findMany({ const data = await prisma.investasi.findMany({
@@ -61,7 +62,7 @@ export async function GET(request: Request) {
// cek data yang lewat // cek data yang lewat
// klo ada, update status // klo ada, update status
const dataAwal = await prisma.investasi.findMany({ const dataAwal = await prisma.investasi.findMany({
take: 5, take: dataTake,
skip: dataSkip, skip: dataSkip,
orderBy: [ orderBy: [
{ {
@@ -100,28 +101,28 @@ export async function GET(request: Request) {
} }
const data = await prisma.investasi.findMany({ const data = await prisma.investasi.findMany({
take: 5, take: dataTake,
skip: dataSkip, skip: dataSkip,
orderBy: { orderBy: {
updatedAt: "desc", updatedAt: "desc",
}, },
where: { where: {
authorId: userLoginId, authorId: userLoginId,
masterStatusInvestasiId: status, masterStatusInvestasiId: status,
}, },
select: { select: {
id: true, id: true,
title: true, title: true,
targetDana: true, targetDana: true,
imageId: true, imageId: true,
countDown: true, countDown: true,
updatedAt: true, updatedAt: true,
MasterPencarianInvestor: { MasterPencarianInvestor: {
select: { select: {
name: true name: true,
} },
} },
} },
}); });
dataFix = data.map((v: any) => ({ dataFix = data.map((v: any) => ({

View File

@@ -1,24 +1,12 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { LayoutKatalogNew } from "@/app_modules/katalog/main"; import { LayoutKatalogNew } from "@/app_modules/katalog/main";
export default async function Layout({ children, params, }: { children: any; params: { id: string } }) { export default async function Layout({ children }: { children: any }) {
// const profileId = params.id; const userLoginId = await funGetUserIdByToken();
// const dataProfile = await Profile_getOneProfileAndUserById(profileId);
// const authorId = dataProfile?.userId;
// const userLoginId = await funGetUserIdByToken();
// const userRoleId = dataProfile?.User?.masterUserRoleId;
return ( return (
<> <>
{/* <KatalogLayout <LayoutKatalogNew userLoginId={userLoginId}>{children}</LayoutKatalogNew>
profileId={profileId}
userLoginId={userLoginId as string}
authorId={authorId as any}
userRoleId={userRoleId as string}
>
{children}
</KatalogLayout> */}
<LayoutKatalogNew>{children}</LayoutKatalogNew>
</> </>
); );
} }

View File

@@ -1,20 +1,14 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { PortofolioLayoutNew } from "@/app_modules/katalog/portofolio"; import { PortofolioLayoutNew } from "@/app_modules/katalog/portofolio";
export default async function Layout({ children, params, }: { children: any; params: { id: string }; }) { export default async function Layout({ children, }: { children: any; }) {
// let portoId = params.id; const userLoginId = await funGetUserIdByToken();
// const getPorto = await portofolio_getOneById(portoId);
// const userLoginId = await funGetUserIdByToken();
return ( return (
<> <>
{/* <PortofolioLayout <PortofolioLayoutNew userLoginId={userLoginId}>
portoId={portoId}
userLoginId={userLoginId as string}
authorId={getPorto?.Profile?.User?.id as any}
>
{children} {children}
</PortofolioLayout> */} </PortofolioLayoutNew>
<PortofolioLayoutNew>{children}</PortofolioLayoutNew>
</> </>
); );
} }

View File

@@ -1,6 +1,6 @@
const DIRECTORY_ID = { const DIRECTORY_ID = {
profile_foto: "cm0x93rgo000jbp5tj8baoaus", profile_foto: "cm5ni43ub001pxpug0qw4p11e",
profile_background: "cm0x93ze8000lbp5t1a8uc9wl", profile_background: "cm5ni4hnq001l12p9gpagxgtv",
portofolio_logo: "cm0yjl6ug000310njwmk6j0tx", portofolio_logo: "cm0yjl6ug000310njwmk6j0tx",
map_pin: "cm0yjq8up000710njv5klra32", map_pin: "cm0yjq8up000710njv5klra32",
map_image: "cm0yjqnxl000910njplqho07w", map_image: "cm0yjqnxl000910njplqho07w",

View File

@@ -22,29 +22,7 @@ export async function funGlobal_DeleteFileById({
return { success: false, message: data.message }; return { success: false, message: data.message };
} }
} catch (error) { } catch (error) {
console.error("Upload error:", error); clientLogger.error("Upload error:", error);
return { success: false, message: "An unexpected error occurred" }; return { success: false, message: "An unexpected error occurred" };
} }
// try {
// const res = await fetch(
// `https://wibu-storage.wibudev.com/api/files/${fileId}/delete`,
// {
// method: "DELETE",
// headers: {
// Authorization: `Bearer ${process.env.WS_APIKEY}`,
// },
// }
// );
// if (res.ok) {
// const hasil = await res.json();
// return { success: true, message: "File berhasil dihapus" };
// } else {
// const errorText = await res.json();
// return { success: false, message: errorText.message };
// }
// } catch (error) {
// console.error("Upload error:", error);
// return { success: false, message: "An unexpected error occurred" };
// }
} }

View File

@@ -1,19 +1,59 @@
export const apiGetAllDonasi = async (path?: string) => { export const apiGetAllDonasi = async (path?: string) => {
const response = await fetch(`/api/new/donasi${(path) ? path : ''}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/donasi${path ? path : ""}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
export const apiGetMasterDonasi = async (path?: string) => { export const apiGetMasterDonasi = async (path?: string) => {
const response = await fetch(`/api/new/donasi/master${(path) ? path : ''}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/donasi/master${path ? path : ""}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
export const apiGetAllDonasiSaya = async (path?: string) => { export const apiGetAllDonasiSaya = async (path?: string) => {
const response = await fetch(`/api/new/donasi/invoice${(path) ? path : ''}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/donasi/invoice${path ? path : ""}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
export const apiGetOneDonasiById = async (path: string, kategori: string) => { export const apiGetOneDonasiById = async (path: string, kategori: string) => {
const response = await fetch(`/api/new/donasi/${path}?cat=${kategori}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/donasi/${path}?cat=${kategori}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};

View File

@@ -18,10 +18,11 @@ import { Home_ComponentAvatarProfile } from "./comp_avatar_profile";
import { listMenuHomeFooter } from "./list_menu_home"; import { listMenuHomeFooter } from "./list_menu_home";
import { MainColor } from "@/app_modules/_global/color"; import { MainColor } from "@/app_modules/_global/color";
import { clientLogger } from "@/util/clientLogger"; import { clientLogger } from "@/util/clientLogger";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function FooterHome() { export default function FooterHome() {
const router = useRouter(); const router = useRouter();
const [dataUser, setDataUser] = useState<any>({}); const [dataUser, setDataUser] = useState<any | null>(null);
useShallowEffect(() => { useShallowEffect(() => {
cekUserLogin(); cekUserLogin();
@@ -36,7 +37,7 @@ export default function FooterHome() {
setDataUser(response.data); setDataUser(response.data);
} }
} catch (error) { } catch (error) {
clientLogger.error("Error get data profile",error); clientLogger.error("Error get data profile", error);
} }
} }
@@ -50,84 +51,101 @@ export default function FooterHome() {
bottom={0} bottom={0}
h={"9vh"} h={"9vh"}
> >
<SimpleGrid cols={listMenuHomeFooter.length + 1}> {dataUser?.profile === undefined || dataUser?.profile === null ? (
{listMenuHomeFooter.map((e) => ( <SimpleGrid cols={4}>
<Center h={"9vh"} key={e.id}> {Array.from(new Array(4)).map((_, i) => (
<Center h={"9vh"} key={i}>
<Stack align="center">
<CustomSkeleton radius={"lg"} height={40} w={40} />
</Stack>
</Center>
))}
</SimpleGrid>
) : (
<SimpleGrid cols={listMenuHomeFooter.length + 1}>
{listMenuHomeFooter.map((e) => (
<Center h={"9vh"} key={e.id}>
<Stack
align="center"
spacing={0}
onClick={() => {
if (
dataUser.profile === undefined ||
dataUser?.profile === null
) {
return null;
} else if (
dataUser.profile === undefined ||
dataUser?.profile === null
) {
router.push(RouterProfile.create, { scroll: false });
} else {
if (e.link == "") {
ComponentGlobal_NotifikasiPeringatan("Cooming Soon");
} else {
router.push(e.link, { scroll: false });
}
}
}}
>
<ActionIcon
radius={"xl"}
c={e.link === "" ? "gray" : MainColor.white}
variant="transparent"
>
{e.icon}
</ActionIcon>
<Text
lineClamp={1}
c={e.link === "" ? "gray" : MainColor.white}
fz={12}
>
{e.name}
</Text>
</Stack>
</Center>
))}
<Center h={"9vh"}>
<Stack <Stack
align="center" align="center"
spacing={0} spacing={2}
onClick={() => { onClick={() => {
if ( if (
dataUser.profile === undefined || dataUser.profile === undefined ||
dataUser?.profile === null dataUser?.profile === null
) {
return null;
} else if (
dataUser.profile === undefined ||
dataUser?.profile === null
) { ) {
router.push(RouterProfile.create, { scroll: false }); router.push(RouterProfile.create, { scroll: false });
} else { } else {
if (e.link == "") { router.push(
ComponentGlobal_NotifikasiPeringatan("Cooming Soon"); RouterProfile.katalogOLD + `${dataUser?.profile}`,
} else { {
router.push(e.link, { scroll: false }); scroll: false,
} }
);
} }
}} }}
> >
<ActionIcon <ActionIcon variant={"transparent"}>
radius={"xl"} {dataUser.profile === undefined ||
c={e.link === "" ? "gray" : MainColor.white} dataUser?.profile === null ? (
variant="transparent" <IconUserCircle color={MainColor.white} />
> ) : (
{e.icon} <Home_ComponentAvatarProfile
url={APIs.GET({
fileId: dataUser?.imageId as string,
size: "50",
})}
/>
)}
</ActionIcon> </ActionIcon>
<Text lineClamp={1} c={e.link === "" ? "gray" : MainColor.white} fz={12}> <Text fz={10} c={MainColor.white}>
{e.name} Profile
</Text> </Text>
</Stack> </Stack>
</Center> </Center>
))} </SimpleGrid>
)}
<Center h={"9vh"}>
<Stack
align="center"
spacing={2}
onClick={() => {
if (
dataUser.profile === undefined ||
dataUser?.profile === null
) {
router.push(RouterProfile.create, { scroll: false });
} else {
router.push(RouterProfile.katalogOLD + `${dataUser?.profile}`, {
scroll: false,
});
}
}}
>
<ActionIcon
variant={"transparent"}>
{dataUser.profile === undefined || dataUser?.profile === null ? (
<IconUserCircle color={MainColor.white} />
) : (
<Home_ComponentAvatarProfile
url={APIs.GET({
fileId: dataUser?.imageId as string,
size: "50",
})}
/>
)}
</ActionIcon>
<Text fz={10} c={MainColor.white}>
Profile
</Text>
</Stack>
</Center>
</SimpleGrid>
</Box> </Box>
); );
} }

View File

@@ -18,11 +18,12 @@ import BodyHome from "./component/body_home";
import FooterHome from "./component/footer_home"; import FooterHome from "./component/footer_home";
import { apiGetDataHome } from "./fun/get/api_home"; import { apiGetDataHome } from "./fun/get/api_home";
import { clientLogger } from "@/util/clientLogger"; import { clientLogger } from "@/util/clientLogger";
import CustomSkeleton from "../components/CustomSkeleton";
export default function HomeViewNew() { export default function HomeViewNew() {
const [countNtf, setCountNtf] = useAtom(gs_count_ntf); const [countNtf, setCountNtf] = useAtom(gs_count_ntf);
const [newUserNtf, setNewUserNtf] = useAtom(gs_user_ntf); const [newUserNtf, setNewUserNtf] = useAtom(gs_user_ntf);
const [dataUser, setDataUser] = useState<any>({}); const [dataUser, setDataUser] = useState<any | null>(null);
const [categoryPage, setCategoryPage] = useAtom(gs_notifikasi_kategori_app); const [categoryPage, setCategoryPage] = useAtom(gs_notifikasi_kategori_app);
const router = useRouter(); const router = useRouter();
@@ -67,61 +68,69 @@ export default function HomeViewNew() {
<UIGlobal_LayoutHeaderTamplate <UIGlobal_LayoutHeaderTamplate
title="HIPMI" title="HIPMI"
customButtonLeft={ customButtonLeft={
<ActionIcon dataUser?.profile == null ? (
radius={"xl"} <CustomSkeleton width={20} height={20} circle />
disabled={countNtf == null} ) : (
variant={"transparent"} <ActionIcon
onClick={() => { radius={"xl"}
if ( disabled={countNtf == null}
dataUser.profile != undefined || variant={"transparent"}
dataUser?.profile != null onClick={() => {
) { if (
router.push(RouterUserSearch.main, { scroll: false }); dataUser.profile != undefined ||
} else { dataUser?.profile != null
router.push(RouterProfile.create, { scroll: false }); ) {
} router.push(RouterUserSearch.main, { scroll: false });
}} } else {
> router.push(RouterProfile.create, { scroll: false });
<IconUserSearch color={MainColor.white} /> }
</ActionIcon> }}
>
<IconUserSearch color={MainColor.white} />
</ActionIcon>
)
} }
customButtonRight={ customButtonRight={
<ActionIcon dataUser?.profile == null ? (
variant="transparent" <CustomSkeleton width={20} height={20} circle />
disabled={countNtf == null} ) : (
onClick={() => { <ActionIcon
if ( variant="transparent"
dataUser.profile != undefined || disabled={countNtf == null}
dataUser?.profile != null onClick={() => {
) { if (
setCategoryPage("Semua"); dataUser.profile != undefined ||
router.push( dataUser?.profile != null
RouterNotifikasi.categoryApp({ name: "semua" }), ) {
{ setCategoryPage("Semua");
scroll: false, router.push(
} RouterNotifikasi.categoryApp({ name: "semua" }),
); {
} else { scroll: false,
router.push(RouterProfile.create, { scroll: false }); }
} );
}} } else {
> router.push(RouterProfile.create, { scroll: false });
{countNtf != null && countNtf > 0 ? (
<Indicator
processing
color={MainColor.yellow}
label={
<Text fz={10} c={MainColor.darkblue}>
{countNtf > 99 ? "99+" : countNtf}
</Text>
} }
> }}
>
{countNtf != null && countNtf > 0 ? (
<Indicator
processing
color={MainColor.yellow}
label={
<Text fz={10} c={MainColor.darkblue}>
{countNtf > 99 ? "99+" : countNtf}
</Text>
}
>
<IconBell color={MainColor.white} />
</Indicator>
) : (
<IconBell color={MainColor.white} /> <IconBell color={MainColor.white} />
</Indicator> )}
) : ( </ActionIcon>
<IconBell color={MainColor.white} /> )
)}
</ActionIcon>
} }
/> />
} }

View File

@@ -1,19 +1,64 @@
export const apiGetMasterInvestasi = async (path?: string) => { export const apiGetMasterInvestasi = async (path?: string) => {
const response = await fetch(`/api/new/investasi/master${(path) ? path : ''}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/investasi/master${path ? path : ""}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
export const apiGetOneInvestasiById = async (path: string) => { export const apiGetOneInvestasiById = async (path: string) => {
const response = await fetch(`/api/new/investasi/${path}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/investasi/${path}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
export const apiGetAllInvestasi = async (path?: string) => { export const apiGetAllInvestasi = async (path?: string) => {
const response = await fetch(`/api/new/investasi${(path) ? path : ''}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(`/api/new/investasi${path ? path : ""}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null);
};
export const apiGetAllSahamSaya = async (path?: string) => { export const apiGetAllSahamSaya = async (path?: string) => {
const response = await fetch(`/api/new/investasi/invoice${(path) ? path : ''}`) const { token } = await fetch("/api/get-cookie").then((res) => res.json());
return await response.json().catch(() => null) if (!token) return await token.json().catch(() => null);
}
const response = await fetch(
`/api/new/investasi/invoice${path ? path : ""}`,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
);
return await response.json().catch(() => null);
};

View File

@@ -1,3 +1,3 @@
export var validRegex = export var validRegex =
/^([a-zA-Z0-9\.!#$%&'*+/=?^_`{|}~-]+)@([a-zA-Z0-9])+.([a-z]+)(.[a-z]+)?$/; /^([a-zA-Z0-9\.!#$%&'*+/=?^_`{|}~-]+)@([a-zA-Z0-9])+.([a-z]+)(.[a-z]+)?$/;
export const gmailRegex = /^[a-zA-Z0-9._%+-]+@gmail\.com$/; export const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

View File

@@ -1,66 +1,85 @@
'use client' "use client";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { UIGlobal_LayoutHeaderTamplate, UIGlobal_LayoutTamplate } from "@/app_modules/_global/ui"; import {
UIGlobal_LayoutHeaderTamplate,
UIGlobal_LayoutTamplate,
} from "@/app_modules/_global/ui";
import { apiGetUserProfile } from "@/app_modules/user"; import { apiGetUserProfile } from "@/app_modules/user";
import { ActionIcon } from "@mantine/core"; import { ActionIcon, Skeleton } from "@mantine/core";
import { useDisclosure, useShallowEffect } from "@mantine/hooks"; import { useDisclosure, useShallowEffect } from "@mantine/hooks";
import { IconDotsVertical } from "@tabler/icons-react"; import { IconDotsVertical } from "@tabler/icons-react";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import DrawerKatalogNew from "../component/drawer_katalog_new"; import DrawerKatalogNew from "../component/drawer_katalog_new";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function LayoutKatalogNew({ children }: { children: any }) { export default function LayoutKatalogNew({
const param = useParams<{ id: string }>() children,
const [authorId, setAuthorId] = useState("") userLoginId,
const [userRoleId, setUserRoleId] = useState("") }: {
const [userLoginId, setUserLoginId] = useState("") children: any;
const [opened, { open, close }] = useDisclosure() userLoginId: string;
const [loading, setLoading] = useState(true); }) {
const param = useParams<{ id: string }>();
const [authorId, setAuthorId] = useState("");
const [userRoleId, setUserRoleId] = useState("");
const [opened, { open, close }] = useDisclosure();
const [loading, setLoading] = useState(true);
async function getProfile() { async function getProfile() {
try { try {
setLoading(true) setLoading(true);
const response = await apiGetUserProfile(`?profile=${param.id}`) const response = await apiGetUserProfile(`?profile=${param.id}`);
const response2 = await funGetUserIdByToken()
if (response) { if (response) {
setAuthorId(response.data.id) setAuthorId(response.data.id);
setUserRoleId(response.data.masterUserRoleId) setUserRoleId(response.data.masterUserRoleId);
setUserLoginId(response2)
}
} catch (error) {
console.error(error);
} finally {
setLoading(false)
} }
} } catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
useShallowEffect(() => { useShallowEffect(() => {
getProfile() getProfile();
}, []) }, []);
return ( return (
<> <>
<UIGlobal_LayoutTamplate <UIGlobal_LayoutTamplate
header={ header={
<UIGlobal_LayoutHeaderTamplate <UIGlobal_LayoutHeaderTamplate
title="KATALOG" title="KATALOG"
customButtonRight={ customButtonRight={
loading ? loading ? (
<ActionIcon disabled variant="transparent"></ActionIcon> : <ActionIcon disabled variant="transparent">
authorId == userLoginId ? ( <CustomSkeleton h={20} w={20} radius={"100%"} />
<ActionIcon c="white" variant="transparent" onClick={() => open()}> </ActionIcon>
<IconDotsVertical /> ) : authorId == userLoginId ? (
</ActionIcon> <ActionIcon
) : ( c="white"
<ActionIcon disabled variant="transparent"></ActionIcon> variant="transparent"
) onClick={() => open()}
} >
/> <IconDotsVertical />
</ActionIcon>
) : (
<ActionIcon disabled variant="transparent"></ActionIcon>
)
} }
> />
{children} }
<DrawerKatalogNew opened={opened} close={() => close()} userRoleId={userRoleId} userId={userLoginId} /> >
</UIGlobal_LayoutTamplate> {children}
</> <DrawerKatalogNew
) opened={opened}
close={() => close()}
userRoleId={userRoleId}
userId={userLoginId}
/>
</UIGlobal_LayoutTamplate>
</>
);
} }

View File

@@ -10,46 +10,73 @@ import { Button } from "@mantine/core";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import { funGlobal_UploadToStorage } from "@/app_modules/_global/fun"; import {
funGlobal_DeleteFileById,
funGlobal_UploadToStorage,
} from "@/app_modules/_global/fun";
import { DIRECTORY_ID } from "@/app/lib"; import { DIRECTORY_ID } from "@/app/lib";
import { portofolio_funEditLogoBisnisById } from "../../fun"; import { portofolio_funEditLogoBisnisById } from "../../fun";
import { clientLogger } from "@/util/clientLogger";
export function ComponentPortofolio_ButtonEditLogoBisnis({ export function ComponentPortofolio_ButtonEditLogoBisnis({
file, file,
portofolioId, portofolioId,
fileRemoveId,
}: { }: {
file: File; file: File;
portofolioId: string; portofolioId: string;
fileRemoveId: string;
}) { }) {
const router = useRouter(); const router = useRouter();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
async function onUpdate() { async function onUpdate() {
const uploadFileToStorage = await funGlobal_UploadToStorage({ try {
file: file,
dirId: DIRECTORY_ID.portofolio_logo,
});
if (!uploadFileToStorage.success)
return ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
const res = await portofolio_funEditLogoBisnisById({
portofolioId: portofolioId,
logoId: uploadFileToStorage.data.id,
});
if (res.status === 200) {
setLoading(true); setLoading(true);
ComponentGlobal_NotifikasiBerhasil(res.message);
router.back(); const deleteLogo = await funGlobal_DeleteFileById({
} else { fileId: fileRemoveId,
ComponentGlobal_NotifikasiGagal(res.message); dirId: DIRECTORY_ID.portofolio_logo,
});
if (!deleteLogo.success) {
setLoading(false);
clientLogger.error("Error delete logo", deleteLogo.message);
}
const uploadFileToStorage = await funGlobal_UploadToStorage({
file: file,
dirId: DIRECTORY_ID.portofolio_logo,
});
if (!uploadFileToStorage.success) {
setLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
return;
}
const res = await portofolio_funEditLogoBisnisById({
portofolioId: portofolioId,
logoId: uploadFileToStorage.data.id,
});
if (res.status === 200) {
ComponentGlobal_NotifikasiBerhasil(res.message);
router.back();
} else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(res.message);
}
} catch (error) {
setLoading(false);
clientLogger.error("Error update logo", error);
} }
} }
return ( return (
<> <>
{file ? ( {file ? (
<Button <Button
loaderPosition="center" loaderPosition="center"
loading={loading ? true : false} loading={loading}
radius={"xl"} radius={"xl"}
onClick={() => onUpdate()} onClick={() => onUpdate()}
bg={MainColor.yellow} bg={MainColor.yellow}

View File

@@ -37,13 +37,13 @@ export default function ComponentPortofolio_ButtonDeleteNew({
ComponentGlobal_NotifikasiBerhasil(response.message); ComponentGlobal_NotifikasiBerhasil(response.message);
router.back(); router.back();
} else { } else {
setLoadingDel(false);
ComponentGlobal_NotifikasiGagal(response?.message); ComponentGlobal_NotifikasiGagal(response?.message);
} }
} catch (error) { } catch (error) {
setLoadingDel(false);
clientLogger.error("Error delete portofolio", error); clientLogger.error("Error delete portofolio", error);
ComponentGlobal_NotifikasiGagal("Gagal menghapus portofolio"); ComponentGlobal_NotifikasiGagal("Gagal menghapus portofolio");
} finally {
setLoadingDel(false);
} }
} }

View File

@@ -3,122 +3,136 @@ import { RouterMap } from "@/app/lib/router_hipmi/router_map";
import { UIGlobal_Drawer } from "@/app_modules/_global/ui"; import { UIGlobal_Drawer } from "@/app_modules/_global/ui";
import { ActionIcon } from "@mantine/core"; import { ActionIcon } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks"; import { useShallowEffect } from "@mantine/hooks";
import { IconEdit, IconPhotoEdit, IconId, IconMapPin2, IconMapPin, IconDotsVertical } from "@tabler/icons-react"; import {
IconEdit,
IconPhotoEdit,
IconId,
IconMapPin2,
IconMapPin,
IconDotsVertical,
} from "@tabler/icons-react";
import { useParams } from "next/navigation"; import { useParams } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import { apiGetOnePortofolioById } from "../lib/api_portofolio"; import { apiGetOnePortofolioById } from "../lib/api_portofolio";
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get"; import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { MainColor } from "@/app_modules/_global/color"; import { MainColor } from "@/app_modules/_global/color";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function ComponentPortofolio_ButtonMoreNew() { export default function ComponentPortofolio_ButtonMoreNew({
const param = useParams<{ id: string }>() userLoginId,
const [userLoginId, setUserLoginId] = useState("") }: {
const [authorId, setAuthorId] = useState("") userLoginId: string;
const [mapId, setMapId] = useState(true) }) {
const [openDrawer, setOpenDrawer] = useState(false) const param = useParams<{ id: string }>();
const [authorId, setAuthorId] = useState("");
const [mapId, setMapId] = useState(true);
const [openDrawer, setOpenDrawer] = useState(false);
const listPage = [ const listPage = [
{ {
id: "1", id: "1",
name: "Edit detail ", name: "Edit detail ",
icon: <IconEdit color={MainColor.white} />, icon: <IconEdit color={MainColor.white} />,
path: RouterPortofolio.edit_data_bisnis + `${param.id}`, path: RouterPortofolio.edit_data_bisnis + `${param.id}`,
}, },
{ {
id: "2", id: "2",
name: "Edit logo ", name: "Edit logo ",
icon: <IconPhotoEdit color={MainColor.white} />, icon: <IconPhotoEdit color={MainColor.white} />,
path: RouterPortofolio.edit_logo_bisnis + `${param.id}`, path: RouterPortofolio.edit_logo_bisnis + `${param.id}`,
}, },
{ {
id: "3", id: "3",
name: "Edit sosial media", name: "Edit sosial media",
icon: <IconId color={MainColor.white} />, icon: <IconId color={MainColor.white} />,
path: RouterPortofolio.edit_medsos_bisnis + `${param.id}`, path: RouterPortofolio.edit_medsos_bisnis + `${param.id}`,
}, },
{ {
id: "4", id: "4",
name: "Edit data map", name: "Edit data map",
icon: <IconMapPin2 color={MainColor.white} />, icon: <IconMapPin2 color={MainColor.white} />,
path: RouterMap.edit + `${param.id}`, path: RouterMap.edit + `${param.id}`,
}, },
{ {
id: "5", id: "5",
name: "Custom pin map", name: "Custom pin map",
icon: <IconMapPin color={MainColor.white} />, icon: <IconMapPin color={MainColor.white} />,
path: RouterMap.custom_pin + `${param.id}`, path: RouterMap.custom_pin + `${param.id}`,
}, },
]; ];
const listPage2 = [ const listPage2 = [
{ {
id: "1", id: "1",
name: "Edit detail ", name: "Edit detail ",
icon: <IconEdit color={MainColor.white} />, icon: <IconEdit color={MainColor.white} />,
path: RouterPortofolio.edit_data_bisnis + `${param.id}`, path: RouterPortofolio.edit_data_bisnis + `${param.id}`,
}, },
{ {
id: "2", id: "2",
name: "Edit logo ", name: "Edit logo ",
icon: <IconPhotoEdit color={MainColor.white} />, icon: <IconPhotoEdit color={MainColor.white} />,
path: RouterPortofolio.edit_logo_bisnis + `${param.id}`, path: RouterPortofolio.edit_logo_bisnis + `${param.id}`,
}, },
{ {
id: "3", id: "3",
name: "Edit sosial media", name: "Edit sosial media",
icon: <IconId color={MainColor.white} />, icon: <IconId color={MainColor.white} />,
path: RouterPortofolio.edit_medsos_bisnis + `${param.id}`, path: RouterPortofolio.edit_medsos_bisnis + `${param.id}`,
}, },
{ {
id: "4", id: "4",
name: "Edit data map", name: "Edit data map",
icon: <IconMapPin2 color={MainColor.white} />, icon: <IconMapPin2 color={MainColor.white} />,
path: RouterMap.create + `${param.id}`, path: RouterMap.create + `${param.id}`,
}, },
{ {
id: "5", id: "5",
name: "Custom pin map", name: "Custom pin map",
icon: <IconMapPin color={MainColor.white} />, icon: <IconMapPin color={MainColor.white} />,
path: RouterMap.custom_pin + `${param.id}`, path: RouterMap.custom_pin + `${param.id}`,
}, },
]; ];
async function funGetPortofolio() {
try {
const response = await apiGetOnePortofolioById(param.id, "bisnis");
const response3 = await apiGetOnePortofolioById(param.id, "lokasi");
async function funGetPortofolio() { if (response) {
try { setAuthorId(response.data.authorId);
const response = await apiGetOnePortofolioById(param.id, "bisnis") setMapId(
const response3 = await apiGetOnePortofolioById(param.id, "lokasi") response3 !== null && response3.data?.mapId !== undefined
const response2 = await funGetUserIdByToken() ? true
if (response) { : false
setAuthorId(response.data.authorId) );
setMapId((response3 !== null && response3.data?.mapId !== undefined) ? true : false)
setUserLoginId(response2)
}
} catch (error) {
console.error(error);
} }
} } catch (error) {
console.error(error);
}
}
useShallowEffect(() => { useShallowEffect(() => {
funGetPortofolio() funGetPortofolio();
}, []); }, []);
return (
<>
{userLoginId === authorId ? (
<ActionIcon variant="transparent" onClick={() => setOpenDrawer(true)}>
<IconDotsVertical color={MainColor.white} />
</ActionIcon>
) : (
<ActionIcon disabled variant="transparent">
<CustomSkeleton h={20} w={20} radius={"100%"} />
</ActionIcon>
)}
return ( <UIGlobal_Drawer
<> opened={openDrawer}
{userLoginId === authorId ? ( close={() => setOpenDrawer(false)}
<ActionIcon variant="transparent" onClick={() => setOpenDrawer(true)}> component={mapId ? listPage : listPage2}
<IconDotsVertical color={MainColor.white} /> />
</ActionIcon> </>
) : ( );
<ActionIcon disabled variant="transparent"></ActionIcon>
)}
<UIGlobal_Drawer
opened={openDrawer}
close={() => setOpenDrawer(false)}
component={mapId ? listPage : listPage2}
/>
</>
)
} }

View File

@@ -84,6 +84,7 @@ export default function Portofolio_EditLogoBisnis({
<ComponentPortofolio_ButtonEditLogoBisnis <ComponentPortofolio_ButtonEditLogoBisnis
file={file as any} file={file as any}
portofolioId={dataPorto.id} portofolioId={dataPorto.id}
fileRemoveId={dataPorto.logoId}
/> />
</Stack> </Stack>
</> </>

View File

@@ -1,6 +1,6 @@
export const apiGetPortofolioByProfile = async (path?: string) => { export const apiGetPortofolioByProfile = async (path?: string) => {
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 null; if (!token) return await token.json().catch(() => null);
const response = await fetch(`/api/new/portofolio${path ? path : ""}`, { const response = await fetch(`/api/new/portofolio${path ? path : ""}`, {
headers: { headers: {
@@ -18,7 +18,7 @@ export const apiGetPortofolioByProfile = async (path?: string) => {
export const apiGetOnePortofolioById = async (path: string, cat: string) => { export const apiGetOnePortofolioById = async (path: string, cat: string) => {
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 null; if (!token) return await token.json().catch(() => null);
const response = await fetch(`/api/new/portofolio/${path}?cat=${cat}`, { const response = await fetch(`/api/new/portofolio/${path}?cat=${cat}`, {
headers: { headers: {
@@ -36,7 +36,7 @@ export const apiGetOnePortofolioById = async (path: string, cat: string) => {
export const apiDeletePortofolio = async (path: string) => { export const apiDeletePortofolio = async (path: string) => {
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 null; if (!token) return await token.json().catch(() => null);
const response = await fetch(`/api/new/portofolio/${path}`, { const response = await fetch(`/api/new/portofolio/${path}`, {
method: "DELETE", method: "DELETE",
@@ -46,6 +46,5 @@ export const apiDeletePortofolio = async (path: string) => {
}, },
}); });
return await response.json().catch(() => null); return await response.json().catch(() => null);
}; };

View File

@@ -2,19 +2,27 @@
import { UIGlobal_LayoutHeaderTamplate, UIGlobal_LayoutTamplate } from "@/app_modules/_global/ui"; import { UIGlobal_LayoutHeaderTamplate, UIGlobal_LayoutTamplate } from "@/app_modules/_global/ui";
import ComponentPortofolio_ButtonMoreNew from "../component/button_more_new"; import ComponentPortofolio_ButtonMoreNew from "../component/button_more_new";
export default function PortofolioLayoutNew({ children }: { children: any }) { export default function PortofolioLayoutNew({
return ( children,
<> userLoginId,
<UIGlobal_LayoutTamplate }: {
header={ children: any;
<UIGlobal_LayoutHeaderTamplate userLoginId: string
title="Detail Portofolio" }) {
customButtonRight={<ComponentPortofolio_ButtonMoreNew />} return (
/> <>
<UIGlobal_LayoutTamplate
header={
<UIGlobal_LayoutHeaderTamplate
title="Detail Portofolio"
customButtonRight={
<ComponentPortofolio_ButtonMoreNew userLoginId={userLoginId} />
} }
> />
{children} }
</UIGlobal_LayoutTamplate> >
</> {children}
) </UIGlobal_LayoutTamplate>
</>
);
} }

View File

@@ -29,16 +29,8 @@ export function Profile_ComponentButtonUpdateBackgroundProfile({
async function onUpdate() { async function onUpdate() {
try { try {
setLoading(true); setLoading(true);
const deletePhoto = await funGlobal_DeleteFileById({
fileId: fileId,
dirId: DIRECTORY_ID.profile_background,
});
if (!deletePhoto.success) {
ComponentGlobal_NotifikasiPeringatan("Gagal update background");
return;
}
// Upload gambar baru
const uploadFile = await funGlobal_UploadToStorage({ const uploadFile = await funGlobal_UploadToStorage({
file: file, file: file,
dirId: DIRECTORY_ID.profile_background, dirId: DIRECTORY_ID.profile_background,
@@ -46,9 +38,19 @@ export function Profile_ComponentButtonUpdateBackgroundProfile({
if (!uploadFile.success) { if (!uploadFile.success) {
setLoading(false); setLoading(false);
return ComponentGlobal_NotifikasiPeringatan( ComponentGlobal_NotifikasiPeringatan("Gagal upload background");
"Gagal upload background" return;
); }
// Hapus gambar lama
const deletePhoto = await funGlobal_DeleteFileById({
fileId: fileId,
dirId: DIRECTORY_ID.profile_background,
});
if (!deletePhoto.success) {
setLoading(false);
clientLogger.error("Error delete background", deletePhoto.message);
} }
const res = await profile_funUpdateBackground({ const res = await profile_funUpdateBackground({
@@ -60,12 +62,12 @@ export function Profile_ComponentButtonUpdateBackgroundProfile({
ComponentGlobal_NotifikasiBerhasil(res.message); ComponentGlobal_NotifikasiBerhasil(res.message);
router.back(); router.back();
} else { } else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(res.message); ComponentGlobal_NotifikasiGagal(res.message);
} }
} catch (error) { } catch (error) {
clientLogger.error("Error upload background", error);
} finally {
setLoading(false); setLoading(false);
clientLogger.error("Error upload background", error);
} }
} }

View File

@@ -1,21 +1,21 @@
"use client"; "use client";
import { DIRECTORY_ID } from "@/app/lib";
import { MainColor } from "@/app_modules/_global/color"; import { MainColor } from "@/app_modules/_global/color";
import {
funGlobal_DeleteFileById,
funGlobal_UploadToStorage,
} from "@/app_modules/_global/fun";
import { import {
ComponentGlobal_NotifikasiBerhasil, ComponentGlobal_NotifikasiBerhasil,
ComponentGlobal_NotifikasiGagal, ComponentGlobal_NotifikasiGagal,
ComponentGlobal_NotifikasiPeringatan, ComponentGlobal_NotifikasiPeringatan,
} from "@/app_modules/_global/notif_global"; } from "@/app_modules/_global/notif_global";
import { Box, Button, Center } from "@mantine/core"; import { clientLogger } from "@/util/clientLogger";
import { Box, Button } from "@mantine/core";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import { profile_funUpdatePhoto } from "../../fun"; import { profile_funUpdatePhoto } from "../../fun";
import {
funGlobal_DeleteFileById,
funGlobal_UploadToStorage,
} from "@/app_modules/_global/fun";
import { DIRECTORY_ID } from "@/app/lib";
import { clientLogger } from "@/util/clientLogger";
export function Profile_ComponentButtonUpdatePhotoProfile({ export function Profile_ComponentButtonUpdatePhotoProfile({
file, file,
@@ -31,26 +31,30 @@ export function Profile_ComponentButtonUpdatePhotoProfile({
async function onUpdate() { async function onUpdate() {
try { try {
setLoading(true); setLoading(true);
const deletePhoto = await funGlobal_DeleteFileById({
fileId: fileId,
dirId: DIRECTORY_ID.profile_foto,
});
if (!deletePhoto.success) {
ComponentGlobal_NotifikasiPeringatan("Gagal update foto profile");
return;
}
// Upload foto baru
const uploadPhoto = await funGlobal_UploadToStorage({ const uploadPhoto = await funGlobal_UploadToStorage({
file: file, file: file,
dirId: DIRECTORY_ID.profile_foto, dirId: DIRECTORY_ID.profile_foto,
}); });
if (!uploadPhoto.success) { if (!uploadPhoto.success) {
setLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload foto profile"); ComponentGlobal_NotifikasiPeringatan("Gagal upload foto profile");
return; return;
} }
// Hapus gambar lama
const deletePhoto = await funGlobal_DeleteFileById({
fileId: fileId,
dirId: DIRECTORY_ID.profile_foto,
});
if (!deletePhoto.success) {
setLoading(false);
clientLogger.error("Error delete logo", deletePhoto.message);
}
const res = await profile_funUpdatePhoto({ const res = await profile_funUpdatePhoto({
fileId: uploadPhoto.data.id, fileId: uploadPhoto.data.id,
profileId: profileId, profileId: profileId,
@@ -60,12 +64,12 @@ export function Profile_ComponentButtonUpdatePhotoProfile({
ComponentGlobal_NotifikasiBerhasil(res.message); ComponentGlobal_NotifikasiBerhasil(res.message);
router.back(); router.back();
} else { } else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(res.message); ComponentGlobal_NotifikasiGagal(res.message);
} }
} catch (error) { } catch (error) {
clientLogger.error("Error update photo profile", error);
} finally {
setLoading(false); setLoading(false);
clientLogger.error("Error update photo profile", error);
} }
} }
return ( return (

View File

@@ -7,7 +7,7 @@ import {
ComponentGlobal_NotifikasiGagal, ComponentGlobal_NotifikasiGagal,
ComponentGlobal_NotifikasiPeringatan, ComponentGlobal_NotifikasiPeringatan,
} from "@/app_modules/_global/notif_global"; } from "@/app_modules/_global/notif_global";
import { gmailRegex } from "@/app_modules/katalog/component/regular_expressions"; import { emailRegex } from "@/app_modules/katalog/component/regular_expressions";
import { Button } from "@mantine/core"; import { Button } from "@mantine/core";
import _ from "lodash"; import _ from "lodash";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
@@ -36,7 +36,7 @@ export function Profile_ComponentCreateNewProfile({
}; };
if (_.values(newData).includes("")) if (_.values(newData).includes(""))
return ComponentGlobal_NotifikasiPeringatan("Lengkapi Data"); return ComponentGlobal_NotifikasiPeringatan("Lengkapi Data");
if (!newData.email.match(gmailRegex)) if (!newData.email.match(emailRegex))
return ComponentGlobal_NotifikasiPeringatan("Format email salah"); return ComponentGlobal_NotifikasiPeringatan("Format email salah");
if (fotoProfileId == "") if (fotoProfileId == "")

View File

@@ -4,7 +4,7 @@ import { ComponentGlobal_ErrorInput } from "@/app_modules/_global/component";
import { Select, Stack, TextInput } from "@mantine/core"; import { Select, Stack, TextInput } from "@mantine/core";
import { IconAt } from "@tabler/icons-react"; import { IconAt } from "@tabler/icons-react";
import { useState } from "react"; import { useState } from "react";
import { gmailRegex } from "../../component/regular_expressions"; import { emailRegex } from "../../component/regular_expressions";
import { Profile_ComponentCreateNewProfile } from "../_component"; import { Profile_ComponentCreateNewProfile } from "../_component";
import Profile_ViewUploadBackground from "./view_upload_background"; import Profile_ViewUploadBackground from "./view_upload_background";
import Profile_ViewUploadFoto from "./view_upload_foto"; import Profile_ViewUploadFoto from "./view_upload_foto";
@@ -70,7 +70,7 @@ export default function CreateProfile() {
maxLength={100} maxLength={100}
placeholder="Contoh: User@gmail.com" placeholder="Contoh: User@gmail.com"
error={ error={
value.email.length > 0 && !value.email.match(gmailRegex) ? ( value.email.length > 0 && !value.email.match(emailRegex) ? (
<ComponentGlobal_ErrorInput text="Invalid Email" /> <ComponentGlobal_ErrorInput text="Invalid Email" />
) : ( ) : (
"" ""

View File

@@ -1,17 +1,18 @@
"use client"; "use client";
import { MainColor } from "@/app_modules/_global/color/color_pallet";
import ComponentGlobal_ErrorInput from "@/app_modules/_global/component/error_input";
import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global";
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import { clientLogger } from "@/util/clientLogger";
import { Button, Loader, Select, Stack, TextInput } from "@mantine/core"; import { Button, Loader, Select, Stack, TextInput } from "@mantine/core";
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 { MainColor } from "@/app_modules/_global/color/color_pallet"; import { emailRegex } from "../../component/regular_expressions";
import ComponentGlobal_ErrorInput from "@/app_modules/_global/component/error_input";
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import { gmailRegex, validRegex } from "../../component/regular_expressions";
import { Profile_funEditById } from "../fun/update/fun_edit_profile_by_id"; import { Profile_funEditById } from "../fun/update/fun_edit_profile_by_id";
import { MODEL_PROFILE } from "../model/interface"; import { MODEL_PROFILE } from "../model/interface";
import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global";
export default function EditProfile({ data }: { data: MODEL_PROFILE }) { export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
const router = useRouter(); const router = useRouter();
@@ -26,18 +27,23 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
// console.log(body) // console.log(body)
if (_.values(body).includes("")) if (_.values(body).includes(""))
return ComponentGlobal_NotifikasiPeringatan("Lengkapi data"); return ComponentGlobal_NotifikasiPeringatan("Lengkapi data");
if (!body.email.match(gmailRegex)) if (!body.email.match(emailRegex))
return ComponentGlobal_NotifikasiPeringatan("Format email salah"); return ComponentGlobal_NotifikasiPeringatan("Format email salah");
await Profile_funEditById(body).then((res) => { try {
setLoading(true);
const res = await Profile_funEditById(body);
if (res.status === 200) { if (res.status === 200) {
setLoading(true);
ComponentGlobal_NotifikasiBerhasil(res.message); ComponentGlobal_NotifikasiBerhasil(res.message);
setTimeout(() => router.back(), 1000); router.back();
} else { } else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(res.message); ComponentGlobal_NotifikasiGagal(res.message);
} }
}); } catch (error) {
setLoading(false);
clientLogger.error("Error update foto profile", error);
}
} }
if (!dataProfile) if (!dataProfile)
@@ -49,7 +55,6 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
return ( return (
<> <>
{/* <pre>{JSON.stringify(dataProfile, null, 2)}</pre> */}
<Stack px={"sm"}> <Stack px={"sm"}>
<TextInput <TextInput
styles={{ styles={{
@@ -96,7 +101,7 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
}, },
input: { input: {
backgroundColor: MainColor.white, backgroundColor: MainColor.white,
} },
}} }}
withAsterisk withAsterisk
label="Nama" label="Nama"
@@ -125,7 +130,7 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
}, },
input: { input: {
backgroundColor: MainColor.white, backgroundColor: MainColor.white,
} },
}} }}
withAsterisk withAsterisk
label="Email" label="Email"
@@ -134,7 +139,7 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
dataProfile?.email === "" ? ( dataProfile?.email === "" ? (
<ComponentGlobal_ErrorInput text="Masukan email " /> <ComponentGlobal_ErrorInput text="Masukan email " />
) : dataProfile?.email?.length > 0 && ) : dataProfile?.email?.length > 0 &&
!dataProfile?.email.match(gmailRegex) ? ( !dataProfile?.email.match(emailRegex) ? (
<ComponentGlobal_ErrorInput text="Invalid email" /> <ComponentGlobal_ErrorInput text="Invalid email" />
) : ( ) : (
"" ""
@@ -156,7 +161,7 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
}, },
input: { input: {
backgroundColor: MainColor.white, backgroundColor: MainColor.white,
} },
}} }}
withAsterisk withAsterisk
label="Alamat" label="Alamat"
@@ -185,7 +190,7 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
}, },
input: { input: {
backgroundColor: MainColor.white, backgroundColor: MainColor.white,
} },
}} }}
withAsterisk withAsterisk
label="Jenis Kelamin" label="Jenis Kelamin"
@@ -216,7 +221,6 @@ export default function EditProfile({ data }: { data: MODEL_PROFILE }) {
</Button> </Button>
</Stack> </Stack>
{/* <pre>{JSON.stringify(dataProfile, null, 2)}</pre> */}
</> </>
); );
} }

View File

@@ -8,12 +8,16 @@ import {
} from "@/app_modules/_global/notif_global"; } from "@/app_modules/_global/notif_global";
import { Button } from "@mantine/core"; import { Button } from "@mantine/core";
import { DIRECTORY_ID } from "@/app/lib";
import {
funGlobal_DeleteFileById,
funGlobal_UploadToStorage,
} from "@/app_modules/_global/fun";
import { clientLogger } from "@/util/clientLogger";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { map_funEditMap } from "../../fun/edit/fun_edit_map"; import { map_funEditMap } from "../../fun/edit/fun_edit_map";
import { MODEL_MAP } from "../../lib/interface"; import { MODEL_MAP } from "../../lib/interface";
import { useRouter } from "next/navigation";
import { DIRECTORY_ID } from "@/app/lib";
import { funGlobal_UploadToStorage } from "@/app_modules/_global/fun";
import { useState } from "react";
export function ComponentMap_ButtonUpdateDataMap({ export function ComponentMap_ButtonUpdateDataMap({
data, data,
@@ -25,30 +29,59 @@ export function ComponentMap_ButtonUpdateDataMap({
const router = useRouter(); const router = useRouter();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
async function onSavePin() { async function onSavePin() {
if (file !== null) { try {
const uploadFileToStorage = await funGlobal_UploadToStorage({ setIsLoading(true);
file: file,
dirId: DIRECTORY_ID.map_image,
});
if (!uploadFileToStorage.success)
return ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
const res = await map_funEditMap({ if (file !== null) {
data: data, const deleteLogo = await funGlobal_DeleteFileById({
fileId: uploadFileToStorage.data.id, fileId: data.imageId,
}); dirId: DIRECTORY_ID.map_image,
res.status === 200 });
? (ComponentGlobal_NotifikasiBerhasil(res.message), router.back())
: ComponentGlobal_NotifikasiGagal(res.message); if (!deleteLogo.success) {
} else { setIsLoading(false);
const res = await map_funEditMap({ clientLogger.error("Error delete logo", deleteLogo.message);
data: data, }
});
res.status === 200 const uploadFileToStorage = await funGlobal_UploadToStorage({
? (ComponentGlobal_NotifikasiBerhasil(res.message), router.back()) file: file,
: ComponentGlobal_NotifikasiGagal(res.message); dirId: DIRECTORY_ID.map_image,
});
if (!uploadFileToStorage.success) {
setIsLoading(false);
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
return;
}
const res = await map_funEditMap({
data: data,
fileId: uploadFileToStorage.data.id,
});
if (res.status === 200) {
ComponentGlobal_NotifikasiBerhasil(res.message);
router.back();
} else {
setIsLoading(false);
ComponentGlobal_NotifikasiGagal(res.message);
}
} else {
const res = await map_funEditMap({
data: data,
});
if (res.status === 200) {
ComponentGlobal_NotifikasiBerhasil(res.message);
router.back();
} else {
setIsLoading(false);
ComponentGlobal_NotifikasiGagal(res.message);
}
}
} catch (error) {
setIsLoading(false);
clientLogger.error("Error update logo", error);
} }
setIsLoading(true);
} }
return ( return (

View File

@@ -14,7 +14,17 @@ export const apiGetAllMap = async (path?: string) => {
}; };
export const apiGetOneMapById = async (path: string) => { export const apiGetOneMapById = async (path: string) => {
const { token } = await fetch("/api/get-cookie").then((res) => res.json());
if (!token) return await token.json().catch(() => null);
const response = await fetch(`/api/new/map/${path}`);
const response = await fetch(`/api/new/map/${path}`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
});
return await response.json().catch(() => null); return await response.json().catch(() => null);
}; };

View File

@@ -26,9 +26,13 @@ import { map_funCustomPinMap } from "../fun";
import { defaultMapZoom } from "../lib/default_lat_long"; import { defaultMapZoom } from "../lib/default_lat_long";
import { MODEL_MAP } from "../lib/interface"; import { MODEL_MAP } from "../lib/interface";
import { APIs, DIRECTORY_ID } from "@/app/lib"; import { APIs, DIRECTORY_ID } from "@/app/lib";
import { funGlobal_UploadToStorage } from "@/app_modules/_global/fun"; import {
funGlobal_DeleteFileById,
funGlobal_UploadToStorage,
} from "@/app_modules/_global/fun";
import { MAX_SIZE } from "@/app_modules/_global/lib"; import { MAX_SIZE } from "@/app_modules/_global/lib";
import { PemberitahuanMaksimalFile } from "@/app_modules/_global/lib/max_size"; import { PemberitahuanMaksimalFile } from "@/app_modules/_global/lib/max_size";
import { clientLogger } from "@/util/clientLogger";
export function UiMap_CustomPin({ export function UiMap_CustomPin({
dataMap, dataMap,
@@ -172,34 +176,67 @@ export function UiMap_CustomPin({
<AttributionControl customAttribution="Map design by PT. Bali Interaktif Perkasa" /> <AttributionControl customAttribution="Map design by PT. Bali Interaktif Perkasa" />
</Map> </Map>
<ButtonSimpan mapId={data.id} filePin={filePin} /> <ButtonSimpan
mapId={data.id}
filePin={filePin}
fileRemoveId={data.pinId}
/>
</Stack> </Stack>
</> </>
); );
} }
function ButtonSimpan({ mapId, filePin }: { mapId: string; filePin: File }) { function ButtonSimpan({
mapId,
filePin,
fileRemoveId,
}: {
mapId: string;
filePin: File;
fileRemoveId: string;
}) {
const router = useRouter(); const router = useRouter();
const [isLoading, setLoading] = useState(false); const [isLoading, setLoading] = useState(false);
async function onCustom() { async function onCustom() {
const uploadFileToStorage = await funGlobal_UploadToStorage({ try {
file: filePin, setLoading(true);
dirId: DIRECTORY_ID.map_pin, const deletePin = await funGlobal_DeleteFileById({
}); fileId: fileRemoveId,
dirId: DIRECTORY_ID.map_pin,
});
if (!deletePin.success) {
setLoading(false);
clientLogger.error("Error delete logo", deletePin.message);
}
if (!uploadFileToStorage.success) const uploadFileToStorage = await funGlobal_UploadToStorage({
return ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar"); file: filePin,
dirId: DIRECTORY_ID.map_pin,
});
const res = await map_funCustomPinMap({ if (!uploadFileToStorage.success) {
mapId: mapId, setLoading(false);
fileId: uploadFileToStorage.data.id, ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
}); return;
res.status === 200 }
? (ComponentGlobal_NotifikasiBerhasil(res.message),
setLoading(true), const res = await map_funCustomPinMap({
router.back()) mapId: mapId,
: ComponentGlobal_NotifikasiGagal(res.message); fileId: uploadFileToStorage.data.id,
});
if (res.status === 200) {
ComponentGlobal_NotifikasiBerhasil(res.message);
router.back();
} else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(res.message);
}
} catch (error) {
setLoading(false);
clientLogger.error("Error custom pin", error);
}
} }
return ( return (