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 { 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 { 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 { 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) }