From a01a9bd93f21990460c4a85cbf5ecd706aa9df98 Mon Sep 17 00:00:00 2001 From: bagasbanuna Date: Wed, 17 Dec 2025 17:46:28 +0800 Subject: [PATCH] Filter console dan clean code Add: - service/api-device-token.ts Fix: - app/(application)/(user)/home.tsx - app/(application)/(user)/test-notifications.tsx - app/_layout.tsx - components/_ShareComponent/NotificationInitializer.tsx - context/AuthContext.tsx - hooks/use-foreground-notifications.ts - screens/Home/HeaderBell.tsx - service/api-notifications.ts ### No Issue --- app/(application)/(user)/home.tsx | 46 ---------------- .../(user)/test-notifications.tsx | 23 +++++++- app/_layout.tsx | 8 +-- .../NotificationInitializer.tsx | 53 ++++++++---------- context/AuthContext.tsx | 3 +- hooks/use-foreground-notifications.ts | 10 ++-- screens/Home/HeaderBell.tsx | 2 +- service/api-device-token.ts | 54 +++++++++++++++++++ service/api-notifications.ts | 27 +--------- 9 files changed, 110 insertions(+), 116 deletions(-) create mode 100644 service/api-device-token.ts diff --git a/app/(application)/(user)/home.tsx b/app/(application)/(user)/home.tsx index 3d2b5f3..dfc8d7e 100644 --- a/app/(application)/(user)/home.tsx +++ b/app/(application)/(user)/home.tsx @@ -21,12 +21,6 @@ export default function Application() { const { token, user, userData } = useAuth(); const [data, setData] = useState(); 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: () => , - // headerRight: () => { - // return ( - // - // { - // router.push("/notifications"); - // }} - // /> - // {unreadCount > 0 && ( - // - // - // {unreadCount > 9 ? "9+" : unreadCount} - // - // - // )} - // - // ); - // }, }} /> { + // 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 || "", }, }); diff --git a/app/_layout.tsx b/app/_layout.tsx index c568ec3..a62a04b 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -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"; diff --git a/components/_ShareComponent/NotificationInitializer.tsx b/components/_ShareComponent/NotificationInitializer.tsx index 5d52875..0e9c222 100644 --- a/components/_ShareComponent/NotificationInitializer.tsx +++ b/components/_ShareComponent/NotificationInitializer.tsx @@ -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({ diff --git a/context/AuthContext.tsx b/context/AuthContext.tsx index 53da0d5..fa7eee1 100644 --- a/context/AuthContext.tsx +++ b/context/AuthContext.tsx @@ -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", diff --git a/hooks/use-foreground-notifications.ts b/hooks/use-foreground-notifications.ts index 9d88c1d..f35e162 100644 --- a/hooks/use-foreground-notifications.ts +++ b/hooks/use-foreground-notifications.ts @@ -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]); -} +} \ No newline at end of file diff --git a/screens/Home/HeaderBell.tsx b/screens/Home/HeaderBell.tsx index a52a20e..edc8b80 100644 --- a/screens/Home/HeaderBell.tsx +++ b/screens/Home/HeaderBell.tsx @@ -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 ( diff --git a/service/api-device-token.ts b/service/api-device-token.ts new file mode 100644 index 0000000..95a2c63 --- /dev/null +++ b/service/api-device-token.ts @@ -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; + } +} diff --git a/service/api-notifications.ts b/service/api-notifications.ts index a776a71..bff72a3 100644 --- a/service/api-notifications.ts +++ b/service/api-notifications.ts @@ -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; - } -}