fix api update medsos portofolio

This commit is contained in:
2025-02-13 12:38:04 +08:00
parent 61c43ef72a
commit 542e36345d
5 changed files with 236 additions and 90 deletions

View File

@@ -0,0 +1,54 @@
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
export async function PUT(
request: Request,
{ params }: { params: { id: string } }
) {
if (request.method !== "PUT") {
return NextResponse.json(
{
success: false,
message: "Method not allowed",
},
{ status: 405 }
);
}
try {
const { id } = params;
const { data } = await request.json();
const updateData = await prisma.portofolio_MediaSosial.update({
where: {
id: id,
},
data: {
facebook: data.facebook,
instagram: data.instagram,
tiktok: data.tiktok,
twitter: data.twitter,
youtube: data.youtube,
},
});
return NextResponse.json(
{
success: true,
message: "Berhasil update data",
data: updateData,
},
{ status: 200 }
);
} catch (error) {
backendLogger.error("Error update data", error);
return NextResponse.json(
{
success: false,
message: "Error update data",
reason: (error as Error).message,
},
{ status: 500 }
);
}
}

View File

@@ -2,15 +2,15 @@ import { Portofolio_EditMedsosBisnis } from "@/app_modules/katalog/portofolio";
import { Portofolio_geOnetMedsosById } from "@/app_modules/katalog/portofolio/fun/get/get_one_medsos_by_id"; import { Portofolio_geOnetMedsosById } from "@/app_modules/katalog/portofolio/fun/get/get_one_medsos_by_id";
import _ from "lodash"; import _ from "lodash";
export default async function Page({ params }: { params: { id: string } }) { export default async function Page() {
let portoId = params.id; // let portoId = params.id;
const dataMedsos = await Portofolio_geOnetMedsosById(portoId).then((res) => // const dataMedsos = await Portofolio_geOnetMedsosById(portoId).then((res) =>
_.omit(res, ["active", "createdAt", "updatedAt", "portofolioId"]) // _.omit(res, ["active", "createdAt", "updatedAt", "portofolioId"])
); // );
return ( return (
<> <>
<Portofolio_EditMedsosBisnis dataMedsos={dataMedsos as any} /> <Portofolio_EditMedsosBisnis />
</> </>
); );
} }

View File

