freshyo/apps/backend/src/lib/admin-notif.ts
2026-10-29 23:04:42 +05:30

97 lines
2.8 KiB
TypeScript

import {
getAllStaffNotifTokens,
getStaffNotifTokensForRegion,
} from '@/src/dbService'
import { queueDataPusher } from '@/src/lib/queue-data-pusher'
// Number of push tokens batched into a single queue message.
const TOKENS_PER_QUEUE_MESSAGE = 5
interface AdminNotificationPayload {
title: string
body: string
imageUrl?: string | null
orderId?: number | null
complaintId?: number | null
}
/**
* Queues the same notification for a list of device tokens in batches.
* Returns the number of tokens queued for; a failed batch is logged and the
* remaining batches still go out.
*/
async function queueForTokens(
tokens: string[],
payload: AdminNotificationPayload
): Promise<number> {
let queuedCount = 0
for (let i = 0; i < tokens.length; i += TOKENS_PER_QUEUE_MESSAGE) {
const tokenChunk = tokens.slice(i, i + TOKENS_PER_QUEUE_MESSAGE)
try {
await queueDataPusher.pushNotifQueue({
name: 'send-admin-notification',
jobData: {
tokens: tokenChunk,
title: payload.title,
body: payload.body,
imageUrl: payload.imageUrl ?? null,
orderId: payload.orderId ?? null,
complaintId: payload.complaintId ?? null,
},
options: {
attempts: 3,
backoff: {
type: 'exponential',
delay: 2000,
},
},
})
queuedCount += tokenChunk.length
} catch (error) {
console.error(`Failed to queue admin notification for tokens:`, error)
}
}
return queuedCount
}
/**
* Queues a push notification to every admin/staff device.
*
* Manual broadcasts only (the "send notification" screens). Order and complaint
* events must use `notifyRegionAdmins` so a region never sees another region's
* work.
*/
export async function notifyAllAdmins(
payload: AdminNotificationPayload
): Promise<number> {
const tokens = (await getAllStaffNotifTokens()).map((t) => t.token)
return queueForTokens(tokens, payload)
}
/**
* Queues a push notification to the staff devices of one region.
*
* Region scoping is not optional: admin reads are region-scoped
* (`eq(orders.regionId, staff.regionId)`), so a device in another region could
* not act on the order or complaint it was shown.
*
* `orderId` / `complaintId`, when set, are delivered in the push `data` so the
* app can deep-link. Returns the number of tokens queued for (0 when the event
* has no region or the region has no devices).
*/
export async function notifyRegionAdmins(
regionId: number | null | undefined,
payload: AdminNotificationPayload
): Promise<number> {
if (regionId === null || regionId === undefined) {
console.warn('Skipping admin notification: the event has no region')
return 0
}
const tokens = (await getStaffNotifTokensForRegion(regionId)).map(
(t) => t.token
)
return queueForTokens(tokens, payload)
}