Compare commits
11 Commits
mobile-not
...
mobile-not
| Author | SHA1 | Date | |
|---|---|---|---|
| 2086692897 | |||
| 87515ae19f | |||
| 44d6788f6e | |||
| ac634100b5 | |||
| 1b206102b0 | |||
| 94a545bd30 | |||
| d50fda90e0 | |||
| d3d4912a5f | |||
| b2e8bc3caf | |||
| f05571caa4 | |||
| 6507bdcd35 |
@@ -2,6 +2,14 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
|
||||
|
||||
## [1.5.33](https://wibugit.wibudev.com/wibu/hipmi/compare/v1.5.32...v1.5.33) (2026-01-06)
|
||||
|
||||
## [1.5.32](https://wibugit.wibudev.com/wibu/hipmi/compare/v1.5.31...v1.5.32) (2026-01-05)
|
||||
|
||||
## [1.5.31](https://wibugit.wibudev.com/wibu/hipmi/compare/v1.5.30...v1.5.31) (2025-12-24)
|
||||
|
||||
## [1.5.30](https://wibugit.wibudev.com/wibu/hipmi/compare/v1.5.29...v1.5.30) (2025-12-19)
|
||||
|
||||
## [1.5.29](https://wibugit.wibudev.com/wibu/hipmi/compare/v1.5.28...v1.5.29) (2025-12-17)
|
||||
|
||||
## [1.5.28](https://wibugit.wibudev.com/wibu/hipmi/compare/v1.5.27...v1.5.28) (2025-12-17)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hipmi",
|
||||
"version": "1.5.29",
|
||||
"version": "1.5.33",
|
||||
"private": true,
|
||||
"prisma": {
|
||||
"seed": "bun prisma/seed.ts"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Notifikasi" ADD COLUMN "type" TEXT;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Notifikasi" DROP CONSTRAINT "Notifikasi_userRoleId_fkey";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Notifikasi" ADD COLUMN "recipientId" TEXT,
|
||||
ADD COLUMN "senderId" TEXT,
|
||||
ALTER COLUMN "userRoleId" DROP NOT NULL;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Notifikasi" ADD CONSTRAINT "Notifikasi_userRoleId_fkey" FOREIGN KEY ("userRoleId") REFERENCES "MasterUserRole"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Notifikasi" ADD CONSTRAINT "Notifikasi_recipientId_fkey" FOREIGN KEY ("recipientId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Notifikasi" ADD CONSTRAINT "Notifikasi_senderId_fkey" FOREIGN KEY ("senderId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Notifikasi" ALTER COLUMN "appId" DROP NOT NULL,
|
||||
ALTER COLUMN "kategoriApp" DROP NOT NULL,
|
||||
ALTER COLUMN "pesan" DROP NOT NULL;
|
||||
@@ -59,6 +59,10 @@ model User {
|
||||
acceptedTermsAt DateTime?
|
||||
acceptedForumTermsAt DateTime?
|
||||
tokenUserDevices TokenUserDevice[]
|
||||
|
||||
// For Mobile App
|
||||
NotificationRecipient Notifikasi[] @relation("NotificationRecipient")
|
||||
NotificationSender Notifikasi[] @relation("NotificationSender")
|
||||
}
|
||||
|
||||
model MasterUserRole {
|
||||
@@ -978,23 +982,32 @@ model Notifikasi {
|
||||
isActive Boolean @default(true)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
appId String
|
||||
kategoriApp String
|
||||
pesan String
|
||||
appId String?
|
||||
kategoriApp String?
|
||||
pesan String?
|
||||
title String?
|
||||
status String?
|
||||
|
||||
isRead Boolean @default(false)
|
||||
readAt DateTime? // kapan user membaca notifikasi ini
|
||||
deepLink String? // misal: "announcement/123", "user/profile/cmha6wb9w0001cfndwl9fcse6"
|
||||
type String?
|
||||
|
||||
Role MasterUserRole? @relation(fields: [userRoleId], references: [id])
|
||||
userRoleId String
|
||||
userRoleId String?
|
||||
|
||||
User User? @relation("UserNotifikasi", fields: [userId], references: [id], map: "NotifikasiUser")
|
||||
userId String?
|
||||
Admin User? @relation("AdminNotifikasi", fields: [adminId], references: [id], map: "NotifikasiAdmin")
|
||||
adminId String?
|
||||
|
||||
// Recipient (user who receives the notification)
|
||||
recipient User? @relation("NotificationRecipient", fields: [recipientId], references: [id])
|
||||
recipientId String?
|
||||
|
||||
// Sender (user who sent the notification)
|
||||
sender User? @relation("NotificationSender", fields: [senderId], references: [id])
|
||||
senderId String?
|
||||
}
|
||||
|
||||
// MAPS
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { sessionCreate } from "@/app/(auth)/_lib/session_create";
|
||||
import { randomOTP } from "@/app_modules/auth/fun/rondom_otp";
|
||||
import { adminMessaging } from "@/lib/firebase-admin";
|
||||
import prisma from "@/lib/prisma";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
@@ -51,12 +52,6 @@ export async function POST(req: Request) {
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
// const token = await sessionCreate({
|
||||
// sessionKey: process.env.NEXT_PUBLIC_BASE_SESSION_KEY!,
|
||||
// encodedKey: process.env.NEXT_PUBLIC_BASE_TOKEN_KEY!,
|
||||
// user: createUser as any,
|
||||
// });
|
||||
|
||||
const createOtpId = await prisma.kodeOtp.create({
|
||||
data: {
|
||||
nomor: data.nomor,
|
||||
@@ -87,11 +82,89 @@ export async function POST(req: Request) {
|
||||
{ status: 400 }
|
||||
);
|
||||
|
||||
// =========== START SEND NOTIFICATION =========== //
|
||||
|
||||
const findAllUserBySendTo = await prisma.user.findMany({
|
||||
where: { masterUserRoleId: "2" },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
console.log("Users to notify:", findAllUserBySendTo);
|
||||
|
||||
const dataNotification = {
|
||||
title: "Pendaftaran Baru",
|
||||
type: "announcement",
|
||||
kategoriApp: "OTHER",
|
||||
createdAt: new Date(),
|
||||
pesan: "User baru telah melakukan registrasi. Ayo cek dan verifikasi!",
|
||||
deepLink: `/admin/user-access/${createUser.id}`,
|
||||
senderId: createUser.id,
|
||||
};
|
||||
|
||||
for (let a of findAllUserBySendTo) {
|
||||
const createdNotification = await prisma.notifikasi.create({
|
||||
data: {
|
||||
...dataNotification,
|
||||
recipientId: a.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (createdNotification) {
|
||||
const deviceToken = await prisma.tokenUserDevice.findMany({
|
||||
where: {
|
||||
userId: a.id,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
for (let i of deviceToken) {
|
||||
const message = {
|
||||
token: i.token,
|
||||
notification: {
|
||||
title: dataNotification.title,
|
||||
body: dataNotification.pesan,
|
||||
},
|
||||
data: {
|
||||
sentAt: new Date().toISOString(), // ✅ Simpan metadata di data
|
||||
id: createdNotification.id,
|
||||
deepLink: dataNotification.deepLink,
|
||||
},
|
||||
// Konfigurasi Android untuk prioritas tinggi
|
||||
android: {
|
||||
priority: "high" as const, // Kirim secepatnya, bahkan di doze mode untuk notifikasi penting
|
||||
notification: {
|
||||
channelId: "default", // Sesuaikan dengan channel yang kamu buat di Android
|
||||
},
|
||||
ttl: 0 as const, // Kirim secepatnya, jangan tunda
|
||||
},
|
||||
// Opsional: tambahkan untuk iOS juga
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
sound: "default" as const,
|
||||
// 'content-available': 1 as const, // jika butuh silent push
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await adminMessaging.send(message);
|
||||
console.log("✅ FCM sent successfully", "Response:", response);
|
||||
} catch (error: any) {
|
||||
console.error("❌ FCM send failed:", error);
|
||||
// Lanjutkan ke token berikutnya meski satu gagal
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =========== END SEND NOTIFICATION =========== //
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: "Registrasi Berhasil",
|
||||
// token: token,
|
||||
kodeId: createOtpId.id,
|
||||
},
|
||||
{ status: 201 }
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import prisma from "@/lib/prisma";
|
||||
import _ from "lodash";
|
||||
import { sendNotificationMobileToOneUser } from "@/lib/mobile/notification/send-notification";
|
||||
import { routeUserMobile } from "@/lib/mobile/route-page-mobile";
|
||||
|
||||
export { GET, PUT };
|
||||
|
||||
@@ -54,10 +56,14 @@ async function GET(request: Request, { params }: { params: { id: string } }) {
|
||||
async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
const { id } = params;
|
||||
const { data } = await request.json();
|
||||
|
||||
const { catatan, senderId } = data;
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const status = searchParams.get("status");
|
||||
const fixStatus = _.startCase(status as string);
|
||||
|
||||
|
||||
let fixData;
|
||||
try {
|
||||
const checkStatus = await prisma.masterStatus.findFirst({
|
||||
@@ -83,7 +89,7 @@ async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
},
|
||||
data: {
|
||||
masterStatusId: checkStatus.id,
|
||||
catatan: data,
|
||||
catatan: catatan,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -97,6 +103,18 @@ async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
},
|
||||
});
|
||||
|
||||
await sendNotificationMobileToOneUser({
|
||||
recipientId: updt.authorId as any,
|
||||
senderId: senderId,
|
||||
payload: {
|
||||
title: "Pengajuan Review",
|
||||
body: "Pengajuan data anda telah di tolak !",
|
||||
type: "announcement",
|
||||
kategoriApp: "JOB",
|
||||
deepLink: routeUserMobile.jobByStatus({ status: "reject" }),
|
||||
},
|
||||
});
|
||||
|
||||
fixData = updt;
|
||||
} else if (fixStatus === "Publish") {
|
||||
const updt = await prisma.job.update({
|
||||
@@ -118,6 +136,18 @@ async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
},
|
||||
});
|
||||
|
||||
await sendNotificationMobileToOneUser({
|
||||
recipientId: updt.authorId as any,
|
||||
senderId: senderId,
|
||||
payload: {
|
||||
title: "Pengajuan Review",
|
||||
body: "Selamat data anda telah terpublikasi",
|
||||
type: "announcement",
|
||||
kategoriApp: "JOB",
|
||||
deepLink: routeUserMobile.jobByStatus({ status: "publish" }),
|
||||
},
|
||||
});
|
||||
|
||||
fixData = updt;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,9 +34,15 @@ async function GET(request: Request, { params }: { params: { id: string } }) {
|
||||
async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
const { id } = params;
|
||||
const { data } = await request.json();
|
||||
const { searchParams } = new URL(request.url);
|
||||
const category = searchParams.get("category");
|
||||
|
||||
console.log("Received data:", data);
|
||||
console.log("User ID:", id);
|
||||
console.log("Category:", category);
|
||||
|
||||
try {
|
||||
if (data.active) {
|
||||
if (category === "access") {
|
||||
const updateData = await prisma.user.update({
|
||||
where: {
|
||||
id: id,
|
||||
@@ -47,7 +53,7 @@ async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
});
|
||||
|
||||
console.log("[Update Active Berhasil]", updateData);
|
||||
} else if (data.role) {
|
||||
} else if (category === "role") {
|
||||
const fixName = _.startCase(data.role.replace(/_/g, " "));
|
||||
|
||||
const checkRole = await prisma.masterUserRole.findFirst({
|
||||
@@ -68,6 +74,12 @@ async function PUT(request: Request, { params }: { params: { id: string } }) {
|
||||
});
|
||||
|
||||
console.log("[Update Role Berhasil]", updateData);
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
status: 400,
|
||||
success: false,
|
||||
message: "Invalid category",
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -8,10 +8,17 @@ async function DELETE(
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { id } = params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const deviceId = searchParams.get("deviceId");
|
||||
|
||||
console.log("ID", id);
|
||||
console.log("DEVICE ID", deviceId);
|
||||
|
||||
try {
|
||||
const findFirst = await prisma.tokenUserDevice.findFirst({
|
||||
where: {
|
||||
userId: id,
|
||||
deviceId: deviceId as any,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ export { POST, GET };
|
||||
async function POST(request: NextRequest) {
|
||||
const { data } = await request.json();
|
||||
try {
|
||||
console.log("Data >>", JSON.stringify(data, null, 2));
|
||||
|
||||
const { userId, platform, deviceId, model, appVersion, fcmToken } = data;
|
||||
|
||||
@@ -24,6 +23,9 @@ async function POST(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
console.log("✅ EX", existing);
|
||||
|
||||
let deviceToken;
|
||||
|
||||
if (existing) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sendNotificationMobileToManyUser } from "@/lib/mobile/notification/send-notification";
|
||||
import { routeAdminMobile } from "@/lib/mobile/route-page-mobile";
|
||||
import prisma from "@/lib/prisma";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
@@ -17,6 +19,25 @@ async function POST(request: Request) {
|
||||
},
|
||||
});
|
||||
|
||||
// kirim notifikasi ke semua admin untuk mengetahui ada job baru yang harus di review
|
||||
|
||||
const adminUsers = await prisma.user.findMany({
|
||||
where: { masterUserRoleId: "2" },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
await sendNotificationMobileToManyUser({
|
||||
recipientIds: adminUsers.map((user) => user.id),
|
||||
senderId: data.authorId,
|
||||
payload: {
|
||||
title: "Pengajuan Review",
|
||||
body: "Terdapat pengajuan baru yang perlu direview",
|
||||
type: "announcement",
|
||||
deepLink: routeAdminMobile.jobByStatus({ status: "review" }),
|
||||
kategoriApp: "JOB",
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
|
||||
197
src/app/api/mobile/notification/[id]/route.ts
Normal file
197
src/app/api/mobile/notification/[id]/route.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import { prisma } from "@/lib";
|
||||
import _ from "lodash";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NotificationProp } from "../route";
|
||||
import { adminMessaging } from "@/lib/firebase-admin";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { id } = params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const category = searchParams.get("category");
|
||||
|
||||
let fixData;
|
||||
const fixCategory = _.upperCase(category || "");
|
||||
|
||||
try {
|
||||
const data = await prisma.notifikasi.findMany({
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
where: {
|
||||
recipientId: id,
|
||||
kategoriApp: fixCategory,
|
||||
},
|
||||
});
|
||||
|
||||
fixData = data;
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: fixData,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { id } = params;
|
||||
|
||||
try {
|
||||
await prisma.notifikasi.update({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
data: {
|
||||
isRead: true,
|
||||
readAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Notifications marked as read",
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { id } = params;
|
||||
|
||||
const { data } = await request.json();
|
||||
|
||||
const {
|
||||
title,
|
||||
body: notificationBody,
|
||||
userLoginId,
|
||||
type,
|
||||
kategoriApp,
|
||||
appId,
|
||||
status,
|
||||
deepLink,
|
||||
} = data as NotificationProp;
|
||||
|
||||
console.log("Notification Send >>", data);
|
||||
|
||||
try {
|
||||
// Cari user yang login
|
||||
const findUserLogin = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userLoginId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!findUserLogin) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Cari token fcm user yang login
|
||||
const checkFcmToken = await prisma.tokenUserDevice.findFirst({
|
||||
where: {
|
||||
userId: findUserLogin.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!checkFcmToken) {
|
||||
return NextResponse.json(
|
||||
{ error: "FCM Token not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const created = await prisma.notifikasi.create({
|
||||
data: {
|
||||
title,
|
||||
type,
|
||||
createdAt: new Date(),
|
||||
appId,
|
||||
kategoriApp,
|
||||
pesan: notificationBody || "",
|
||||
userRoleId: findUserLogin.masterUserRoleId,
|
||||
status,
|
||||
deepLink,
|
||||
senderId: findUserLogin.id,
|
||||
recipientId: id,
|
||||
},
|
||||
});
|
||||
|
||||
if (created) {
|
||||
const deviceToken = await prisma.tokenUserDevice.findMany({
|
||||
where: {
|
||||
userId: id,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
for (let i of deviceToken) {
|
||||
const message = {
|
||||
token: i.token,
|
||||
notification: {
|
||||
title,
|
||||
body: notificationBody || "",
|
||||
},
|
||||
data: {
|
||||
sentAt: new Date().toISOString(), // ✅ Simpan metadata di data
|
||||
id: created.id,
|
||||
deepLink: deepLink || "",
|
||||
},
|
||||
// Konfigurasi Android untuk prioritas tinggi
|
||||
android: {
|
||||
priority: "high" as const, // Kirim secepatnya, bahkan di doze mode untuk notifikasi penting
|
||||
notification: {
|
||||
channelId: "default", // Sesuaikan dengan channel yang kamu buat di Android
|
||||
},
|
||||
|
||||
ttl: 0 as const, // Kirim secepatnya, jangan tunda
|
||||
},
|
||||
// Opsional: tambahkan untuk iOS juga
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
sound: "default" as const,
|
||||
// 'content-available': 1 as const, // jika butuh silent push
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await adminMessaging.send(message);
|
||||
console.log("✅ FCM sent successfully", "Response:", response);
|
||||
} catch (error: any) {
|
||||
console.error("❌ FCM send failed:", error);
|
||||
// Lanjutkan ke token berikutnya meski satu gagal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Notification sent successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("❌ FCM error:", error);
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
31
src/app/api/mobile/notification/[id]/unread-count/route.ts
Normal file
31
src/app/api/mobile/notification/[id]/unread-count/route.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { prisma } from "@/lib";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { id } = params;
|
||||
console.log("User ID:", id);
|
||||
|
||||
try {
|
||||
const data = await prisma.notifikasi.count({
|
||||
where: {
|
||||
recipientId: id,
|
||||
isRead: false,
|
||||
},
|
||||
});
|
||||
|
||||
console.log("List Notification >>", data);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: data,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: "Failed to get unread count",
|
||||
});
|
||||
}
|
||||
}
|
||||
210
src/app/api/mobile/notification/route.ts
Normal file
210
src/app/api/mobile/notification/route.ts
Normal file
@@ -0,0 +1,210 @@
|
||||
// app/api/test/notifications/route.ts
|
||||
import { prisma } from "@/lib";
|
||||
import { adminMessaging } from "@/lib/firebase-admin";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export type NotificationProp = {
|
||||
title: string;
|
||||
body: string;
|
||||
userLoginId: string;
|
||||
appId?: string;
|
||||
status?: string;
|
||||
kategoriApp?: string;
|
||||
type?: string;
|
||||
deepLink?: string;
|
||||
};
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { data } = await request.json();
|
||||
|
||||
const {
|
||||
title,
|
||||
body: notificationBody,
|
||||
userLoginId,
|
||||
type,
|
||||
kategoriApp,
|
||||
appId,
|
||||
status,
|
||||
deepLink,
|
||||
} = data as NotificationProp;
|
||||
|
||||
console.log("Notification Send >>", data);
|
||||
|
||||
// Cari user yang login
|
||||
const findUserLogin = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userLoginId,
|
||||
},
|
||||
});
|
||||
|
||||
if (!findUserLogin) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Cari token fcm user yang login
|
||||
const checkFcmToken = await prisma.tokenUserDevice.findFirst({
|
||||
where: {
|
||||
userId: findUserLogin.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!checkFcmToken) {
|
||||
return NextResponse.json(
|
||||
{ error: "FCM Token not found" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Jika user yang masuk maka notifikasik akan dikirim ke semua admin , begitu sebaliknya !
|
||||
const filterByCurrentLoginId =
|
||||
findUserLogin.masterUserRoleId === "1" ? "2" : "1";
|
||||
|
||||
// Cari user yang akan menerima notifikasi
|
||||
const findAllUserBySendTo = await prisma.user.findMany({
|
||||
where: {
|
||||
masterUserRoleId: filterByCurrentLoginId,
|
||||
NOT: {
|
||||
id: findUserLogin.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log("Find All User By Send To >>", findAllUserBySendTo);
|
||||
|
||||
for (let a of findAllUserBySendTo) {
|
||||
const responseCreatedNotifications = await createNotification({
|
||||
title,
|
||||
type: type as string,
|
||||
createdAt: new Date(),
|
||||
pesan: notificationBody || "",
|
||||
appId: appId as string,
|
||||
kategoriApp: kategoriApp as string,
|
||||
userRoleId: findUserLogin.masterUserRoleId,
|
||||
status: status,
|
||||
deepLink: deepLink,
|
||||
senderId: findUserLogin.id,
|
||||
recipientId: a.id,
|
||||
});
|
||||
|
||||
if (responseCreatedNotifications) {
|
||||
const deviceToken = await prisma.tokenUserDevice.findMany({
|
||||
where: {
|
||||
userId: a.id,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
|
||||
for (let i of deviceToken) {
|
||||
const message = {
|
||||
token: i.token,
|
||||
notification: {
|
||||
title,
|
||||
body: notificationBody || "",
|
||||
},
|
||||
data: {
|
||||
sentAt: new Date().toISOString(), // ✅ Simpan metadata di data
|
||||
id: responseCreatedNotifications.id,
|
||||
deepLink: deepLink || "",
|
||||
// contoh: senderId, type, etc.
|
||||
},
|
||||
// Konfigurasi Android untuk prioritas tinggi
|
||||
android: {
|
||||
priority: "high" as const, // Kirim secepatnya, bahkan di doze mode untuk notifikasi penting
|
||||
notification: {
|
||||
channelId: "default", // Sesuaikan dengan channel yang kamu buat di Android
|
||||
// Opsional: sesuaikan icon & warna
|
||||
// icon: 'ic_notification',
|
||||
// color: '#FFD700',
|
||||
},
|
||||
// FCM akan bangunkan app jika perlu
|
||||
ttl: 0 as const, // Kirim secepatnya, jangan tunda
|
||||
},
|
||||
// Opsional: tambahkan untuk iOS juga
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
sound: "default" as const,
|
||||
// 'content-available': 1 as const, // jika butuh silent push
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await adminMessaging.send(message);
|
||||
console.log(
|
||||
"✅ FCM sent to token:",
|
||||
"Response:",
|
||||
response
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error("❌ FCM send failed for token:", i.token, error);
|
||||
// Lanjutkan ke token berikutnya meski satu gagal
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
message: "Failed to create notification",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Notification sent successfully",
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("❌ FCM error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Failed to send FCM" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function createNotification({
|
||||
title,
|
||||
type,
|
||||
createdAt,
|
||||
appId,
|
||||
kategoriApp,
|
||||
pesan,
|
||||
userRoleId,
|
||||
status,
|
||||
deepLink,
|
||||
senderId,
|
||||
recipientId,
|
||||
}: {
|
||||
title: string;
|
||||
type: string;
|
||||
createdAt: Date;
|
||||
appId: string;
|
||||
kategoriApp: string;
|
||||
userRoleId: string;
|
||||
status?: string;
|
||||
deepLink?: string;
|
||||
pesan: string;
|
||||
|
||||
senderId: string;
|
||||
recipientId: string;
|
||||
}) {
|
||||
const createNotification = await prisma.notifikasi.create({
|
||||
data: {
|
||||
title,
|
||||
type,
|
||||
createdAt,
|
||||
appId,
|
||||
kategoriApp,
|
||||
pesan,
|
||||
userRoleId,
|
||||
status,
|
||||
deepLink,
|
||||
senderId,
|
||||
recipientId,
|
||||
},
|
||||
});
|
||||
|
||||
return createNotification;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// app/api/test/notifications/route.ts
|
||||
import { adminMessaging } from "@/lib/firebase-admin";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { data } = await request.json();
|
||||
const { fcmToken, title, body: notificationBody, userLoginId } = data;
|
||||
|
||||
console.log("Data Notifikasi >>", data);
|
||||
|
||||
if (!fcmToken || !title) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing fcmToken or title" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const deviceToken = await prisma.tokenUserDevice.findMany({
|
||||
where: {
|
||||
isActive: true,
|
||||
NOT: {
|
||||
userId: userLoginId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
for (let i of deviceToken) {
|
||||
const message = {
|
||||
token: i.token,
|
||||
notification: {
|
||||
title,
|
||||
body: notificationBody || "",
|
||||
},
|
||||
data: {
|
||||
sentAt: new Date().toISOString(), // ✅ Simpan metadata di data
|
||||
// contoh: senderId, type, etc.
|
||||
},
|
||||
};
|
||||
console.log("[MSG]", message);
|
||||
|
||||
const response = await adminMessaging.send(message);
|
||||
console.log("✅ FCM sent:", response);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Notification sent successfully",
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("❌ FCM error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Failed to send FCM" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
117
src/lib/mobile/notification/send-notification.ts
Normal file
117
src/lib/mobile/notification/send-notification.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
// lib/notifications/send-notification.ts
|
||||
import { adminMessaging } from "@/lib/firebase-admin";
|
||||
import prisma from "@/lib/prisma";
|
||||
import { NotificationMobilePayload } from "../../../../types/type-mobile-notification";
|
||||
import _ from "lodash";
|
||||
|
||||
/**
|
||||
* Kirim notifikasi ke satu user (semua device aktifnya)
|
||||
* @param recipientId - ID penerima
|
||||
* @param senderId - ID pengirim
|
||||
* @param payload - Data notifikasi
|
||||
*/
|
||||
|
||||
export async function sendNotificationMobileToOneUser({
|
||||
recipientId,
|
||||
senderId,
|
||||
payload,
|
||||
}: {
|
||||
recipientId: string;
|
||||
senderId: string;
|
||||
payload: NotificationMobilePayload;
|
||||
}) {
|
||||
try {
|
||||
const kategoriToNormalCase = _.lowerCase(payload.kategoriApp);
|
||||
const titleFix = `${_.startCase(kategoriToNormalCase)}: ${payload.title}`;
|
||||
console.log("titleFix", titleFix);
|
||||
|
||||
// 1. Simpan notifikasi ke DB
|
||||
const notification = await prisma.notifikasi.create({
|
||||
data: {
|
||||
title: titleFix,
|
||||
pesan: payload.body,
|
||||
deepLink: payload.deepLink,
|
||||
kategoriApp: payload.kategoriApp,
|
||||
recipientId: recipientId,
|
||||
senderId: senderId,
|
||||
type: payload.type.trim(),
|
||||
},
|
||||
});
|
||||
|
||||
// 2. Ambil semua token aktif milik penerima
|
||||
const tokens = await prisma.tokenUserDevice.findMany({
|
||||
where: { userId: recipientId, isActive: true },
|
||||
select: { token: true, id: true },
|
||||
});
|
||||
|
||||
if (tokens.length === 0) {
|
||||
console.warn(`No active tokens found for user ${recipientId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Kirim FCM ke semua token
|
||||
|
||||
await Promise.allSettled(
|
||||
tokens.map(async ({ token, id }) => {
|
||||
try {
|
||||
await adminMessaging.send({
|
||||
token,
|
||||
notification: {
|
||||
title: titleFix,
|
||||
body: payload.body,
|
||||
},
|
||||
data: {
|
||||
sentAt: new Date().toISOString(), // ✅ Simpan metadata di data
|
||||
id: notification.id,
|
||||
deepLink: payload.deepLink,
|
||||
},
|
||||
android: {
|
||||
priority: "high" as const,
|
||||
notification: { channelId: "default" },
|
||||
ttl: 0 as const,
|
||||
},
|
||||
apns: {
|
||||
payload: { aps: { sound: "default" as const } },
|
||||
},
|
||||
});
|
||||
} catch (fcmError: any) {
|
||||
// Hapus token jika invalid
|
||||
console.log("fcmError", fcmError);
|
||||
if (fcmError.code === "messaging/invalid-registration-token") {
|
||||
await prisma.tokenUserDevice.delete({ where: { id: id } });
|
||||
console.log(`❌ Invalid token removed: ${token}`);
|
||||
}
|
||||
console.error(`FCM failed for token ${token}:`, fcmError.message);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
console.log(`✅ Notification sent to user ${recipientId}`);
|
||||
} catch (error) {
|
||||
console.error("Failed to send notification:", error);
|
||||
throw error; // biarkan caller handle error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kirim notifikasi ke banyak user
|
||||
*/
|
||||
export async function sendNotificationMobileToManyUser({
|
||||
recipientIds,
|
||||
senderId,
|
||||
payload,
|
||||
}: {
|
||||
recipientIds: string[];
|
||||
senderId: string;
|
||||
payload: NotificationMobilePayload;
|
||||
}) {
|
||||
await Promise.allSettled(
|
||||
recipientIds.map((id) =>
|
||||
sendNotificationMobileToOneUser({
|
||||
recipientId: id,
|
||||
senderId: senderId,
|
||||
payload: payload,
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
19
src/lib/mobile/route-page-mobile.ts
Normal file
19
src/lib/mobile/route-page-mobile.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export { routeAdminMobile, routeUserMobile };
|
||||
|
||||
type StatusApp = "review" | "draft" | "reject" | "publish";
|
||||
|
||||
const routeAdminMobile = {
|
||||
userAccess: ({ id }: { id: string }) => `/admin/user-access/${id}`,
|
||||
// JOB
|
||||
jobDetail: ({ id, status }: { id: string; status: StatusApp }) =>
|
||||
`/admin/job/${id}/${status}`,
|
||||
jobByStatus: ({ status }: { status: StatusApp }) =>
|
||||
`/admin/job/${status}/status`,
|
||||
};
|
||||
|
||||
const routeUserMobile = {
|
||||
home: `/(user)/home`,
|
||||
// JOB
|
||||
jobByStatus: ({ status }: { status?: StatusApp }) =>
|
||||
`/job/(tabs)/status?status=${status}`,
|
||||
};
|
||||
36
types/type-mobile-notification.ts
Normal file
36
types/type-mobile-notification.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
// Jika semua custom type diawali "custom_"
|
||||
|
||||
export type NotificationMobilePayload = {
|
||||
title: NotificationMobileTitleType;
|
||||
body: NotificationMobileBodyType;
|
||||
userLoginId?: string;
|
||||
appId?: string;
|
||||
status?: string;
|
||||
type: "announcement" | "trigger";
|
||||
deepLink: string;
|
||||
kategoriApp: TypeNotificationCategoryApp;
|
||||
};
|
||||
|
||||
export type NotificationMobileTitleType =
|
||||
| (string & { __type: "NotificationMobileTitleType" })
|
||||
| "Pengajuan Review"
|
||||
| "Review Selesai";
|
||||
|
||||
export type NotificationMobileBodyType =
|
||||
// USER
|
||||
| (string & { __type: "NotificationMobileBodyType" })
|
||||
| "Terdapat pengajuan baru yang perlu direview"
|
||||
|
||||
// ADMIN
|
||||
| "Pengajuan data anda telah di tolak !"
|
||||
| "Selamat data anda telah terpublikasi"
|
||||
|
||||
export type TypeNotificationCategoryApp =
|
||||
| "EVENT"
|
||||
| "JOB"
|
||||
| "VOTING"
|
||||
| "DONASI"
|
||||
| "INVESTASI"
|
||||
| "COLLABORATION"
|
||||
| "FORUM"
|
||||
| "OTHER";
|
||||
7
x.sh
7
x.sh
@@ -3,10 +3,13 @@ URL="http://localhost:3000"
|
||||
# curl -X GET -H "Authorization: Bearer $TOKEN" ${URL}/api/middleware
|
||||
# curl -X GET -H "Cookie: hipmi-key=$TOKEN; user_id=789" ${URL}/dev/home | tee test.html
|
||||
|
||||
curl -X POST ${URL}/api/mobile/notifications \
|
||||
curl -X POST ${URL}/api/mobile/notification \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"fcmToken": "cVmHm-3P4E-1vjt6AA9kSF:APA91bHTkHjGTLxrFsb6Le6bZmzboZhwMGYXU4p0FP9yEeXixLDXNKS4F5vLuZV3sRgSnjjQsPpLOgstVLHJB8VJTObctKLdN-CxAp4dnP7Jbc_mH53jWvs",
|
||||
"title": "Test dari Backend (App Router)!",
|
||||
"body": "Berhasil di App Router!"
|
||||
"body": "Berhasil di App Router!",
|
||||
"userLoginId": "cmha7p6yc0000cfoe5w2e7gdr",
|
||||
"type": "NOTIFICATION",
|
||||
"kategoriApp": "PERCOBAAN"
|
||||
}'
|
||||
Reference in New Issue
Block a user