Compare commits

...

27 Commits

Author SHA1 Message Date
a54f8599b4 API Mobile notifikasi job
Fix:
modified:   src/app/api/mobile/admin/job/[id]/route.ts
modified:   src/app/api/mobile/job/[id]/route.ts
modified:   src/app/api/mobile/job/route.ts
modified:   src/lib/mobile/route-page-mobile.ts
modified:   types/type-mobile-notification.ts

### No Issue
2026-01-08 18:35:32 +08:00
09825756f3 Merge branch 'mobile-notification/7-jan-26' of https://wibugit.wibudev.com/wibu/hipmi into mobile-notification/8-jan-26 2026-01-08 10:35:49 +08:00
2086692897 Fix API notifikasi untuk job
### No Issue
2026-01-08 10:14:35 +08:00
87515ae19f Notifikasi mobile job
Add:
 src/lib/mobile/
 types/type-mobile-notification.ts

Fix:
src/app/api/auth/mobile-register/route.ts
src/app/api/mobile/job/route.ts

### No Issue
2026-01-06 17:52:28 +08:00
44d6788f6e chore(release): 1.5.33 2026-01-06 12:24:28 +08:00
ac634100b5 Notifikasi ke admin untuk user baru mendaftar
Fix:

- prisma/schema.prisma
- src/app/api/auth/mobile-register/route.ts
- src/app/api/mobile/admin/user/[id]/route.ts
- src/app/api/mobile/notification/[id]/route.ts
- src/app/api/mobile/notification/route.ts

Add:
Migrasi untuk db table notifikasi
- prisma/migrations/20260105064508_fix_table_notifikasi_optional_data/

