File size: 2,194 Bytes
632173a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
 * Quick script to send a test push notification directly via Firebase Admin SDK.
 *
 * Usage:
 *   1. Set FIREBASE_SERVICE_ACCOUNT_PATH or FIREBASE_SERVICE_ACCOUNT_JSON in your .env
 *      (or export GOOGLE_APPLICATION_CREDENTIALS=/path/to/serviceAccount.json)
 *   2. Run:
 *        node backend/scripts/send_test_notification.js <FCM_TOKEN> "Title" "Body"
 *
 * Example:
 *   node backend/scripts/send_test_notification.js "eA1b2c3..." "Hello" "Push is working!"
 */

const path = require('path');
const admin = require('firebase-admin');
const dotenv = require('dotenv');

dotenv.config({ path: path.resolve(__dirname, '..', '.env') });

const token = process.argv[2];
const title = process.argv[3] || 'Care People';
const body = process.argv[4] || 'Push notification is working!';

if (!token) {
  console.error('Usage: node send_test_notification.js <FCM_TOKEN> [title] [body]');
  process.exit(1);
}

function initFirebase() {
  if (process.env.FIREBASE_SERVICE_ACCOUNT_JSON) {
    const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_JSON);
    admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });
    return;
  }

  if (process.env.FIREBASE_SERVICE_ACCOUNT_PATH) {
    const fullPath = path.resolve(__dirname, '..', process.env.FIREBASE_SERVICE_ACCOUNT_PATH);
    const serviceAccount = require(fullPath);
    admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });
    return;
  }

  // Falls back to GOOGLE_APPLICATION_CREDENTIALS env var
  admin.initializeApp({ credential: admin.credential.applicationDefault() });
}

async function sendNotification() {
  initFirebase();

  const message = {
    token,
    notification: { title, body },
    android: {
      priority: 'high',
      notification: {
        channelId: 'care_people_general',
        clickAction: 'FLUTTER_NOTIFICATION_CLICK',
      },
    },
  };

  try {
    const response = await admin.messaging().send(message);
    console.log('✅ Notification sent successfully!');
    console.log('Message ID:', response);
  } catch (err) {
    console.error('❌ Failed to send notification:', err.message);
    process.exit(1);
  }
}

sendNotification();