Phase 3 scaffold: chat engine (WebSocket, FCM, pricing, timer, extension, history)
- Backend: WebSocket plugin, chat/pricing/timer/extension/closure/notification services - Client app: ChatBloc, pricing dialog, chat screen with message status, extension/goodbye flow, history - Mitra app: MitraChatBloc, ExtensionBloc, chat screen, extension accept/reject, history - Control center: free trial, extension timeout, early end config toggles - DB migration: chat_messages, session_closures, session_extensions, customer_transactions tables Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
52
backend/src/services/notification.service.js
Normal file
52
backend/src/services/notification.service.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import admin from 'firebase-admin'
|
||||
import { getDb } from '../db/client.js'
|
||||
|
||||
const sql = getDb()
|
||||
|
||||
export const registerDeviceToken = async (userType, userId, fcmToken) => {
|
||||
const table = userType === 'customer' ? 'customers' : 'mitras'
|
||||
await sql`
|
||||
UPDATE ${sql(table)}
|
||||
SET fcm_token = ${fcmToken}
|
||||
WHERE id = ${userId}
|
||||
`
|
||||
}
|
||||
|
||||
export const sendPushNotification = async (recipientType, recipientId, { title, body, data = {} }) => {
|
||||
const table = recipientType === 'customer' ? 'customers' : 'mitras'
|
||||
const [user] = await sql`
|
||||
SELECT fcm_token FROM ${sql(table)} WHERE id = ${recipientId}
|
||||
`
|
||||
|
||||
if (!user?.fcm_token) return false
|
||||
|
||||
try {
|
||||
await admin.messaging().send({
|
||||
token: user.fcm_token,
|
||||
notification: { title, body },
|
||||
data: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(data).map(([k, v]) => [k, String(v)])
|
||||
),
|
||||
click_action: 'FLUTTER_NOTIFICATION_CLICK',
|
||||
},
|
||||
android: {
|
||||
priority: 'high',
|
||||
notification: { channelId: 'chat_messages' },
|
||||
},
|
||||
apns: {
|
||||
payload: {
|
||||
aps: { sound: 'default', badge: 1 },
|
||||
},
|
||||
},
|
||||
})
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error(`[FCM] Failed to send to ${recipientType}:${recipientId}:`, err.message)
|
||||
// Clear invalid token
|
||||
if (err.code === 'messaging/registration-token-not-registered') {
|
||||
await sql`UPDATE ${sql(table)} SET fcm_token = NULL WHERE id = ${recipientId}`
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user