feat admin sticker

deksrupsi:
- edit stiker
- hapu stiker
This commit is contained in:
2025-05-16 14:32:56 +08:00
parent f245969602
commit 9733efb4f3
9 changed files with 728 additions and 72 deletions

View File

@@ -0,0 +1,137 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib";
export { GET, PUT, DELETE };
async function GET(request: Request, { params }: { params: { id: string } }) {
const method = request.method;
if (method !== "GET") {
return NextResponse.json(
{ success: false, message: "Method not allowed" },
{ status: 405 }
);
}
try {
const { id } = params;
const sticker = await prisma.sticker.findUnique({
where: {
id: id,
},
include: {
MasterEmotions: true,
},
});
return NextResponse.json(
{ success: true, message: "Success get data sticker", data: sticker },
{ status: 200 }
);
} catch (error) {
console.error("Error get data sticker", error);
return NextResponse.json(
{ success: false, message: "Error get data sticker" },
{ status: 500 }
);
}
}
async function PUT(request: Request, { params }: { params: { id: string } }) {
const method = request.method;
if (method !== "PUT") {
return NextResponse.json(
{ success: false, message: "Method not allowed" },
{ status: 405 }
);
}
try {
const { id } = params;
const data = await request.json();
if (data.fileId) {
const updatedDataWithFile = await prisma.sticker.update({
where: {
id: id,
},
data: {
fileId: data.fileId,
MasterEmotions: {
set: data.emotions.map((value: string) => ({ value })), // ✅ replace relasi
},
},
});
return NextResponse.json({
success: true,
message: "Sticker updated successfully",
data: updatedDataWithFile,
});
}
const updatedDataWithoutFile = await prisma.sticker.update({
where: {
id: id,
},
data: {
MasterEmotions: {
set: data.emotions.map((value: string) => ({ value })), // ✅ replace relasi
},
},
});
if (!updatedDataWithoutFile) {
return NextResponse.json(
{ success: false, message: "Failed to update sticker" },
{ status: 400 }
);
}
return NextResponse.json({
success: true,
message: "Sticker updated successfully",
data: updatedDataWithoutFile,
});
} catch (error) {
console.error("Error updating sticker:", error);
return NextResponse.json(
{ success: false, message: "Failed to update sticker" },
{ status: 500 }
);
}
}
async function DELETE(
request: Request,
{ params }: { params: { id: string } }
) {
const method = request.method;
if (method !== "DELETE") {
return NextResponse.json(
{ success: false, message: "Method not allowed" },
{ status: 405 }
);
}
try {
const { id } = params;
const sticker = await prisma.sticker.delete({
where: {
id: id,
},
});
return NextResponse.json(
{ success: true, message: "Success delete sticker", data: sticker },
{ status: 200 }
);
} catch (error) {
console.error("Error delete sticker", error);
return NextResponse.json(
{ success: false, message: "Error delete sticker" },
{ status: 500 }
);
}
}

View File

