Simpan notifikasi ke database

Add:
- prisma/migrations/20251218071503_add_type_on_db_notifikasi/
- src/app/api/mobile/notification/

Fix:
- modified:   prisma/schema.prisma
- modified:   src/app/api/mobile/auth/device-tokens/route.ts
- deleted:    src/app/api/mobile/notifications/route.ts
- modified:   x.sh

###No Issue
This commit is contained in:
2025-12-19 16:38:33 +08:00
parent 6507bdcd35
commit f05571caa4
8 changed files with 216 additions and 59 deletions

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Notifikasi" ADD COLUMN "type" TEXT;

View File

@@ -987,6 +987,7 @@ model Notifikasi {
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

View File

@@ -24,6 +24,9 @@ async function POST(request: NextRequest) {
},
});
console.log("✅ EX", existing);
let deviceToken;
if (existing) {

View File

@@ -0,0 +1,49 @@
import { prisma } from "@/lib";
import { NextRequest, NextResponse } from "next/server";
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
const { id } = params;
const { searchParams } = new URL(request.url);
const category = searchParams.get("category");
try {
let fixData;
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",
});
}
return NextResponse.json({
success: true,
data: fixData,
});
} catch (error) {
return NextResponse.json(
{ error: (error as Error).message },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,32 @@
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("Id >>", id);
try {
const data = await prisma.notifikasi.findMany({
where: {
userId: id,
isRead: false,
},
});
console.log("Data >>", data);
return NextResponse.json({
success: true,
data: data.length,
});
} catch (error) {
return NextResponse.json({
success: false,
message: "Failed to get unread count",
});
}
}

View File

@@ -0,0 +1,124 @@
// app/api/test/notifications/route.ts
import { adminMessaging } from "@/lib/firebase-admin";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib";
export async function POST(request: NextRequest) {
try {
const { data } = await request.json();
const {
fcmToken,
title,
body: notificationBody,
userLoginId,
type,
kategoriApp,
} = data;
console.log("Data Notifikasi >>", data);
if (!fcmToken || !title) {
return NextResponse.json(
{ error: "Missing fcmToken or title" },
{ status: 400 }
);
}
const findUserLogin = await prisma.user.findUnique({
where: {
id: userLoginId,
},
});
if (!findUserLogin) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const deviceToken = await prisma.tokenUserDevice.findMany({
where: {
isActive: true,
NOT: {
userId: findUserLogin.id,
},
},
include: {
user: true,
},
});
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 (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,
},
});
if (createNotification) {
const response = await adminMessaging.send(message);
console.log("✅ FCM sent:", response);
} else {
return NextResponse.json({
success: false,
message: "Failed to create notification",
});
}
} 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,
},
});
if (createNotification) {
const response = await adminMessaging.send(message);
console.log("✅ FCM sent:", response);
} 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 }
);
}
}

View File

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

7
x.sh
View File

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