### No Issue
2026-01-06 12:20:12 +08:00
1b206102b0 Fix API Notifikasi
### No Issue
2026-01-05 14:04:08 +08:00
94a545bd30 chore(release): 1.5.32 2026-01-05 12:37:14 +08:00
3552cf4f39 Merge pull request 'mobile-notification API' (#36) from mobile-notification/24-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/36
2025-12-24 17:48:07 +08:00
d50fda90e0 Fix notifikasi API for mobile
Fix:
modified:   src/app/api/mobile/notification/[id]/route.ts
modified:   src/app/api/mobile/notification/[id]/unread-count/route.ts
modified:   src/app/api/mobile/notification/route.ts

### No Issue
2025-12-24 17:47:00 +08:00
d3d4912a5f chore(release): 1.5.31 2025-12-24 17:46:08 +08:00
b2e8bc3caf Fix database notification untuk mobile
Fix:
- prisma/migrations/20251223084450_add_recipient_and_sender

Add:
- prisma/schema.prisma
- src/app/api/mobile/auth/device-tokens/[id]/route.ts
- src/app/api/mobile/auth/device-tokens/route.ts
- src/app/api/mobile/notification/[id]/unread-count/route.ts
- src/app/api/mobile/notification/route.ts

### No Issue
2025-12-23 17:32:05 +08:00
d207b6feed Merge pull request 'Penerapan notifikasi mobile' (#35) from mobile-notification/19-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/35
2025-12-19 16:40:09 +08:00
f1c8432fdc Merge pull request 'Fix DB table donasi' (#33) from login-api/17-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/33
2025-12-17 14:44:53 +08:00
1cd4c3713e Merge pull request 'login-api/17-dec-25' (#31) from login-api/17-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/31
2025-12-17 11:43:32 +08:00
4307b383e3 Merge pull request 'Penerapan notifikasi mobil ke database' (#30) from mobile-notification/16-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/30
2025-12-16 17:57:21 +08:00
0786d23336 Merge pull request 'API notif dan penambahan package firebase-admin' (#29) from mobile-notification/15-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/29
2025-12-15 17:52:03 +08:00
cb3511f973 Merge pull request 'Fix QC ( Ayu )' (#28) from qc-mobile/10-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/28
2025-12-10 17:38:42 +08:00
b4921c4e82 Merge pull request 'Fix API untuk QC: Ayu' (#27) from qc-mobile/9-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/27
2025-12-09 17:40:20 +08:00
a9325054eb Merge pull request 'Fix Apple Reject' (#26) from qc-mobile/8-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/26
2025-12-08 15:33:58 +08:00
819812149f Merge pull request 'Fix QC Admin ( Inno )' (#25) from qc-mobile/5-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/25
2025-12-05 17:15:53 +08:00
75ba2b29ae Merge pull request 'Fix QC Inno:' (#24) from mobile-reject/4-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/24
2025-12-04 17:45:04 +08:00
54a4d15bdd Merge pull request 'Fix WA Server' (#23) from mobile-reject/3-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/23
2025-12-03 16:28:09 +08:00
1321f33da9 Merge pull request 'Fix Apple Rejected' (#22) from mobile-reject/3-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/22
2025-12-03 15:02:40 +08:00
fad0c33b9a Merge pull request 'Alur autentikasi dirubah' (#21) from mobile-reject/2-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/21
2025-12-02 14:41:44 +08:00
565bab4998 Merge pull request 'QC Mobile: Pak jun dan Inno' (#20) from qc/1-dec-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/20
2025-12-01 17:44:48 +08:00
7530a38c4d Merge pull request 'Fix version' (#19) from apple-reject/28-nov-25 into staging
Reviewed-on: http://wibugit.wibudev.com/wibu/hipmi/pulls/19
2025-11-28 11:47:44 +08:00
18 changed files with 783 additions and 174 deletions

View File

@@ -2,6 +2,12 @@
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)

View File

@@ -1,6 +1,6 @@
{
"name": "hipmi",
"version": "1.5.30",
"version": "1.5.33",
"private": true,
"prisma": {
"seed": "bun prisma/seed.ts"

View File

@@ -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;

View File

@@ -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;

View File

@@ -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 {
@@ -587,7 +591,7 @@ model Donasi_Invoice {
imageId String?
MasterBank MasterBank? @relation(fields: [masterBankId], references: [id])
masterBankId String?
masterBankId String?
}
model Donasi_Kabar {
@@ -974,28 +978,36 @@ model NomorAdmin {
}
model Notifikasi {
id String @id @default(cuid())
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
appId String
kategoriApp String
pesan String
id String @id @default(cuid())
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
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?
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

View File

@@ -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 }

View File

@@ -1,6 +1,12 @@
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import _ from "lodash";
import {
sendNotificationMobileToManyUser,
sendNotificationMobileToOneUser,
} from "@/lib/mobile/notification/send-notification";
import { routeUserMobile } from "@/lib/mobile/route-page-mobile";
import { NotificationMobileBodyType } from "../../../../../../../types/type-mobile-notification";
export { GET, PUT };
@@ -54,6 +60,9 @@ 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);
@@ -83,7 +92,7 @@ async function PUT(request: Request, { params }: { params: { id: string } }) {
},
data: {
masterStatusId: checkStatus.id,
catatan: data,
catatan: catatan,
},
select: {
id: true,
@@ -97,6 +106,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 +139,35 @@ 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" }),
},
});
const adminUsers = await prisma.user.findMany({
where: { masterUserRoleId: "1", NOT: { id: updt.authorId as any } },
select: { id: true },
});
await sendNotificationMobileToManyUser({
recipientIds: adminUsers.map((user) => user.id),
senderId: data.authorId,
payload: {
title: "Ada lowongan kerja baru",
body: `${updt.title}` as NotificationMobileBodyType,
type: "announcement",
deepLink: routeUserMobile.jobDetailPublised({ id: id }),
kategoriApp: "JOB",
},
});
fixData = updt;
}

View File

@@ -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({

View File

@@ -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,
},
});

View File

@@ -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;

View File

@@ -13,6 +13,7 @@ async function GET(request: Request, { params }: { params: { id: string } }) {
include: {
Author: {
select: {
id: true,
username: true,
nomor: true,
Profile: {

View File

@@ -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", NOT: { id: data.authorId } },
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,
@@ -54,10 +75,10 @@ async function GET(request: Request) {
MasterStatus: {
name: "Publish",
},
// title: {
// contains: search || "",
// mode: "insensitive",
// },
// title: {
// contains: search || "",
// mode: "insensitive",
// },
},
orderBy: {
createdAt: "desc",
@@ -90,46 +111,46 @@ async function GET(request: Request) {
fixData = data;
} else if (category === "beranda") {
const data = await prisma.job.findMany({
where: {
isActive: true,
isArsip: false,
MasterStatus: {
name: "Publish",
},
title: {
contains: search || "",
mode: "insensitive",
},
},
orderBy: {
createdAt: "desc",
},
select: {
id: true,
title: true,
deskripsi: true,
authorId: true,
MasterStatus: {
select: {
name: true,
},
},
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
imageId: true,
},
},
},
},
},
});
const data = await prisma.job.findMany({
where: {
isActive: true,
isArsip: false,
MasterStatus: {
name: "Publish",
},
title: {
contains: search || "",
mode: "insensitive",
},
},
orderBy: {
createdAt: "desc",
},
select: {
id: true,
title: true,
deskripsi: true,
authorId: true,
MasterStatus: {
select: {
name: true,
},
},
Author: {
select: {
id: true,
username: true,
Profile: {
select: {
id: true,
name: true,
imageId: true,
},
},
},
},
},
});
fixData = data;
}

View File

@@ -1,5 +1,8 @@
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,
@@ -9,32 +12,21 @@ export async function GET(
const { searchParams } = new URL(request.url);
const category = searchParams.get("category");
let fixData;
const fixCategory = _.upperCase(category || "");
try {
let fixData;
const data = await prisma.notifikasi.findMany({
orderBy: {
createdAt: "desc",
},
where: {
recipientId: id,
kategoriApp: fixCategory,
},
});
if (category === "count-as-unread") {
const data = await prisma.notifikasi.findMany({
where: {
userId: id,
isRead: false,
},
});
fixData = data.length;
} else if (category === "all") {
const data = await prisma.notifikasi.findMany({
where: {
userId: id,
},
});
fixData = data;
} else {
return NextResponse.json({
success: false,
message: "Invalid category",
});
}
fixData = data;
return NextResponse.json({
success: true,
@@ -47,3 +39,159 @@ export async function GET(
);
}
}
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 }
);
}
}

View File

@@ -6,22 +6,21 @@ export async function GET(
{ params }: { params: { id: string } }
) {
const { id } = params;
console.log("Id >>", id);
console.log("User ID:", id);
try {
const data = await prisma.notifikasi.findMany({
const data = await prisma.notifikasi.count({
where: {
userId: id,
recipientId: id,
isRead: false,
},
});
console.log("Data >>", data);
console.log("List Notification >>", data);
return NextResponse.json({
success: true,
data: data.length,
data: data,
});
} catch (error) {
return NextResponse.json({

View File

@@ -1,29 +1,37 @@
// app/api/test/notifications/route.ts
import { prisma } from "@/lib";
import { adminMessaging } from "@/lib/firebase-admin";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib";
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 {
fcmToken,
title,
body: notificationBody,
userLoginId,
type,
kategoriApp,
} = data;
appId,
status,
deepLink,
} = data as NotificationProp;
console.log("Data Notifikasi >>", data);
if (!fcmToken || !title) {
return NextResponse.json(
{ error: "Missing fcmToken or title" },
{ status: 400 }
);
}
console.log("Notification Send >>", data);
// Cari user yang login
const findUserLogin = await prisma.user.findUnique({
where: {
id: userLoginId,
@@ -34,79 +42,112 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const deviceToken = await prisma.tokenUserDevice.findMany({
// Cari token fcm user yang login
const checkFcmToken = await prisma.tokenUserDevice.findFirst({
where: {
isActive: true,
NOT: {
userId: findUserLogin.id,
},
},
include: {
user: true,
userId: findUserLogin.id,
},
});
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);
if (!checkFcmToken) {
return NextResponse.json(
{ error: "FCM Token not found" },
{ status: 404 }
);
}
if (i.user?.masterUserRoleId === "1") {
const createNotification = await prisma.notifikasi.create({
data: {
title,
type,
createdAt: message.data.sentAt,
appId: "test-id-app",
userRoleId: findUserLogin.masterUserRoleId,
kategoriApp: "PERCOBAAN",
pesan: notificationBody || "",
userId: i.userId,
// 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,
},
});
if (createNotification) {
const response = await adminMessaging.send(message);
console.log("✅ FCM sent:", response);
} else {
return NextResponse.json({
success: false,
message: "Failed to create notification",
});
}
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 {
const createNotification = await prisma.notifikasi.create({
data: {
title,
type,
createdAt: message.data.sentAt,
appId: "test-id-app",
userRoleId: findUserLogin.masterUserRoleId,
kategoriApp: "PERCOBAAN",
pesan: notificationBody || "",
adminId: i.userId,
},
return NextResponse.json({
success: false,
message: "Failed to create notification",
});
if (createNotification) {
const response = await adminMessaging.send(message);
console.log("✅ FCM sent:", response);
} else {
return NextResponse.json({
success: false,
message: "Failed to create notification",
});
}
}
}
@@ -122,3 +163,48 @@ export async function POST(request: NextRequest) {
);
}
}
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;
}

View 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,
})
)
);
}

View File

@@ -0,0 +1,20 @@
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
jobDetailPublised: ({ id }: { id: string }) => `/job/${id}`,
jobByStatus: ({ status }: { status?: StatusApp }) =>
`/job/(tabs)/status?status=${status}`,
};

View File

@@ -0,0 +1,38 @@
// 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"
// to ALL user
| "Ada lowongan kerja baru"
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";