deskripsi:
- fix server action to API notification to admin
- fix api created job
This commit is contained in:
2025-03-27 15:37:44 +08:00
parent d4049a9fca
commit c94ecd8f9c
20 changed files with 482 additions and 58 deletions

View File

@@ -1,8 +1,6 @@
import { prisma } from "@/lib";
import backendLogger from "@/util/backendLogger";
import { NextResponse } from "next/server";
import { prisma } from "@/lib";
export const dynamic = "force-dynamic";
export async function GET(request: Request) {
try {
@@ -10,7 +8,7 @@ export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const search = searchParams.get("search");
const page = searchParams.get("page");
const dataTake = 10
const dataTake = 10;
const dataSkip = Number(page) * dataTake - dataTake;
if (!page) {
@@ -83,3 +81,68 @@ export async function GET(request: Request) {
});
}
}
export async function POST(request: Request) {
if (request.method !== "POST") {
return NextResponse.json(
{
success: false,
message: "Method not allowed",
},
{ status: 405 }
);
}
try {
const { data } = await request.json();
const fixData = await prisma.job.create({
data: {
title: data.title,
content: data.content,
deskripsi: data.deskripsi,
authorId: data.authorId,
imageId: data.imageId ?? null,
},
select: {
id: true,
authorId: true,
MasterStatus: {
select: {
name: true,
},
},
title: true,
},
});
if (!fixData) {
return NextResponse.json(
{
success: false,
message: "Failed created job",
},
{ status: 400 }
);
}
return NextResponse.json(
{
success: true,
message: "Success created job",
data: fixData,
},
{ status: 201 }
);
} catch (error) {
console.log("Error created job", error);
return NextResponse.json(
{
success: false,
message: "Error created job",
error: (error as Error).message || error,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,72 @@
import { NextResponse } from "next/server";
import {prisma} from "@/lib"
interface NotificationData {
userId: string;
appId: string;
status: string;
title: string;
pesan: string;
kategoriApp: string;
}
export async function POST(request: Request) {
try {
const { data }: { data: NotificationData } = await request.json();
// Validasi input
if (!data || !data.userId || !data.title || !data.pesan) {
return NextResponse.json(
{
success: false,
message: "Missing required fields",
},
{ status: 400 }
);
}
// Ambil semua admin aktif
const getAdmin = await prisma.user.findMany({
where: {
active: true,
masterUserRoleId: "2",
},
});
// Buat notifikasi untuk semua admin secara paralel
const createPromises = getAdmin.map((a) =>
prisma.notifikasi.create({
data: {
adminId: a.id,
userId: data.userId,
appId: data.appId,
status: data.status,
title: data.title,
pesan: data.pesan,
kategoriApp: data.kategoriApp,
userRoleId: "2",
},
})
);
await Promise.all(createPromises);
return NextResponse.json(
{
success: true,
message: "Successfully created notifications for admins",
},
{ status: 201 }
);
} catch (error) {
console.error("Error creating notification for admin:", error);
return NextResponse.json(
{
success: false,
message: "Error creating notification for admin",
error: (error as Error).message || "Unknown error",
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,65 @@
import { NextResponse } from "next/server";
import { decrypt } from "../../../app/(auth)/_lib/decrypt";
import { cookies } from "next/headers";
export const dynamic = "force-dynamic";
interface DecryptedUser {
id: string;
[key: string]: any;
}
export async function GET(request: Request) {
const SESSION_KEY = process.env.NEXT_PUBLIC_BASE_SESSION_KEY;
const TOKEN_KEY = process.env.NEXT_PUBLIC_BASE_TOKEN_KEY;
if (!SESSION_KEY || !TOKEN_KEY) {
return NextResponse.json(
{ success: false, message: "Server configuration error" },
{ status: 500 }
);
}
try {
const cookieStore = cookies();
const sessionCookie = cookieStore.get(SESSION_KEY);
if (!sessionCookie || !sessionCookie.value) {
return NextResponse.json(
{ success: false, message: "Unauthorized: No session found" },
{ status: 401 }
);
}
const cekUser = (await decrypt({
token: sessionCookie.value,
encodedKey: TOKEN_KEY,
})) as DecryptedUser | null;
if (!cekUser || !cekUser.id) {
return NextResponse.json(
{ success: false, message: "Unauthorized: Invalid session" },
{ status: 401 }
);
}
return NextResponse.json(
{
success: true,
message: "User session retrieved successfully",
data: { id: cekUser.id },
},
{ status: 200 }
);
} catch (error) {
console.error("Error retrieving user session:", error);
return NextResponse.json(
{
success: false,
message: "Error retrieving user session",
error: (error as Error).message || "Unknown error",
},
{ status: 500 }
);
}
}

View File

@@ -1,9 +1,12 @@
import { funGetUserIdByToken } from "@/app_modules/_global/fun/get";
import { Job_Create } from "@/app_modules/job";
export default async function Page() {
const userLoginId = await funGetUserIdByToken();
return (
<>
<Job_Create />
<Job_Create userLoginId={userLoginId} />
</>
);
}

View File

@@ -1,4 +1,4 @@
export { apiGetPdfToImage };
export { apiGetPdfToImage, apiCreatedNotificationToAdmin, apiGetSeasonUserId };
export interface PageData {
imageUrl: string;
@@ -35,10 +35,7 @@ const apiGetPdfToImage = async ({ id }: { id: string }) => {
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Failed get file",
errorData?.message || "Unknown error"
);
console.error("Failed get file", errorData?.message || "Unknown error");
return null;
}
@@ -50,3 +47,68 @@ const apiGetPdfToImage = async ({ id }: { id: string }) => {
throw error; // Re-throw the error to handle it in the calling function
}
};
const apiCreatedNotificationToAdmin = async ({ data }: { data: any }) => {
try {
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/notifications/to-admin`, {
method: "POST",
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 created notifications",
response.statusText,
errorData
);
throw new Error(errorData?.message || "Failed to created notifications");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error to created notifications", error);
throw error; // Re-throw the error to handle it in the calling function
}
};
const apiGetSeasonUserId = async () => {
try {
const response = await fetch(`/api/season`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
// Check if the response is OK
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error(
"Failed to created notifications",
response.statusText,
errorData
);
throw new Error(errorData?.message || "Failed to created notifications");
}
return await response.json();
} catch (error) {
console.error("Error get user id", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -20,41 +20,157 @@ import { WibuRealtime } from "wibu-pkg";
import { job_funCreateNoFile, job_funCreateWithFile } from "../../fun";
import { gs_job_hot_menu } from "../../global_state";
import { MODEL_JOB } from "../../model/interface";
import { apiCreatedJob } from "../../lib/api_fetch_job";
import {
apiCreatedNotificationToAdmin,
apiGetSeasonUserId,
} from "@/app_modules/_global/lib/api_fetch_global";
import { useShallowEffect } from "@mantine/hooks";
import { apiGetUserId } from "@/app_modules/_global/lib/api_user";
function Job_ComponentButtonSaveCreate({
value,
file,
userLoginId,
}: {
value: MODEL_JOB;
file: File;
userLoginId: string;
}) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [hotMenu, setHotMenu] = useAtom(gs_job_hot_menu);
async function onCreate() {
// async function onCreate() {
// try {
// setIsLoading(true);
// if (file === null) {
// const createNoFile = await job_funCreateNoFile({
// data: value,
// });
// if (createNoFile.status === 201) {
// const dataNotifikasi: IRealtimeData = {
// appId: createNoFile.data?.id as any,
// status: createNoFile.data?.MasterStatus?.name as any,
// userId: createNoFile.data?.authorId as any,
// pesan: createNoFile.data?.title as any,
// kategoriApp: "JOB",
// title: "Job baru",
// };
// const notif = await notifikasiToAdmin_funCreate({
// data: dataNotifikasi as any,
// });
// if (notif.status === 201) {
// WibuRealtime.setData({
// type: "notification",
// pushNotificationTo: "ADMIN",
// });
// WibuRealtime.setData({
// type: "trigger",
// pushNotificationTo: "ADMIN",
// dataMessage: dataNotifikasi,
// });
// setHotMenu(2);
// router.replace(RouterJob.status({ id: "2" }));
// ComponentGlobal_NotifikasiBerhasil(createNoFile.message);
// }
// } else {
// setIsLoading(false);
// ComponentGlobal_NotifikasiGagal(createNoFile.message);
// }
// } else {
// const uploadFile = await funGlobal_UploadToStorage({
// file: file,
// dirId: DIRECTORY_ID.job_image,
// });
// if (!uploadFile.success) {
// setIsLoading(false);
// ComponentGlobal_NotifikasiPeringatan("Gagal upload gambar");
// return;
// }
// const createWithFile = await job_funCreateWithFile({
// data: value,
// fileId: uploadFile.data.id,
// });
// if (createWithFile.status === 201) {
// const dataNotifikasi: IRealtimeData = {
// appId: createWithFile.data?.id as any,
// status: createWithFile.data?.MasterStatus?.name as any,
// userId: createWithFile.data?.authorId as any,
// pesan: createWithFile.data?.title as any,
// kategoriApp: "JOB",
// title: "Job baru",
// };
// const notif = await notifikasiToAdmin_funCreate({
// data: dataNotifikasi as any,
// });
// if (notif.status === 201) {
// WibuRealtime.setData({
// type: "notification",
// pushNotificationTo: "ADMIN",
// });
// WibuRealtime.setData({
// type: "trigger",
// pushNotificationTo: "ADMIN",
// dataMessage: dataNotifikasi,
// });
// setHotMenu(2);
// router.replace(RouterJob.status({ id: "2" }));
// ComponentGlobal_NotifikasiBerhasil(createWithFile.message);
// }
// } else {
// setIsLoading(false);
// ComponentGlobal_NotifikasiGagal(createWithFile.message);
// }
// }
// } catch (error) {
// setIsLoading(false);
// clientLogger.error("Error create job", error);
// }
// }
async function handleCreated() {
try {
let fixData;
setIsLoading(true);
if (file === null) {
const createNoFile = await job_funCreateNoFile({
data: value,
fixData = {
...value,
authorId: userLoginId,
};
const responseNoFile = await apiCreatedJob({
data: fixData,
});
if (createNoFile.status === 201) {
if (responseNoFile) {
const dataNotifikasi: IRealtimeData = {
appId: createNoFile.data?.id as any,
status: createNoFile.data?.MasterStatus?.name as any,
userId: createNoFile.data?.authorId as any,
pesan: createNoFile.data?.title as any,
appId: responseNoFile.data?.id as any,
status: responseNoFile.data?.MasterStatus?.name as any,
userId: responseNoFile.data?.authorId as any,
pesan: responseNoFile.data?.title as any,
kategoriApp: "JOB",
title: "Job baru",
};
const notif = await notifikasiToAdmin_funCreate({
data: dataNotifikasi as any,
const responseNotification = await apiCreatedNotificationToAdmin({
data: dataNotifikasi,
});
if (notif.status === 201) {
if (responseNotification) {
WibuRealtime.setData({
type: "notification",
pushNotificationTo: "ADMIN",
@@ -68,13 +184,13 @@ function Job_ComponentButtonSaveCreate({
setHotMenu(2);
router.replace(RouterJob.status({ id: "2" }));
ComponentGlobal_NotifikasiBerhasil(createNoFile.message);
ComponentGlobal_NotifikasiBerhasil(responseNoFile.message);
}
} else {
setIsLoading(false);
ComponentGlobal_NotifikasiGagal(createNoFile.message);
}
}
// else {
// setIsLoading(false);
// ComponentGlobal_NotifikasiGagal(responseNoFile.message);
// }
} else {
const uploadFile = await funGlobal_UploadToStorage({
file: file,
@@ -87,17 +203,22 @@ function Job_ComponentButtonSaveCreate({
return;
}
const createWithFile = await job_funCreateWithFile({
data: value,
fileId: uploadFile.data.id,
fixData = {
...value,
authorId: userLoginId,
imageId: uploadFile.data.id,
};
const responseWithFile = await apiCreatedJob({
data: fixData,
});
if (createWithFile.status === 201) {
if (responseWithFile.status === 201) {
const dataNotifikasi: IRealtimeData = {
appId: createWithFile.data?.id as any,
status: createWithFile.data?.MasterStatus?.name as any,
userId: createWithFile.data?.authorId as any,
pesan: createWithFile.data?.title as any,
appId: responseWithFile.data?.id as any,
status: responseWithFile.data?.MasterStatus?.name as any,
userId: responseWithFile.data?.authorId as any,
pesan: responseWithFile.data?.title as any,
kategoriApp: "JOB",
title: "Job baru",
};
@@ -120,12 +241,9 @@ function Job_ComponentButtonSaveCreate({
setHotMenu(2);
router.replace(RouterJob.status({ id: "2" }));
ComponentGlobal_NotifikasiBerhasil(createWithFile.message);
ComponentGlobal_NotifikasiBerhasil(responseWithFile.message);
}
} else {
setIsLoading(false);
ComponentGlobal_NotifikasiGagal(createWithFile.message);
}
}
}
} catch (error) {
setIsLoading(false);
@@ -169,9 +287,7 @@ function Job_ComponentButtonSaveCreate({
loading={isLoading ? true : false}
w={"100%"}
radius={"xl"}
onClick={() => {
onCreate();
}}
onClick={handleCreated}
>
Simpan
</Button>

View File

@@ -29,7 +29,7 @@ import {
import { Job_ComponentButtonSaveCreate } from "../component";
import { defaultDeskripsi, defaultSyarat } from "../component/default_value";
export default function Job_Create() {
export default function Job_Create({userLoginId}: {userLoginId: string}) {
const [value, setValue] = useState({
title: "",
content: "",
@@ -174,7 +174,11 @@ export default function Job_Create() {
</Stack>
</ComponentGlobal_CardStyles>
<Job_ComponentButtonSaveCreate value={value as any} file={file as any} />
<Job_ComponentButtonSaveCreate
userLoginId={userLoginId}
value={value as any}
file={file as any}
/>
</Stack>
);
}

View File

@@ -14,7 +14,7 @@ import { useState } from "react";
import { useDisclosure, useShallowEffect } from "@mantine/hooks";
import UIGlobal_Modal from "@/app_modules/_global/ui/ui_modal";
import { clientLogger } from "@/util/clientLogger";
import { apiGetJobById } from "../../component/api_fetch_job";
import { apiGetJobById } from "../../lib/api_fetch_job";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function Job_DetailArsip() {

View File

@@ -21,7 +21,7 @@ import { job_getOneById } from "../../fun/get/get_one_by_id";
import { IRealtimeData } from "@/lib/global_state";
import { WibuRealtime } from "wibu-pkg";
import { clientLogger } from "@/util/clientLogger";
import { apiGetJobById } from "../../component/api_fetch_job";
import { apiGetJobById } from "../../lib/api_fetch_job";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function Job_DetailDraft() {

View File

@@ -9,7 +9,7 @@ import { IconBrandWhatsapp } from "@tabler/icons-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useState } from "react";
import { apiGetJobById } from "../../component/api_fetch_job";
import { apiGetJobById } from "../../lib/api_fetch_job";
import ComponentJob_DetailData from "../../component/detail/detail_data";
import { MODEL_JOB } from "../../model/interface";

View File

@@ -15,7 +15,7 @@ import { useDisclosure, useShallowEffect } from "@mantine/hooks";
import { useAtom } from "jotai";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { apiGetJobById } from "../../component/api_fetch_job";
import { apiGetJobById } from "../../lib/api_fetch_job";
import ComponentJob_DetailData from "../../component/detail/detail_data";
import { Job_funEditArsipById } from "../../fun/edit/fun_edit_arsip_by_id";
import { gs_job_hot_menu } from "../../global_state";

View File

@@ -16,7 +16,7 @@ import { Job_funDeleteById } from "../../fun/delete/fun_delete_by_id";
import { Job_funEditStatusByStatusId } from "../../fun/edit/fun_edit_status_by_status_id";
import { MODEL_JOB } from "../../model/interface";
import { clientLogger } from "@/util/clientLogger";
import { apiGetJobById } from "../../component/api_fetch_job";
import { apiGetJobById } from "../../lib/api_fetch_job";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function Job_DetailReject() {

View File

@@ -14,7 +14,7 @@ import ComponentJob_DetailData from "../../component/detail/detail_data";
import { Job_funEditStatusByStatusId } from "../../fun/edit/fun_edit_status_by_status_id";
import { MODEL_JOB } from "../../model/interface";
import { clientLogger } from "@/util/clientLogger";
import { apiGetJobById } from "../../component/api_fetch_job";
import { apiGetJobById } from "../../lib/api_fetch_job";
import CustomSkeleton from "@/app_modules/components/CustomSkeleton";
export default function Job_DetailReview() {

View File

@@ -25,7 +25,7 @@ import { Job_ComponentButtonUpdate } from "../component";
import { clientLogger } from "@/util/clientLogger";
import { useShallowEffect } from "@mantine/hooks";
import { useParams } from "next/navigation";
import { apiGetJobById } from "../component/api_fetch_job";
import { apiGetJobById } from "../lib/api_fetch_job";
import { Job_SkeletonEdit } from "../component/skeleton/comp_skeleton_beranda";
const ReactQuill = dynamic(
() => {

View File

@@ -1,4 +1,10 @@
export { apiGetJob, apiGetJobArsip, apiGetJobById, apiGetJobByStatus };
export {
apiGetJob,
apiGetJobArsip,
apiGetJobById,
apiGetJobByStatus,
apiCreatedJob,
};
const apiGetJobByStatus = async ({
status,
@@ -166,3 +172,36 @@ const apiGetJobById = async ({ id }: { id: string }) => {
throw error; // Re-throw the error to handle it in the calling function
}
};
const apiCreatedJob = async ({ data }: { data: any }) => {
try {
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/job`, {
method: "POST",
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 created job", response.statusText, errorData);
throw new Error(errorData?.message || "Failed created job");
}
// Return the JSON response
return await response.json();
} catch (error) {
console.error("Error created job", error);
throw error; // Re-throw the error to handle it in the calling function
}
};

View File

@@ -10,7 +10,7 @@ import { useShallowEffect } from "@mantine/hooks";
import _ from "lodash";
import { ScrollOnly } from "next-scroll-loader";
import { useState } from "react";
import { apiGetJob, apiGetJobArsip } from "../../component/api_fetch_job";
import { apiGetJob, apiGetJobArsip } from "../../lib/api_fetch_job";
import ComponentJob_CardStatus from "../../component/card/card_view";
import { MODEL_JOB } from "../../model/interface";

View File

@@ -16,7 +16,7 @@ import {
Job_ComponentButtonUpdateBeranda,
Job_ComponentSkeletonBeranda,
} from "../../component";
import { apiGetJob } from "../../component/api_fetch_job";
import { apiGetJob } from "../../lib/api_fetch_job";
import ComponentJob_BerandaCardView from "../../component/beranda/card_view";
import { MODEL_JOB } from "../../model/interface";

View File

@@ -9,7 +9,7 @@ import { useState } from "react";
import ComponentJob_CardStatus from "../../component/card/card_view";
import job_getAllStatusPublish from "../../fun/get/status/get_list_publish";
import { useShallowEffect } from "@mantine/hooks";
import { apiGetJobByStatus } from "../../component/api_fetch_job";
import { apiGetJobByStatus } from "../../lib/api_fetch_job";
export default function Job_Publish({ nameStatus }: { nameStatus: string }) {
const [data, setData] = useState<any[] | null>(null);

View File

@@ -9,7 +9,7 @@ import { useState } from "react";
import ComponentJob_CardStatus from "../../component/card/card_view";
import job_getAllStatusReview from "../../fun/get/status/get_list_review";
import { useShallowEffect } from "@mantine/hooks";
import { apiGetJobByStatus } from "../../component/api_fetch_job";
import { apiGetJobByStatus } from "../../lib/api_fetch_job";
export default function Job_Review({ nameStatus }: { nameStatus: string }) {
const [data, setData] = useState<any[] | null>(null);

View File

@@ -11,7 +11,7 @@ import _ from "lodash";
import { ScrollOnly } from "next-scroll-loader";
import { useParams } from "next/navigation";
import { useState } from "react";
import { apiGetJobByStatus } from "../../component/api_fetch_job";
import { apiGetJobByStatus } from "../../lib/api_fetch_job";
import ComponentJob_CardStatus from "../../component/card/card_view";
export default function Job_NewViewStatus() {