@@ -61,6 +61,9 @@ async function GET(request: Request) {
try {
const sticker = await prisma.sticker.findMany({
orderBy: {
updatedAt: "desc",
},
include: {
MasterEmotions: true,
},

View File

@@ -0,0 +1,9 @@
import AdminAppInformation_ViewStickerDetail from "@/app_modules/admin/app_info/view/sticker/view_detail_sticker";
export default function Page() {
return (
<>
<AdminAppInformation_ViewStickerDetail />
</>
);
}

View File

@@ -65,3 +65,103 @@ export const apiAdminGetSticker = async () => {
}
};
export const apiAdminGetStickerById = async ({ id }: { id: 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;
}
const response = await fetch(`/api/sticker/${id}`, {
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("Failed to get sticker", response.statusText, errorData);
throw new Error(errorData?.message || "Failed to get sticker");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error get sticker", error);
throw error; // Re-throw the error to handle it in the calling function
}
};
export const apiAdminUpdateSticker = async ({ data }: { 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;
}
const response = await fetch(`/api/sticker/${data.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error("Failed to update sticker", response.statusText, errorData);
throw new Error(errorData?.message || "Failed to update sticker");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error update sticker", error);
throw error; // Re-throw the error to handle it in the calling function
}
};
export const apiAdminDeleteSticker = async ({ id }: { id: 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;
}
const response = await fetch(`/api/sticker/${id}`, {
method: "DELETE",
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 delete sticker", response.statusText, errorData);
throw new Error(errorData?.message || "Failed to delete sticker");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error delete sticker", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -55,7 +55,7 @@ export default function AdminAppInformation_Layout({
const handleClick = async (path: string) => {
if (path === pathname) return; // kalau sudah di halaman itu, jangan reload
setLoadingPath(path);
// setLoadingPath(path);
router.push(path);
};

View File

@@ -0,0 +1,337 @@
"use client";
import { MainColor } from "@/app_modules/_global/color";
import {
ComponentGlobal_BoxUploadImage,
ComponentGlobal_ButtonUploadFileImage,
} from "@/app_modules/_global/component";
import Component_V3_Label_TextInput from "@/app_modules/_global/component/new/comp_V3_label_text_input";
import {
funGlobal_DeleteFileById,
funGlobal_UploadToStorage,
} from "@/app_modules/_global/fun";
import { apiGetMasterEmotions } from "@/app_modules/_global/lib/api_fetch_master";
import { ISticker } from "@/app_modules/_global/lib/interface/stiker";
import { ComponentGlobal_NotifikasiPeringatan } from "@/app_modules/_global/notif_global";
import { ComponentAdminGlobal_TitlePage } from "@/app_modules/admin/_admin_global/_component";
import { Admin_ComponentBoxStyle } from "@/app_modules/admin/_admin_global/_component/comp_admin_boxstyle";
import { Admin_ComponentModal } from "@/app_modules/admin/_admin_global/_component/comp_admin_modal";
import { ComponentAdminGlobal_NotifikasiBerhasil } from "@/app_modules/admin/_admin_global/admin_notifikasi/notifikasi_berhasil";
import { ComponentAdminGlobal_NotifikasiGagal } from "@/app_modules/admin/_admin_global/admin_notifikasi/notifikasi_gagal";
import Admin_ComponentBackButton from "@/app_modules/admin/_admin_global/back_button";
import { Admin_V3_ComponentBreakpoint } from "@/app_modules/admin/_components_v3/comp_simple_grid_breakpoint";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { APIs, DIRECTORY_ID, pathAssetImage } from "@/lib";
import {
AspectRatio,
Box,
Button,
Center,
Chip,
Group,
Image,
Stack,
Text,
Title,
} from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { IconCheck, IconTrash } from "@tabler/icons-react";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import {
apiAdminDeleteSticker,
apiAdminGetStickerById,
apiAdminUpdateSticker,
} from "../../lib/api_fetch_stiker";
import { AdminColor } from "@/app_modules/_global/color/color_pallet";
export default function AdminAppInformation_ViewStickerDetail() {
const router = useRouter();
const param = useParams<{ id: string }>();
const [file, setFile] = useState<File | null>(null);
const [img, setImg] = useState<any | null>(null);
const [listEmotion, setListEmotion] = useState<any[]>([]);
const [valueEmotion, setValueEmotion] = useState<any[]>([]);
const [data, setData] = useState<ISticker | null>(null);
const [loading, setLoading] = useState(false);
const [loadingDelete, setLoadingDelete] = useState(false);
const [openModalDelete, setOpenModalDelete] = useState(false);
useShallowEffect(() => {
onLoadData();
onLoadMasterEmotions();
}, []);
async function onLoadData() {
try {
const response = await apiAdminGetStickerById({ id: param.id });
if (response.success) {
setData(response.data);
setValueEmotion(response.data.MasterEmotions.map((e: any) => e.value));
}
} catch (error) {
console.error("Error fetching data", error);
}
}
async function onLoadMasterEmotions() {
try {
const response = await apiGetMasterEmotions();
if (response.success) {
setListEmotion(response.data);
}
} catch (error) {
console.error("Error on load master emotions:", error);
}
}
async function onUploadFile() {
try {
const response = await funGlobal_UploadToStorage({
file: file as File,
dirId: DIRECTORY_ID.sticker,
});
if (!response.success) {
ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
return;
} else {
const deleteFile = await funGlobal_DeleteFileById({
fileId: data?.fileId as string,
});
if (!deleteFile.success) {
ComponentGlobal_NotifikasiPeringatan("Gagal delete gambar");
return;
}
return response.data.id;
}
} catch (error) {
console.error("Error on upload file", error);
}
}
async function handleUpdateSticker({ fileId }: { fileId?: string }) {
try {
const response = await apiAdminUpdateSticker({
data: {
emotions: valueEmotion,
fileId: fileId || "",
id: param.id,
},
});
if (response.success) {
ComponentAdminGlobal_NotifikasiBerhasil("Berhasil disimpan");
router.back();
} else {
setLoading(false);
throw new Error("Failed to create sticker");
}
} catch (error) {
setLoading(false);
ComponentAdminGlobal_NotifikasiGagal("Gagal disimpan");
console.error("Error create sticker", error);
}
}
async function onSubmit() {
try {
setLoading(true);
if (file) {
const uploadFile = await onUploadFile();
if (!uploadFile) {
setLoading(false);
return;
}
await handleUpdateSticker({ fileId: uploadFile });
} else {
await handleUpdateSticker({});
}
} catch (error) {
console.error("Error on create sticker", error);
}
}
async function onDelete() {
try {
setLoadingDelete(true);
const response = await apiAdminDeleteSticker({ id: param.id });
if (response.success) {
const deleteFile = await funGlobal_DeleteFileById({
fileId: data?.fileId as string,
});
if (!deleteFile.success) {
ComponentGlobal_NotifikasiPeringatan("Gagal delete gambar");
return;
}
setLoadingDelete(false);
ComponentAdminGlobal_NotifikasiBerhasil("Berhasil dihapus");
router.back();
} else {
setLoadingDelete(false);
ComponentGlobal_NotifikasiPeringatan("Gagal dihapus");
}
} catch (error) {
setLoadingDelete(false);
ComponentAdminGlobal_NotifikasiGagal("Proses hapus error");
console.error("Error delete sticker", error);
}
}
return (
<>
<Stack>
<ComponentAdminGlobal_TitlePage name="Detail Stiker" />
<Admin_ComponentBackButton />
{/* <pre style={{ color: "white" }}>
{JSON.stringify(valueEmotion, null, 2)}
</pre> */}
<Admin_V3_ComponentBreakpoint lg={2} md={2} sm={1}>
{!listEmotion.length || !data ? (
<CustomSkeleton height={400} />
) : (
<Admin_ComponentBoxStyle>
<Stack>
<Stack spacing={"xs"}>
<ComponentGlobal_BoxUploadImage>
{img ? (
<AspectRatio ratio={1 / 1} mah={265} mx={"auto"}>
<Image
style={{
maxHeight: 250,
margin: "auto",
padding: "5px",
}}
alt="Foto"
height={250}
src={img}
/>
</AspectRatio>
) : (
<AspectRatio ratio={1 / 1} mah={265} mx={"auto"}>
<Image
style={{
maxHeight: 250,
margin: "auto",
padding: "5px",
}}
alt="Foto"
height={250}
src={
data.fileId
? APIs.GET({ fileId: data.fileId })
: pathAssetImage.no_image
}
/>
</AspectRatio>
)}
</ComponentGlobal_BoxUploadImage>
<Center>
<ComponentGlobal_ButtonUploadFileImage
accept="image/webp, image/jpeg, image/png"
onSetFile={setFile}
onSetImage={setImg}
/>
</Center>
</Stack>
<Stack>
<Stack>
<Component_V3_Label_TextInput text="Pilih emosi stiker" />
<Group style={{ display: "flex", flexWrap: "wrap" }}>
<Chip.Group
multiple
value={valueEmotion}
onChange={setValueEmotion}
>
{listEmotion.map((e, i) => {
return (
<Chip key={i} value={e.value}>
{e.label}
</Chip>
);
})}
</Chip.Group>
</Group>
</Stack>
<Box
mt={"xl"}
style={{
display: "flex",
justifyContent: "flex-end",
gap: "10px",
}}
>
<Button
color="red"
bg={MainColor.red}
loaderPosition="center"
radius="xl"
leftIcon={<IconTrash size={20} />}
onClick={() => setOpenModalDelete(true)}
>
Hapus
</Button>
<Button
color="green"
bg={MainColor.green}
loading={loading}
loaderPosition="center"
radius="xl"
leftIcon={<IconCheck size={20} />}
onClick={() => onSubmit()}
>
Simpan
</Button>
</Box>
</Stack>
</Stack>
</Admin_ComponentBoxStyle>
)}
</Admin_V3_ComponentBreakpoint>
<Admin_ComponentModal
opened={openModalDelete}
onClose={() => setOpenModalDelete(false)}
withCloseButton={false}
closeOnClickOutside={false}
size="md"
>
<Stack>
<Title order={5} c={AdminColor.white}>
Apakah anda yakin ingin menghapus stiker ini?
</Title>
<Group position="center">
<Button radius="xl" onClick={() => setOpenModalDelete(false)}>
Batal
</Button>
<Button
loading={loadingDelete}
loaderPosition="center"
radius="xl"
color="red"
bg={MainColor.red}
onClick={() => onDelete()}
>
Hapus
</Button>
</Group>
</Stack>
</Admin_ComponentModal>
</Stack>
</>
);
}

View File

@@ -261,7 +261,6 @@ export default function AdminAppInformation_ViewCreateSticker() {
<Button
color="green"
bg={MainColor.green}
disabled={loading}
loading={loading}
loaderPosition="center"
radius="xl"

View File

@@ -1,8 +1,12 @@
"use client";
import { AdminColor } from "@/app_modules/_global/color/color_pallet";
import {
AdminColor,
MainColor,
} from "@/app_modules/_global/color/color_pallet";
import { ISticker } from "@/app_modules/_global/lib/interface/stiker";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
import { APIs } from "@/lib";
import { APIs, pathAssetImage } from "@/lib";
import { RouterAdminAppInformation } from "@/lib/router_admin/router_app_information";
import {
Badge,
@@ -11,29 +15,33 @@ import {
Center,
Group,
Image,
Paper,
ScrollArea,
Spoiler,
Stack,
Switch,
Table,
Text,
} from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { Prisma } from "@prisma/client";
import { IconPencil, IconPlus } from "@tabler/icons-react";
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ComponentAdminGlobal_TitlePage } from "../../_admin_global/_component";
import { Admin_ComponentBoxStyle } from "../../_admin_global/_component/comp_admin_boxstyle";
import { apiAdminGetSticker } from "../lib/api_fetch_stiker";
import { ISticker } from "@/app_modules/_global/lib/interface/stiker";
export default function AdminAppInformation_ViewSticker() {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [loadingCreate, setLoadingCreate] = useState(false);
const [loadingDetail, setLoadingDetail] = useState<string | null>(null);
const [dataSticker, setDataSticker] = useState<ISticker[] | null>(null);
const [isActivation, setIsActivation] = useState(false);
const [updateStatus, setUpdateStatus] = useState({
id: "",
active: false,
});
useShallowEffect(() => {
const fetchData = async () => {
@@ -50,78 +58,20 @@ export default function AdminAppInformation_ViewSticker() {
fetchData();
}, []);
const rowTable = () => {
if (!Array.isArray(dataSticker) || dataSticker.length === 0) {
return (
<tr>
<td colSpan={12}>
<Center>
<Text color={"gray"}>Tidak ada data</Text>
</Center>
</td>
</tr>
);
}
return dataSticker.map((e, i) => (
<tr key={i}>
<td>
<Center>
<Button
radius={"xl"}
leftIcon={<IconPencil size={20} />}
onClick={() => {}}
>
Detail
</Button>
</Center>
</td>
<td>
<Center>
<Box bg="gray" p={"xs"}>
<Image
src={APIs.GET({ fileId: e.fileId, size: "200" })}
alt="Sticker"
width={100}
height={100}
/>
</Box>
</Center>
</td>
<td>
<Center>
<Box maw={300}>
<Spoiler
maxHeight={50}
hideLabel="Sembunyikan"
showLabel="Tampilkan"
>
<Group>
{e.MasterEmotions.map((e) => (
<Badge key={e.value}>{e.value}</Badge>
))}
</Group>
</Spoiler>
</Box>
</Center>
</td>
</tr>
));
};
return (
<>
<Stack>
<ComponentAdminGlobal_TitlePage name="Stiker " />
<Button
loading={isLoading}
loading={loadingCreate}
loaderPosition="center"
w={120}
radius={"xl"}
leftIcon={<IconPlus size={20} />}
onClick={() => {
router.push(RouterAdminAppInformation.createSticker);
setIsLoading(true);
setLoadingCreate(true);
}}
>
Tambah
@@ -145,15 +95,30 @@ export default function AdminAppInformation_ViewSticker() {
<th>
<Center c={AdminColor.white}>Aksi</Center>
</th>
{/* <th>
<Center c={AdminColor.white}>Status</Center>
</th> */}
<th>
<Center c={AdminColor.white}>Stiker</Center>
</th>
<th>
<Center c={AdminColor.white}>Kategori</Center>
<Text c={AdminColor.white}>Kategori</Text>
</th>
</tr>
</thead>
<tbody>{rowTable()}</tbody>
<tbody>
{rowTable({
dataSticker,
router,
loadingDetail,
setLoadingDetail,
isActivation,
setIsActivation,
updateStatus,
setUpdateStatus,
})}
</tbody>
</Table>
</ScrollArea>
</Admin_ComponentBoxStyle>
@@ -162,3 +127,108 @@ export default function AdminAppInformation_ViewSticker() {
</>
);
}
type RowTableProps = {
dataSticker: ISticker[] | null;
router: AppRouterInstance;
loadingDetail: string | null;
setLoadingDetail: (val: string | null) => void;
isActivation: boolean;
setIsActivation: (val: boolean) => void;
updateStatus: { id: string; active: boolean };
setUpdateStatus: (val: { id: string; active: boolean }) => void;
};
const rowTable = ({
dataSticker,
router,
loadingDetail,
setLoadingDetail,
isActivation,
setIsActivation,
updateStatus,
setUpdateStatus,
}: RowTableProps) => {
if (!Array.isArray(dataSticker) || dataSticker.length === 0) {
return (
<tr>
<td colSpan={12}>
<Center>
<Text color={"gray"}>Tidak ada data</Text>
</Center>
</td>
</tr>
);
}
return dataSticker.map((e, i) => (
<tr key={i}>
<td>
<Center>
<Button
loading={loadingDetail === e.id}
loaderPosition="center"
bg={MainColor.green}
color="green"
radius={"xl"}
leftIcon={<IconPencil size={20} />}
onClick={() => {
setLoadingDetail(e.id);
setTimeout(() => {
router.push(
RouterAdminAppInformation.detailSticker({ id: e.id })
);
setLoadingDetail(null);
}, 1000);
}}
>
Detail
</Button>
</Center>
</td>
{/* <td>
<Center>
<Switch
checked={e.isActive}
color="green"
onLabel="ON"
offLabel="OFF"
onChange={(val) => {
setIsActivation(true);
setUpdateStatus({
id: e?.id,
active: val.currentTarget.checked as any,
});
}}
/>
</Center>
</td> */}
<td>
<Center>
<Paper bg="gray" p={"xs"}>
<Image
src={
e.fileId
? APIs.GET({ fileId: e.fileId })
: pathAssetImage.no_image
}
alt="Sticker"
width={100}
height={100}
/>
</Paper>
</Center>
</td>
<td>
<Box maw={300}>
<Spoiler maxHeight={70} hideLabel="Sembunyikan" showLabel="Tampilkan">
<Group>
{e.MasterEmotions.map((e) => (
<Badge key={e.value}>{e.value}</Badge>
))}
</Group>
</Spoiler>
</Box>
</td>
</tr>
));
};

View File

@@ -6,4 +6,5 @@ export const RouterAdminAppInformation = {
// Sticker
sticker: "/dev/admin/app-information/sticker",
createSticker: "/dev/admin/app-information/sticker/create",
detailSticker: ({ id }: { id: string }) => `/dev/admin/app-information/sticker/${id}`,
};