@@ -3,6 +3,7 @@ export {
apiGetPortofolioById, apiGetPortofolioById,
apiUpdatePortofolioById, apiUpdatePortofolioById,
apiUpdateLogoPortofolioById, apiUpdateLogoPortofolioById,
apiUpdateMedsosPortofolioById,
}; };
const apiCreatePortofolio = async ({ const apiCreatePortofolio = async ({
@@ -21,7 +22,6 @@ const apiCreatePortofolio = async ({
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Accept: "application/json", Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
@@ -38,7 +38,6 @@ const apiGetPortofolioById = async ({ id }: { id: string }) => {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Accept: "application/json", Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
@@ -62,7 +61,6 @@ const apiUpdatePortofolioById = async ({
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Accept: "application/json", Accept: "application/json",
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
@@ -118,4 +116,51 @@ const apiUpdateLogoPortofolioById = async ({
console.error("Error updating portfolio logo:", error); console.error("Error updating portfolio logo:", error);
throw error; // Re-throw the error to handle it in the calling function throw error; // Re-throw the error to handle it in the calling function
} }
}; };
const apiUpdateMedsosPortofolioById = async ({
id,
data,
}: {
id: string;
data: any;
}) => {
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;
}
// Send PUT request to update portfolio logo
const response = await fetch(`/api/portofolio/medsos/${id}`, {
method: "PUT",
body: JSON.stringify({ data }),
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(
"Failed to update portfolio medsos:",
response.statusText,
errorData
);
throw new Error(
errorData?.message || "Failed to update portfolio medsos"
);
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error updating portfolio medsos:", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -1,61 +1,121 @@
"use client"; "use client";
import ComponentKatalog_NotedBox from "@/app_modules/katalog/component/noted_box";
import { Box, Button, Paper, Stack, TextInput } from "@mantine/core";
import { useState } from "react";
import { MODEL_PORTOFOLIO_MEDSOS } from "../../model/interface";
import { Portofolio_funEditMedsosById } from "../../fun/edit/fun_edit_medsos_bisnis_by_id";
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { useRouter } from "next/navigation";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global/notifikasi_peringatan";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import { import {
AccentColor, AccentColor,
MainColor, MainColor,
} from "@/app_modules/_global/color/color_pallet"; } from "@/app_modules/_global/color/color_pallet";
import { ComponentGlobal_CardStyles } from "@/app_modules/_global/component";
import { ComponentGlobal_NotifikasiBerhasil } from "@/app_modules/_global/notif_global/notifikasi_berhasil";
import { ComponentGlobal_NotifikasiGagal } from "@/app_modules/_global/notif_global/notifikasi_gagal";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { Button, Stack, TextInput } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import {
apiGetPortofolioById,
apiUpdateMedsosPortofolioById,
} from "../../component/api_fetch_portofolio";
import { Portofolio_funEditMedsosById } from "../../fun/edit/fun_edit_medsos_bisnis_by_id";
import { MODEL_PORTOFOLIO_MEDSOS } from "../../model/interface";
import { clientLogger } from "@/util/clientLogger";
export default function Portofolio_EditMedsosBisnis({ interface IUpdateMedson {
dataMedsos, facebook: string;
}: { instagram: string;
dataMedsos: MODEL_PORTOFOLIO_MEDSOS; tiktok: string;
}) { twitter: string;
youtube: string;
}
export default function Portofolio_EditMedsosBisnis() {
const params = useParams<{ id: string }>();
const portofolioId = params.id;
const router = useRouter(); const router = useRouter();
const [medsos, setMedsos] = useState(dataMedsos); const [data, setData] = useState<MODEL_PORTOFOLIO_MEDSOS | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
useShallowEffect(() => {
handleLoadData();
}, []);
const handleLoadData = async () => {
try {
const response = await apiGetPortofolioById({ id: portofolioId });
if (response.success) {
setData(response.data.Portofolio_MediaSosial);
}
} catch (error) {
clientLogger.error("Error Load Data Portofolio", error);
}
};
const hanldeUpdateData = async (data: any) => {
const newData: IUpdateMedson = {
facebook: data.facebook,
instagram: data.instagram,
tiktok: data.tiktok,
twitter: data.twitter,
youtube: data.youtube,
};
const response = await apiUpdateMedsosPortofolioById({
id: data.id,
data: newData,
});
return response;
};
async function submitUpdate() {
if (!data) {
ComponentGlobal_NotifikasiGagal("Data tidak valid");
return;
}
try {
setLoading(true);
const responseUpdate = await hanldeUpdateData(data);
if (responseUpdate.success) {
ComponentGlobal_NotifikasiBerhasil(responseUpdate.message);
router.back();
} else {
setLoading(false);
ComponentGlobal_NotifikasiGagal(responseUpdate.message);
}
} catch (error) {
setLoading(false);
clientLogger.error("Error Update Medsos", error);
ComponentGlobal_NotifikasiGagal("Error Update Medsos");
}
}
if (!data) return <CustomSkeleton height={450} width={"100%"} />;
return ( return (
<> <>
{/* <pre>{JSON.stringify(dataMedsos, null, 2)}</pre> */} {/* <pre>{JSON.stringify(dataMedsos, null, 2)}</pre> */}
<Paper <ComponentGlobal_CardStyles>
p={"sm"}
style={{
backgroundColor: AccentColor.darkblue,
border: `2px solid ${AccentColor.blue}`,
borderRadius: "10px ",
padding: "15px",
color: MainColor.white,
}}
>
<Stack px={"sm"}> <Stack px={"sm"}>
<TextInput <TextInput
styles={{ styles={{
label: { label: {
color: MainColor.white color: MainColor.white,
}, },
input: { input: {
backgroundColor: MainColor.white backgroundColor: MainColor.white,
}, },
required: { required: {
color: MainColor.red color: MainColor.red,
} },
}} }}
label="Facebook" label="Facebook"
value={medsos.facebook} value={data.facebook}
placeholder="Facebook" placeholder="Facebook"
onChange={(val) => { onChange={(val) => {
setMedsos({ setData({
...medsos, ...data,
facebook: val.target.value, facebook: val.target.value,
}); });
}} }}
@@ -63,21 +123,21 @@ export default function Portofolio_EditMedsosBisnis({
<TextInput <TextInput
styles={{ styles={{
label: { label: {
color: MainColor.white color: MainColor.white,
}, },
input: { input: {
backgroundColor: MainColor.white backgroundColor: MainColor.white,
}, },
required: { required: {
color: MainColor.red color: MainColor.red,
} },
}} }}
label="Instagram" label="Instagram"
value={medsos.instagram} value={data.instagram}
placeholder="Instagram" placeholder="Instagram"
onChange={(val) => { onChange={(val) => {
setMedsos({ setData({
...medsos, ...data,
instagram: val.target.value, instagram: val.target.value,
}); });
}} }}
@@ -85,21 +145,21 @@ export default function Portofolio_EditMedsosBisnis({
<TextInput <TextInput
styles={{ styles={{
label: { label: {
color: MainColor.white color: MainColor.white,
}, },
input: { input: {
backgroundColor: MainColor.white backgroundColor: MainColor.white,
}, },
required: { required: {
color: MainColor.red color: MainColor.red,
} },
}} }}
label="Tiktok" label="Tiktok"
value={medsos.tiktok} value={data.tiktok}
placeholder="Tiktok" placeholder="Tiktok"
onChange={(val) => { onChange={(val) => {
setMedsos({ setData({
...medsos, ...data,
tiktok: val.target.value, tiktok: val.target.value,
}); });
}} }}
@@ -107,21 +167,21 @@ export default function Portofolio_EditMedsosBisnis({
<TextInput <TextInput
styles={{ styles={{
label: { label: {
color: MainColor.white color: MainColor.white,
}, },
input: { input: {
backgroundColor: MainColor.white backgroundColor: MainColor.white,
}, },
required: { required: {
color: MainColor.red color: MainColor.red,
} },
}} }}
label="Twitter" label="Twitter"
value={medsos.twitter} value={data.twitter}
placeholder="Twitter" placeholder="Twitter"
onChange={(val) => { onChange={(val) => {
setMedsos({ setData({
...medsos, ...data,
twitter: val.target.value, twitter: val.target.value,
}); });
}} }}
@@ -129,21 +189,21 @@ export default function Portofolio_EditMedsosBisnis({
<TextInput <TextInput
styles={{ styles={{
label: { label: {
color: MainColor.white color: MainColor.white,
}, },
input: { input: {
backgroundColor: MainColor.white backgroundColor: MainColor.white,
}, },
required: { required: {
color: MainColor.red color: MainColor.red,
} },
}} }}
label="Youtube" label="Youtube"
value={medsos.youtube} value={data.youtube}
placeholder="Youtube" placeholder="Youtube"
onChange={(val) => { onChange={(val) => {
setMedsos({ setData({
...medsos, ...data,
youtube: val.target.value, youtube: val.target.value,
}); });
}} }}
@@ -154,7 +214,7 @@ export default function Portofolio_EditMedsosBisnis({
radius={"xl"} radius={"xl"}
loading={loading ? true : false} loading={loading ? true : false}
loaderPosition="center" loaderPosition="center"
onClick={() => onUpdate(router, medsos, setLoading)} onClick={() => submitUpdate()}
style={{ style={{
backgroundColor: MainColor.yellow, backgroundColor: MainColor.yellow,
border: `2px solid ${AccentColor.yellow}`, border: `2px solid ${AccentColor.yellow}`,
@@ -165,23 +225,7 @@ export default function Portofolio_EditMedsosBisnis({
Update Update
</Button> </Button>
</Stack> </Stack>
</Paper> </ComponentGlobal_CardStyles>
</> </>
); );
} }
async function onUpdate(
router: AppRouterInstance,
medsos: MODEL_PORTOFOLIO_MEDSOS,
setLoading: any
) {
await Portofolio_funEditMedsosById(medsos).then((res) => {
if (res.status === 200) {
setLoading(true);
ComponentGlobal_NotifikasiBerhasil(res.message);
router.back();
} else {
ComponentGlobal_NotifikasiGagal(res.message);
}
});
}

View File

@@ -22,4 +22,7 @@ const data = [
}, },
]; ];
console.log(new Set(data.map((d) => d.authorId))); // console.log(new Set(data.map((d) => d.authorId)));
// contoh error
console.error("errornya disini klik aja",import.meta.url);