Filter console dan clean code #32

Merged
bagasbanuna merged 1 commits from notification/17-dec-25 into staging 2025-12-18 11:22:23 +08:00
9 changed files with 110 additions and 116 deletions

View File

@@ -21,12 +21,6 @@ export default function Application() {
const { token, user, userData } = useAuth();
const [data, setData] = useState<any>();
const [refreshing, setRefreshing] = useState(false);
// console.log("[User] >>", JSON.stringify(user?.id, null, 2));
// const { notifications } = useNotificationStore();
// const unreadCount = notifications.filter((n) => !n.read).length;
// console.log("UNREAD", notifications)
// ‼️ Untuk cek apakah: 1. user ada, 2. user punya profile, 3. accept temrs of forum nya ada atau tidak
useFocusEffect(
useCallback(() => {
@@ -89,46 +83,6 @@ export default function Application() {
/>
),
headerRight: () => <HeaderBell />,
// headerRight: () => {
// return (
// <View style={{ position: "relative" }}>
// <Ionicons
// name="notifications"
// size={20}
// color={MainColor.yellow}
// onPress={() => {
// router.push("/notifications");
// }}
// />
// {unreadCount > 0 && (
// <View
// style={{
// position: "absolute",
// top: -4,
// right: -4,
// backgroundColor: "red",
// borderRadius: 8,
// minWidth: 16,
// height: 16,
// justifyContent: "center",
// alignItems: "center",
// paddingHorizontal: 2,
// }}
// >
// <Text
// style={{
// color: "white",
// fontSize: 10,
// fontWeight: "bold",
// }}
// >
// {unreadCount > 9 ? "9+" : unreadCount}
// </Text>
// </View>
// )}
// </View>
// );
// },
}}
/>
<ViewWrapper

View File

@@ -4,11 +4,29 @@ import {
StackCustom,
TextInputCustom,
} from "@/components";
import { apiNotificationsSend } from "@/service/api-notifications";
import { useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { apiGetAllTokenDevice } from "@/service/api-device-token";
import {
apiNotificationsSend,
} from "@/service/api-notifications";
import { useEffect, useState } from "react";
export default function TestNotification() {
const { user } = useAuth();
const [data, setData] = useState("");
useEffect(() => {
// fecthData();
}, []);
const fecthData = async () => {
const response = await apiGetAllTokenDevice();
console.log(
"[RES GET ALL TOKEN DEVICE]",
JSON.stringify(response.data, null, 2)
);
};
const handleSubmit = async () => {
console.log("[Data Dikirim]", data);
const response = await apiNotificationsSend({
@@ -17,6 +35,7 @@ export default function TestNotification() {
"cVmHm-3P4E-1vjt6AA9kSF:APA91bHTkHjGTLxrFsb6Le6bZmzboZhwMGYXU4p0FP9yEeXixLDXNKS4F5vLuZV3sRgSnjjQsPpLOgstVLHJB8VJTObctKLdN-CxAp4dnP7Jbc_mH53jWvs",
title: "Test dari Backend (App Router)!",
body: data,
userLoginId: user?.id || "",
},
});

View File

@@ -1,15 +1,9 @@
import NotificationInitializer from "@/components/_ShareComponent/NotificationInitializer";
import { AuthProvider } from "@/context/AuthContext";
import { useForegroundNotifications } from "@/hooks/use-foreground-notifications";
import {
NotificationProvider,
useNotificationStore,
NotificationProvider
} from "@/hooks/use-notification-store";
import AppRoot from "@/screens/RootLayout/AppRoot";
import messaging, {
FirebaseMessagingTypes,
} from "@react-native-firebase/messaging";
import { useEffect } from "react";
import "react-native-gesture-handler";
import { SafeAreaProvider } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";

View File

@@ -1,6 +1,5 @@
// src/components/NotificationInitializer.tsx
import { useEffect } from "react";
import messaging from "@react-native-firebase/messaging";
import { useForegroundNotifications } from "@/hooks/use-foreground-notifications";
import { useNotificationStore } from "@/hooks/use-notification-store";
import type { FirebaseMessagingTypes } from "@react-native-firebase/messaging";
@@ -8,12 +7,12 @@ import { useAuth } from "@/hooks/use-auth";
import { Platform } from "react-native";
import * as Device from "expo-device";
import * as Application from "expo-application";
import { apiDeviceRegisterToken } from "@/service/api-notifications";
import { apiDeviceRegisterToken } from "@/service/api-device-token";
import messaging from "@react-native-firebase/messaging";
export default function NotificationInitializer() {
// Setup handler notifikasi
const { user } = useAuth(); // dari AuthContext
const { user, logout } = useAuth(); // dari AuthContext
const { addNotification } = useNotificationStore();
// Ambil token FCM (opsional, hanya untuk log)
@@ -23,10 +22,6 @@ export default function NotificationInitializer() {
return;
}
// if (user?.id) {
// syncDeviceToken({ userId: user.id });
// }
const registerDeviceToken = async () => {
try {
// 1. Minta izin & ambil FCM token
@@ -35,6 +30,10 @@ export default function NotificationInitializer() {
if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) {
const token = await messaging().getToken();
console.log("✅ FCM Token:", token);
if (!token) {
logout();
return;
}
} else {
console.warn("Izin notifikasi ditolak");
return;
@@ -47,30 +46,24 @@ export default function NotificationInitializer() {
// 2. Ambil info device
const platform = Platform.OS; // "ios" | "android"
// ? await Device.getUdid()
// : "unknown";
const model = Device.modelName || "unknown";
const appVersion =
(Application.nativeApplicationVersion || "unknown") +
"-" +
(Application.nativeBuildVersion || "unknown");
const deviceId =
Device.osInternalBuildId || Device.modelName + "-" + Date.now();
const appVersion = (Application.nativeApplicationVersion || "unknown") + "-" + (Application.nativeBuildVersion || "unknown");
const deviceId = Device.osInternalBuildId || Device.modelName + "-" + Date.now();
console.log(
"📱 Device info:",
JSON.stringify(
{
fcmToken,
platform,
deviceId,
model,
appVersion,
},
null,
2
)
);
// console.log(
// "📱 Device info:",
// JSON.stringify(
// {
// fcmToken,
// platform,
// deviceId,
// model,
// appVersion,
// },
// null,
// 2
// )
// );
// 3. Kirim ke backend
await apiDeviceRegisterToken({

View File

@@ -4,6 +4,7 @@ import {
apiRegister,
apiValidationCode,
} from "@/service/api-config";
import { apiDeviceTokenDeleted } from "@/service/api-device-token";
import { IUser } from "@/types/User";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { router } from "expo-router";
@@ -282,7 +283,7 @@ export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
setUser(null);
await AsyncStorage.removeItem("authToken");
await AsyncStorage.removeItem("userData");
setIsLoading(false);
await apiDeviceTokenDeleted({userId: user?.id as any})
Toast.show({
type: "success",

View File

@@ -1,5 +1,7 @@
import { useEffect } from "react";
import messaging, {
import {
getMessaging,
onMessage,
FirebaseMessagingTypes,
} from "@react-native-firebase/messaging";
@@ -10,7 +12,9 @@ export function useForegroundNotifications(
onMessageReceived: (message: RemoteMessage) => void
) {
useEffect(() => {
const unsubscribe = messaging().onMessage((remoteMessage) => {
const messaging = getMessaging();
const unsubscribe = onMessage(messaging, (remoteMessage) => {
console.log(
"🔔 Notifikasi diterima saat app aktif:",
JSON.stringify(remoteMessage, null, 2)
@@ -20,4 +24,4 @@ export function useForegroundNotifications(
return unsubscribe;
}, [onMessageReceived]);
}
}

View File

@@ -8,7 +8,7 @@ import { MainColor } from "@/constants/color-palet";
export default function HeaderBell() {
const { notifications } = useNotificationStore();
const unreadCount = notifications.filter((n) => !n.read).length;
console.log("NOTIF:", JSON.stringify(notifications, null, 2));
// console.log("NOTIF:", JSON.stringify(notifications, null, 2));
return (
<View style={{ position: "relative" }}>

View File

@@ -0,0 +1,54 @@
import { apiConfig } from "./api-config";
type DeviceTokenData = {
fcmToken: string;
platform: string;
deviceId: string;
model: string;
appVersion: string;
userId: string;
};
export async function apiDeviceRegisterToken({
data,
}: {
data: DeviceTokenData;
}) {
try {
const response = await apiConfig.post(`/mobile/auth/device-tokens`, {
data: data,
});
console.log(
"Device token registered:",
JSON.stringify(response.data, null, 2)
);
return response.data;
} catch (error) {
console.error("Failed to register device token:", error);
throw error;
}
}
export async function apiDeviceTokenDeleted({ userId }: { userId: string }) {
try {
const response = await apiConfig.delete(
`/mobile/auth/device-tokens/${userId}`
);
console.log("Device token deleted:", response.data);
return response.data;
} catch (error) {
console.error("Failed to delete device token:", error);
throw error;
}
}
export async function apiGetAllTokenDevice() {
try {
const response = await apiConfig.get(`/mobile/auth/device-tokens`);
console.log("Device token deleted:", response.data);
return response.data;
} catch (error) {
console.error("Failed to delete device token:", error);
throw error;
}
}

View File

@@ -4,6 +4,7 @@ type NotificationProp = {
fcmToken: string;
title: string;
body: Object;
userLoginId?: string;
};
export async function apiNotificationsSend({
@@ -23,29 +24,3 @@ export async function apiNotificationsSend({
throw error;
}
}
type DeviceTokenData = {
fcmToken: string;
platform: string;
deviceId: string;
model: string;
appVersion: string;
userId: string;
};
export async function apiDeviceRegisterToken({
data,
}: {
data: DeviceTokenData;
}) {
try {
const response = await apiConfig.post(`/mobile/auth/device-tokens`, {
data: data,
});
console.log("Device token registered:", response.data);
return response.data;
} catch (error) {
console.error("Failed to register device token:", error);
throw error;
}
}