@burdenoff/microfe-notification 2026.518.2 → 2026.521.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AdminNotificationRoutes.d.ts.map +1 -1
- package/dist/AdminNotificationRoutes.js +50 -46
- package/dist/AdminNotificationRoutes.js.map +1 -1
- package/dist/UserNotificationRoutes.d.ts.map +1 -1
- package/dist/UserNotificationRoutes.js +28 -24
- package/dist/UserNotificationRoutes.js.map +1 -1
- package/dist/components/FeatureDisabledPage.d.ts +7 -0
- package/dist/components/FeatureDisabledPage.d.ts.map +1 -0
- package/dist/components/FeatureDisabledPage.js +32 -0
- package/dist/components/FeatureDisabledPage.js.map +1 -0
- package/dist/components/NotificationBell.d.ts.map +1 -1
- package/dist/components/NotificationBell.js +43 -22
- package/dist/components/NotificationBell.js.map +1 -1
- package/dist/components/NotificationCard.d.ts +2 -1
- package/dist/components/NotificationCard.d.ts.map +1 -1
- package/dist/components/NotificationCard.js +64 -63
- package/dist/components/NotificationCard.js.map +1 -1
- package/dist/components/NotificationPanel.d.ts.map +1 -1
- package/dist/components/NotificationPanel.js +2 -1
- package/dist/components/NotificationPanel.js.map +1 -1
- package/dist/graphql/global-client.js +1 -1
- package/dist/graphql/global-client.js.map +1 -1
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +1 -0
- package/dist/hooks/useNotificationAdmin.d.ts.map +1 -1
- package/dist/hooks/useNotificationAdmin.js +67 -64
- package/dist/hooks/useNotificationAdmin.js.map +1 -1
- package/dist/hooks/useNotificationAnalytics.d.ts +67 -0
- package/dist/hooks/useNotificationAnalytics.d.ts.map +1 -0
- package/dist/hooks/useNotificationAnalytics.js +64 -0
- package/dist/hooks/useNotificationAnalytics.js.map +1 -0
- package/dist/hooks/useNotificationPreferences.js +1 -1
- package/dist/hooks/useNotificationPreferences.js.map +1 -1
- package/dist/hooks/useNotificationTemplates.js +3 -3
- package/dist/hooks/useNotificationTemplates.js.map +1 -1
- package/dist/hooks/useNotificationTopics.js +1 -1
- package/dist/hooks/useNotificationTopics.js.map +1 -1
- package/dist/hooks/useNotifications.d.ts.map +1 -1
- package/dist/hooks/useNotifications.js +47 -40
- package/dist/hooks/useNotifications.js.map +1 -1
- package/dist/pages/CreateNotificationPage.d.ts.map +1 -1
- package/dist/pages/CreateNotificationPage.js +407 -391
- package/dist/pages/CreateNotificationPage.js.map +1 -1
- package/dist/pages/NotificationCenterPage.d.ts.map +1 -1
- package/dist/pages/NotificationCenterPage.js +80 -81
- package/dist/pages/NotificationCenterPage.js.map +1 -1
- package/dist/pages/NotificationHistoryAdminPage.d.ts.map +1 -1
- package/dist/pages/NotificationHistoryAdminPage.js +2 -1
- package/dist/pages/NotificationHistoryAdminPage.js.map +1 -1
- package/dist/pages/NotificationHistoryPage.d.ts.map +1 -1
- package/dist/pages/NotificationHistoryPage.js +2 -1
- package/dist/pages/NotificationHistoryPage.js.map +1 -1
- package/dist/pages/NotificationPreferencesPage.d.ts.map +1 -1
- package/dist/pages/NotificationPreferencesPage.js +140 -95
- package/dist/pages/NotificationPreferencesPage.js.map +1 -1
- package/dist/pages/TemplateEditorPage.d.ts.map +1 -1
- package/dist/pages/TemplateEditorPage.js +326 -313
- package/dist/pages/TemplateEditorPage.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationAdmin.js","names":[],"sources":["../../src/hooks/useNotificationAdmin.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { Notification, NotificationAdminFilters } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationsQuery,\n GetNotificationQuery,\n GetNotificationEventsQuery,\n GetScheduledNotificationsQuery,\n} from '../generated/global-operations';\n\nconst defaultFilters: NotificationAdminFilters = {\n search: '',\n status: 'all',\n channel: 'all',\n deliveryStatus: 'all',\n type: 'all',\n topicId: '',\n archived: 'all',\n};\n\nfunction mapPriority(priority: string): Notification['priority'] {\n if (priority === 'MEDIUM') return 'NORMAL';\n return (priority as Notification['priority']) || 'NORMAL';\n}\n\nfunction mapStatus(status: string): Notification['status'] {\n if (status === 'CANCELLED') return 'ARCHIVED';\n if (status === 'READ') return 'DELIVERED';\n return (status as Notification['status']) || 'PENDING';\n}\n\nfunction mapNotification(\n notification:\n | GetNotificationsQuery['notifications']['items'][number]\n | NonNullable<GetNotificationQuery['notification']>\n): Notification {\n return {\n id: notification.id,\n title: notification.title,\n body: notification.message,\n type: notification.type as Notification['type'],\n priority: mapPriority(notification.priority),\n status: mapStatus(notification.status),\n channel: notification.channel as Notification['channel'],\n deliveryStatus: notification.deliveryStatus ?? undefined,\n createdAt: notification.createdAt,\n updatedAt: notification.updatedAt,\n readAt: notification.readAt ?? undefined,\n archivedAt: notification.archivedAt ?? undefined,\n clickedAt: notification.clickedAt ?? undefined,\n openedAt: notification.openedAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n sentAt: notification.sentAt ?? undefined,\n actionUrl: notification.redirectUrl ?? undefined,\n actions: (notification.actions || []).map((action) => ({\n id: action.id,\n label: action.label,\n url: action.url,\n style: action.style ?? undefined,\n actionType: action.actionType ?? undefined,\n metadata: action.metadata ?? undefined,\n })),\n media: (notification.media || []).map((item) => ({\n url: item.url,\n label: item.label ?? undefined,\n kind: item.kind ?? undefined,\n contentType: item.contentType ?? undefined,\n thumbnailUrl: item.thumbnailUrl ?? undefined,\n })),\n appName: notification.appName ?? undefined,\n htmlBody: notification.htmlMessage ?? undefined,\n metadata: notification.metadata ?? undefined,\n channels: [\n {\n id: notification.id,\n channel: notification.channel as Notification['channel'],\n status: mapStatus(notification.status),\n sentAt: notification.sentAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n failedAt: notification.failedAt ?? undefined,\n errorCode: notification.errorCode ?? undefined,\n errorMessage: notification.errorMessage ?? undefined,\n },\n ],\n recipientEmail: notification.recipientEmail ?? undefined,\n recipientPhone: notification.recipientPhone ?? undefined,\n scheduledFor: notification.scheduledFor ?? undefined,\n scheduledNotification: notification.scheduledNotification\n ? {\n id: notification.scheduledNotification.id,\n scheduledFor: notification.scheduledNotification.scheduledFor,\n status: notification.scheduledNotification.status,\n timezone: notification.scheduledNotification.timezone ?? undefined,\n retryCount: notification.scheduledNotification.retryCount ?? undefined,\n errorMessage: notification.scheduledNotification.errorMessage ?? undefined,\n }\n : undefined,\n topicId: notification.topicId ?? undefined,\n topic: notification.topic\n ? {\n id: notification.topic.id,\n name: notification.topic.name,\n slug: notification.topic.slug,\n type: notification.topic.type as Notification['type'],\n description: notification.topic.description ?? undefined,\n }\n : undefined,\n imageUrl: notification.media?.[0]?.url ?? undefined,\n };\n}\n\nexport function useNotificationAdmin() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [filters, setFilters] = useState<NotificationAdminFilters>(defaultFilters);\n const [notifications, setNotifications] = useState<Notification[]>([]);\n const [scheduledNotifications, setScheduledNotifications] = useState<\n GetScheduledNotificationsQuery['scheduledNotifications']['items']\n >([]);\n const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);\n const [events, setEvents] = useState<GetNotificationEventsQuery['notificationEvents']>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchNotifications = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: {\n ...(filters.search ? { search: filters.search } : {}),\n ...(filters.status !== 'all' ? { status: filters.status } : {}),\n ...(filters.channel !== 'all' ? { channel: filters.channel } : {}),\n ...(filters.deliveryStatus !== 'all' ? { deliveryStatus: filters.deliveryStatus } : {}),\n ...(filters.type !== 'all' ? { type: filters.type } : {}),\n ...(filters.topicId ? { topicId: filters.topicId } : {}),\n ...(filters.archived !== 'all' ? { archived: filters.archived === 'archived' } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n setNotifications((result.data?.notifications.items || []).map(mapNotification));\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch notifications:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch notifications');\n } finally {\n setIsLoading(false);\n }\n }, [filters, getClient]);\n\n const fetchScheduledNotifications = useCallback(async () => {\n try {\n const client = getClient();\n const result = await client.query<GetScheduledNotificationsQuery>({\n query: NotificationOps.GetScheduledNotificationsDocument,\n variables: { limit: 100, offset: 0 },\n fetchPolicy: 'network-only',\n });\n\n setScheduledNotifications(result.data?.scheduledNotifications.items || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch scheduled notifications:', err);\n }\n }, [getClient]);\n\n const loadNotification = useCallback(\n async (notificationId: string) => {\n setError(null);\n\n try {\n const client = getClient();\n const [notificationResult, eventsResult] = await Promise.all([\n client.query<GetNotificationQuery>({\n query: NotificationOps.GetNotificationDocument,\n variables: { id: notificationId },\n fetchPolicy: 'network-only',\n }),\n client.query<GetNotificationEventsQuery>({\n query: NotificationOps.GetNotificationEventsDocument,\n variables: { notificationId },\n fetchPolicy: 'network-only',\n }),\n ]);\n\n if (notificationResult.data?.notification) {\n setSelectedNotification(mapNotification(notificationResult.data.notification));\n }\n setEvents(eventsResult.data?.notificationEvents || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to load notification detail:', err);\n setError(err instanceof Error ? err.message : 'Failed to load notification detail');\n }\n },\n [getClient]\n );\n\n const archiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.ArchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const unarchiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.UnarchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const cancelScheduledNotification = useCallback(\n async (scheduledNotificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.CancelScheduledNotificationDocument,\n variables: { id: scheduledNotificationId },\n });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient]\n );\n\n const rescheduleNotification = useCallback(\n async (scheduledNotificationId: string, scheduledFor: string, timezone?: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.RescheduleNotificationDocument,\n variables: {\n input: {\n scheduledNotificationId,\n scheduledFor,\n timezone,\n },\n },\n });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient]\n );\n\n useEffect(() => {\n fetchNotifications();\n fetchScheduledNotifications();\n }, [fetchNotifications, fetchScheduledNotifications]);\n\n return {\n filters,\n setFilters,\n notifications,\n scheduledNotifications,\n selectedNotification,\n events,\n isLoading,\n error,\n refetch: fetchNotifications,\n loadNotification,\n archiveNotification,\n unarchiveNotification,\n cancelScheduledNotification,\n rescheduleNotification,\n clearSelection: () => {\n setSelectedNotification(null);\n setEvents([]);\n },\n };\n}\n"],"mappings":";;;;;AAYA,IAAM,IAA2C;CAC/C,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,gBAAgB;CAChB,MAAM;CACN,SAAS;CACT,UAAU;CACX;AAED,SAAS,EAAY,GAA4C;AAE/D,QADI,MAAa,WAAiB,WAC1B,KAAyC;;AAGnD,SAAS,EAAU,GAAwC;AAGzD,QAFI,MAAW,cAAoB,aAC/B,MAAW,SAAe,cACtB,KAAqC;;AAG/C,SAAS,EACP,GAGc;AACd,QAAO;EACL,IAAI,EAAa;EACjB,OAAO,EAAa;EACpB,MAAM,EAAa;EAC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,EAC7B,EAAU,EAAE,CAAC;;EAEhB"}
|
|
1
|
+
{"version":3,"file":"useNotificationAdmin.js","names":[],"sources":["../../src/hooks/useNotificationAdmin.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { Notification, NotificationAdminFilters } from '../types';\nimport { useNotificationAnalytics } from './useNotificationAnalytics';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationsQuery,\n GetNotificationQuery,\n GetNotificationEventsQuery,\n GetScheduledNotificationsQuery,\n} from '../generated/global-operations';\n\nconst defaultFilters: NotificationAdminFilters = {\n search: '',\n status: 'all',\n channel: 'all',\n deliveryStatus: 'all',\n type: 'all',\n topicId: '',\n archived: 'all',\n};\n\nfunction mapPriority(priority: string): Notification['priority'] {\n if (priority === 'MEDIUM') return 'NORMAL';\n return (priority as Notification['priority']) || 'NORMAL';\n}\n\nfunction mapStatus(status: string): Notification['status'] {\n if (status === 'CANCELLED') return 'ARCHIVED';\n if (status === 'READ') return 'DELIVERED';\n return (status as Notification['status']) || 'PENDING';\n}\n\nfunction mapNotification(\n notification:\n | GetNotificationsQuery['notifications']['items'][number]\n | NonNullable<GetNotificationQuery['notification']>\n): Notification {\n return {\n id: notification.id,\n title: notification.title,\n body: notification.message,\n type: notification.type as Notification['type'],\n priority: mapPriority(notification.priority),\n status: mapStatus(notification.status),\n channel: notification.channel as Notification['channel'],\n deliveryStatus: notification.deliveryStatus ?? undefined,\n createdAt: notification.createdAt,\n updatedAt: notification.updatedAt,\n readAt: notification.readAt ?? undefined,\n archivedAt: notification.archivedAt ?? undefined,\n clickedAt: notification.clickedAt ?? undefined,\n openedAt: notification.openedAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n sentAt: notification.sentAt ?? undefined,\n actionUrl: notification.redirectUrl ?? undefined,\n actions: (notification.actions || []).map((action) => ({\n id: action.id,\n label: action.label,\n url: action.url,\n style: action.style ?? undefined,\n actionType: action.actionType ?? undefined,\n metadata: action.metadata ?? undefined,\n })),\n media: (notification.media || []).map((item) => ({\n url: item.url,\n label: item.label ?? undefined,\n kind: item.kind ?? undefined,\n contentType: item.contentType ?? undefined,\n thumbnailUrl: item.thumbnailUrl ?? undefined,\n })),\n appName: notification.appName ?? undefined,\n htmlBody: notification.htmlMessage ?? undefined,\n metadata: notification.metadata ?? undefined,\n channels: [\n {\n id: notification.id,\n channel: notification.channel as Notification['channel'],\n status: mapStatus(notification.status),\n sentAt: notification.sentAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n failedAt: notification.failedAt ?? undefined,\n errorCode: notification.errorCode ?? undefined,\n errorMessage: notification.errorMessage ?? undefined,\n },\n ],\n recipientEmail: notification.recipientEmail ?? undefined,\n recipientPhone: notification.recipientPhone ?? undefined,\n scheduledFor: notification.scheduledFor ?? undefined,\n scheduledNotification: notification.scheduledNotification\n ? {\n id: notification.scheduledNotification.id,\n scheduledFor: notification.scheduledNotification.scheduledFor,\n status: notification.scheduledNotification.status,\n timezone: notification.scheduledNotification.timezone ?? undefined,\n retryCount: notification.scheduledNotification.retryCount ?? undefined,\n errorMessage: notification.scheduledNotification.errorMessage ?? undefined,\n }\n : undefined,\n topicId: notification.topicId ?? undefined,\n topic: notification.topic\n ? {\n id: notification.topic.id,\n name: notification.topic.name,\n slug: notification.topic.slug,\n type: notification.topic.type as Notification['type'],\n description: notification.topic.description ?? undefined,\n }\n : undefined,\n imageUrl: notification.media?.[0]?.url ?? undefined,\n };\n}\n\nexport function useNotificationAdmin() {\n const { authToken, apiGatewayUrl } = useNotification();\n const { trackScheduleUpdated } = useNotificationAnalytics();\n const [filters, setFilters] = useState<NotificationAdminFilters>(defaultFilters);\n const [notifications, setNotifications] = useState<Notification[]>([]);\n const [scheduledNotifications, setScheduledNotifications] = useState<\n GetScheduledNotificationsQuery['scheduledNotifications']['items']\n >([]);\n const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);\n const [events, setEvents] = useState<GetNotificationEventsQuery['notificationEvents']>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchNotifications = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: {\n ...(filters.search ? { search: filters.search } : {}),\n ...(filters.status !== 'all' ? { status: filters.status } : {}),\n ...(filters.channel !== 'all' ? { channel: filters.channel } : {}),\n ...(filters.deliveryStatus !== 'all' ? { deliveryStatus: filters.deliveryStatus } : {}),\n ...(filters.type !== 'all' ? { type: filters.type } : {}),\n ...(filters.topicId ? { topicId: filters.topicId } : {}),\n ...(filters.archived !== 'all' ? { archived: filters.archived === 'archived' } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n setNotifications((result.data?.notifications.items || []).map(mapNotification));\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch notifications:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch notifications');\n } finally {\n setIsLoading(false);\n }\n }, [filters, getClient]);\n\n const fetchScheduledNotifications = useCallback(async () => {\n try {\n const client = getClient();\n const result = await client.query<GetScheduledNotificationsQuery>({\n query: NotificationOps.GetScheduledNotificationsDocument,\n variables: { limit: 100, offset: 0 },\n fetchPolicy: 'network-only',\n });\n\n setScheduledNotifications(result.data?.scheduledNotifications.items || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch scheduled notifications:', err);\n }\n }, [getClient]);\n\n const loadNotification = useCallback(\n async (notificationId: string) => {\n setError(null);\n\n try {\n const client = getClient();\n const [notificationResult, eventsResult] = await Promise.all([\n client.query<GetNotificationQuery>({\n query: NotificationOps.GetNotificationDocument,\n variables: { id: notificationId },\n fetchPolicy: 'network-only',\n }),\n client.query<GetNotificationEventsQuery>({\n query: NotificationOps.GetNotificationEventsDocument,\n variables: { notificationId },\n fetchPolicy: 'network-only',\n }),\n ]);\n\n if (notificationResult.data?.notification) {\n setSelectedNotification(mapNotification(notificationResult.data.notification));\n }\n setEvents(eventsResult.data?.notificationEvents || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to load notification detail:', err);\n setError(err instanceof Error ? err.message : 'Failed to load notification detail');\n }\n },\n [getClient]\n );\n\n const archiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.ArchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const unarchiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.UnarchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const cancelScheduledNotification = useCallback(\n async (scheduledNotificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.CancelScheduledNotificationDocument,\n variables: { id: scheduledNotificationId },\n });\n trackScheduleUpdated({ action: 'cancel' });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient, trackScheduleUpdated]\n );\n\n const rescheduleNotification = useCallback(\n async (scheduledNotificationId: string, scheduledFor: string, timezone?: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.RescheduleNotificationDocument,\n variables: {\n input: {\n scheduledNotificationId,\n scheduledFor,\n timezone,\n },\n },\n });\n trackScheduleUpdated({ action: 'reschedule' });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient, trackScheduleUpdated]\n );\n\n useEffect(() => {\n fetchNotifications();\n fetchScheduledNotifications();\n }, [fetchNotifications, fetchScheduledNotifications]);\n\n return {\n filters,\n setFilters,\n notifications,\n scheduledNotifications,\n selectedNotification,\n events,\n isLoading,\n error,\n refetch: fetchNotifications,\n loadNotification,\n archiveNotification,\n unarchiveNotification,\n cancelScheduledNotification,\n rescheduleNotification,\n clearSelection: () => {\n setSelectedNotification(null);\n setEvents([]);\n },\n };\n}\n"],"mappings":";;;;;;AAaA,IAAM,IAA2C;CAC/C,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,gBAAgB;CAChB,MAAM;CACN,SAAS;CACT,UAAU;CACX;AAED,SAAS,EAAY,GAA4C;AAE/D,QADI,MAAa,WAAiB,WAC1B,KAAyC;;AAGnD,SAAS,EAAU,GAAwC;AAGzD,QAFI,MAAW,cAAoB,aAC/B,MAAW,SAAe,cACtB,KAAqC;;AAG/C,SAAS,EACP,GAGc;AACd,QAAO;EACL,IAAI,EAAa;EACjB,OAAO,EAAa;EACpB,MAAM,EAAa;EACnB,MAAM,EAAa;EACnB,UAAU,EAAY,EAAa,SAAS;EAC5C,QAAQ,EAAU,EAAa,OAAO;EACtC,SAAS,EAAa;EACtB,gBAAgB,EAAa,kBAAkB,KAAA;EAC/C,WAAW,EAAa;EACxB,WAAW,EAAa;EACxB,QAAQ,EAAa,UAAU,KAAA;EAC/B,YAAY,EAAa,cAAc,KAAA;EACvC,WAAW,EAAa,aAAa,KAAA;EACrC,UAAU,EAAa,YAAY,KAAA;EACnC,aAAa,EAAa,eAAe,KAAA;EACzC,QAAQ,EAAa,UAAU,KAAA;EAC/B,WAAW,EAAa,eAAe,KAAA;EACvC,UAAU,EAAa,WAAW,EAAE,EAAE,KAAK,OAAY;GACrD,IAAI,EAAO;GACX,OAAO,EAAO;GACd,KAAK,EAAO;GACZ,OAAO,EAAO,SAAS,KAAA;GACvB,YAAY,EAAO,cAAc,KAAA;GACjC,UAAU,EAAO,YAAY,KAAA;GAC9B,EAAE;EACH,QAAQ,EAAa,SAAS,EAAE,EAAE,KAAK,OAAU;GAC/C,KAAK,EAAK;GACV,OAAO,EAAK,SA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AAI,GAAyB;GAC3C,CAAC,EACF,EAAqB,EAAE,QAAQ,UAAU,CAAC,EAC1C,MAAM,QAAQ,IAAI,CAAC,GAAoB,EAAE,GAA6B,CAAC,CAAC;IAE1E;EAAC;EAAoB;EAA6B;EAAW;EAAqB,CACnF,EAEK,IAAyB,EAC7B,OAAO,GAAiC,GAAsB,MAAsB;AAalF,EAXA,MADe,GAAW,CACb,OAAO;GAClB,UAAU;GACV,WAAW,EACT,OAAO;IACL;IACA;IACA;IACD,EACF;GACF,CAAC,EACF,EAAqB,EAAE,QAAQ,cAAc,CAAC,EAC9C,MAAM,QAAQ,IAAI,CAAC,GAAoB,EAAE,GAA6B,CAAC,CAAC;IAE1E;EAAC;EAAoB;EAA6B;EAAW;EAAqB,CACnF;AAOD,QALA,QAAgB;AAEd,EADA,GAAoB,EACpB,GAA6B;IAC5B,CAAC,GAAoB,EAA4B,CAAC,EAE9C;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;EACT;EACA;EACA;EACA;EACA;EACA,sBAAsB;AAEpB,GADA,EAAwB,KAAK,EAC7B,EAAU,EAAE,CAAC;;EAEhB"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Notification, NotificationPreferenceScope } from '../types';
|
|
2
|
+
import { NotificationChannelType, NotificationPriorityEnum, NotificationTypeEnum } from './useSendNotification';
|
|
3
|
+
|
|
4
|
+
interface NotificationAnalyticsPayload {
|
|
5
|
+
source?: 'center' | 'panel' | 'history' | 'preferences' | 'admin_history' | 'composer' | 'template_editor';
|
|
6
|
+
action?: 'open' | 'set' | 'reset' | 'send' | 'create' | 'update' | 'cancel' | 'reschedule';
|
|
7
|
+
interaction?: 'card' | 'primary_action' | 'custom_action';
|
|
8
|
+
scope?: 'GLOBAL' | 'CHANNEL' | 'TYPE' | 'TOPIC';
|
|
9
|
+
channel?: string;
|
|
10
|
+
type?: string;
|
|
11
|
+
priority?: string;
|
|
12
|
+
mode?: 'compose' | 'template';
|
|
13
|
+
recipientSource?: 'manual' | 'directory';
|
|
14
|
+
recipientCount?: number;
|
|
15
|
+
successCount?: number;
|
|
16
|
+
failedCount?: number;
|
|
17
|
+
scheduled?: boolean;
|
|
18
|
+
includeInApp?: boolean;
|
|
19
|
+
enabled?: boolean;
|
|
20
|
+
hasActions?: boolean;
|
|
21
|
+
hasMedia?: boolean;
|
|
22
|
+
hasHtml?: boolean;
|
|
23
|
+
variableCount?: number;
|
|
24
|
+
}
|
|
25
|
+
type NotificationAnalyticsSource = NonNullable<NotificationAnalyticsPayload['source']>;
|
|
26
|
+
type NotificationAnalyticsAction = NonNullable<NotificationAnalyticsPayload['action']>;
|
|
27
|
+
type NotificationInteraction = NonNullable<NotificationAnalyticsPayload['interaction']>;
|
|
28
|
+
interface NotificationSentInput {
|
|
29
|
+
mode: 'compose' | 'template';
|
|
30
|
+
channel: NotificationChannelType;
|
|
31
|
+
type?: NotificationTypeEnum | string;
|
|
32
|
+
priority?: NotificationPriorityEnum | string;
|
|
33
|
+
recipientSource: 'manual' | 'directory';
|
|
34
|
+
recipientCount: number;
|
|
35
|
+
successCount?: number;
|
|
36
|
+
failedCount?: number;
|
|
37
|
+
scheduled: boolean;
|
|
38
|
+
includeInApp: boolean;
|
|
39
|
+
hasActions: boolean;
|
|
40
|
+
hasMedia: boolean;
|
|
41
|
+
}
|
|
42
|
+
interface TemplateSavedInput {
|
|
43
|
+
action: Extract<NotificationAnalyticsAction, 'create' | 'update'>;
|
|
44
|
+
channel?: string;
|
|
45
|
+
type?: string;
|
|
46
|
+
variableCount: number;
|
|
47
|
+
hasHtml?: boolean;
|
|
48
|
+
}
|
|
49
|
+
interface PreferenceUpdatedInput {
|
|
50
|
+
action: Extract<NotificationAnalyticsAction, 'set' | 'reset'>;
|
|
51
|
+
scope: NotificationPreferenceScope;
|
|
52
|
+
channel?: string;
|
|
53
|
+
type?: string;
|
|
54
|
+
enabled?: boolean;
|
|
55
|
+
}
|
|
56
|
+
interface ScheduleUpdatedInput {
|
|
57
|
+
action: Extract<NotificationAnalyticsAction, 'cancel' | 'reschedule'>;
|
|
58
|
+
}
|
|
59
|
+
export declare function useNotificationAnalytics(): {
|
|
60
|
+
trackNotificationOpened: (notification: Notification, source: NotificationAnalyticsSource, interaction: NotificationInteraction) => void;
|
|
61
|
+
trackPreferenceUpdated: (input: PreferenceUpdatedInput) => void;
|
|
62
|
+
trackNotificationSent: (input: NotificationSentInput) => void;
|
|
63
|
+
trackTemplateSaved: (input: TemplateSavedInput) => void;
|
|
64
|
+
trackScheduleUpdated: (input: ScheduleUpdatedInput) => void;
|
|
65
|
+
};
|
|
66
|
+
export {};
|
|
67
|
+
//# sourceMappingURL=useNotificationAnalytics.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useNotificationAnalytics.d.ts","sourceRoot":"","sources":["../../src/hooks/useNotificationAnalytics.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AAC1E,OAAO,KAAK,EACV,uBAAuB,EACvB,wBAAwB,EACxB,oBAAoB,EACrB,MAAM,uBAAuB,CAAC;AAS/B,UAAU,4BAA4B;IACpC,MAAM,CAAC,EACH,QAAQ,GACR,OAAO,GACP,SAAS,GACT,aAAa,GACb,eAAe,GACf,UAAU,GACV,iBAAiB,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,YAAY,CAAC;IAC3F,WAAW,CAAC,EAAE,MAAM,GAAG,gBAAgB,GAAG,eAAe,CAAC;IAC1D,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,E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,QAAQ,CAAC,CAAC;IAClE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,UAAU,sBAAsB;IAC9B,MAAM,EAAE,OAAO,CAAC,2BAA2B,EAAE,KAAK,GAAG,OAAO,CAAC,CAAC;IAC9D,KAAK,EAAE,2BAA2B,CAAC;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,UAAU,oBAAoB;IAC5B,MAAM,EAAE,OAAO,CAAC,2BAA2B,EAAE,QAAQ,GAAG,YAAY,CAAC,CAAC;CACvE;AAmBD,wBAAgB,wBAAwB;4CAgBpB,YAAY,UAClB,2BAA2B,eACtB,uBAAuB;oCAU9B,sBAAsB;mCAatB,qBAAqB;gCAqBrB,kBAAkB;kCAalB,oBAAoB;EAgB/B"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { useCallback as e } from "react";
|
|
2
|
+
import { useEventBus as t } from "@burdenoff/fe-libs/shared/events";
|
|
3
|
+
//#region src/hooks/useNotificationAnalytics.ts
|
|
4
|
+
function n(e, t, n) {
|
|
5
|
+
return {
|
|
6
|
+
source: t,
|
|
7
|
+
action: "open",
|
|
8
|
+
interaction: n,
|
|
9
|
+
channel: e.channel,
|
|
10
|
+
type: e.type,
|
|
11
|
+
priority: e.priority,
|
|
12
|
+
hasActions: !!(e.actionUrl || e.actions.length > 0),
|
|
13
|
+
hasMedia: e.media.length > 0
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function r() {
|
|
17
|
+
let r = t(), i = e((e, t) => {
|
|
18
|
+
r.emit(e, t, { component: "microfe-notification" });
|
|
19
|
+
}, [r]);
|
|
20
|
+
return {
|
|
21
|
+
trackNotificationOpened: e((e, t, r) => i("notification.item.opened", n(e, t, r)), [i]),
|
|
22
|
+
trackPreferenceUpdated: e((e) => i("notification.preference.updated", {
|
|
23
|
+
source: "preferences",
|
|
24
|
+
action: e.action,
|
|
25
|
+
scope: e.scope,
|
|
26
|
+
channel: e.channel,
|
|
27
|
+
type: e.type,
|
|
28
|
+
enabled: e.enabled
|
|
29
|
+
}), [i]),
|
|
30
|
+
trackNotificationSent: e((e) => i("notification.admin.sent", {
|
|
31
|
+
source: "composer",
|
|
32
|
+
action: "send",
|
|
33
|
+
mode: e.mode,
|
|
34
|
+
channel: e.channel,
|
|
35
|
+
type: e.type,
|
|
36
|
+
priority: e.priority,
|
|
37
|
+
recipientSource: e.recipientSource,
|
|
38
|
+
recipientCount: e.recipientCount,
|
|
39
|
+
successCount: e.successCount,
|
|
40
|
+
failedCount: e.failedCount,
|
|
41
|
+
scheduled: e.scheduled,
|
|
42
|
+
includeInApp: e.includeInApp,
|
|
43
|
+
hasActions: e.hasActions,
|
|
44
|
+
hasMedia: e.hasMedia
|
|
45
|
+
}), [i]),
|
|
46
|
+
trackTemplateSaved: e((e) => i("notification.template.saved", {
|
|
47
|
+
source: "template_editor",
|
|
48
|
+
action: e.action,
|
|
49
|
+
channel: e.channel,
|
|
50
|
+
type: e.type,
|
|
51
|
+
variableCount: e.variableCount,
|
|
52
|
+
hasHtml: e.hasHtml
|
|
53
|
+
}), [i]),
|
|
54
|
+
trackScheduleUpdated: e((e) => i("notification.schedule.updated", {
|
|
55
|
+
source: "admin_history",
|
|
56
|
+
action: e.action,
|
|
57
|
+
scheduled: e.action === "reschedule"
|
|
58
|
+
}), [i])
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { r as useNotificationAnalytics };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=useNotificationAnalytics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useNotificationAnalytics.js","names":[],"sources":["../../src/hooks/useNotificationAnalytics.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useEventBus } from '@burdenoff/fe-libs/shared/events';\nimport type { Notification, NotificationPreferenceScope } from '../types';\nimport type {\n NotificationChannelType,\n NotificationPriorityEnum,\n NotificationTypeEnum,\n} from './useSendNotification';\n\ntype NotificationAnalyticsName =\n | 'notification.item.opened'\n | 'notification.preference.updated'\n | 'notification.admin.sent'\n | 'notification.template.saved'\n | 'notification.schedule.updated';\n\ninterface NotificationAnalyticsPayload {\n source?:\n | 'center'\n | 'panel'\n | 'history'\n | 'preferences'\n | 'admin_history'\n | 'composer'\n | 'template_editor';\n action?: 'open' | 'set' | 'reset' | 'send' | 'create' | 'update' | 'cancel' | 'reschedule';\n interaction?: 'card' | 'primary_action' | 'custom_action';\n scope?: 'GLOBAL' | 'CHANNEL' | 'TYPE' | 'TOPIC';\n channel?: string;\n type?: string;\n priority?: string;\n mode?: 'compose' | 'template';\n recipientSource?: 'manual' | 'directory';\n recipientCount?: number;\n successCount?: number;\n failedCount?: number;\n scheduled?: boolean;\n includeInApp?: boolean;\n enabled?: boolean;\n hasActions?: boolean;\n hasMedia?: boolean;\n hasHtml?: boolean;\n variableCount?: number;\n}\n\ninterface NotificationAnalyticsEventBus {\n emit: (\n name: NotificationAnalyticsName,\n payload: NotificationAnalyticsPayload,\n options?: { component?: string }\n ) => void;\n}\n\ntype NotificationAnalyticsSource = NonNullable<NotificationAnalyticsPayload['source']>;\ntype NotificationAnalyticsAction = NonNullable<NotificationAnalyticsPayload['action']>;\ntype NotificationInteraction = NonNullable<NotificationAnalyticsPayload['interaction']>;\n\ninterface NotificationSentInput {\n mode: 'compose' | 'template';\n channel: NotificationChannelType;\n type?: NotificationTypeEnum | string;\n priority?: NotificationPriorityEnum | string;\n recipientSource: 'manual' | 'directory';\n recipientCount: number;\n successCount?: number;\n failedCount?: number;\n scheduled: boolean;\n includeInApp: boolean;\n hasActions: boolean;\n hasMedia: boolean;\n}\n\ninterface TemplateSavedInput {\n action: Extract<NotificationAnalyticsAction, 'create' | 'update'>;\n channel?: string;\n type?: string;\n variableCount: number;\n hasHtml?: boolean;\n}\n\ninterface PreferenceUpdatedInput {\n action: Extract<NotificationAnalyticsAction, 'set' | 'reset'>;\n scope: NotificationPreferenceScope;\n channel?: string;\n type?: string;\n enabled?: boolean;\n}\n\ninterface ScheduleUpdatedInput {\n action: Extract<NotificationAnalyticsAction, 'cancel' | 'reschedule'>;\n}\n\nfunction toNotificationOpenPayload(\n notification: Notification,\n source: NotificationAnalyticsSource,\n interaction: NotificationInteraction\n): NotificationAnalyticsPayload {\n return {\n source,\n action: 'open',\n interaction,\n channel: notification.channel,\n type: notification.type,\n priority: notification.priority,\n hasActions: Boolean(notification.actionUrl || notification.actions.length > 0),\n hasMedia: notification.media.length > 0,\n };\n}\n\nexport function useNotificationAnalytics() {\n const eventBus = useEventBus();\n\n const emit = useCallback(\n (name: NotificationAnalyticsName, payload: NotificationAnalyticsPayload) => {\n // The runtime event bus accepts string names; this local typed facade keeps\n // notification emissions constrained to the sparse Rybbit allowlist while\n // consuming app shells roll forward to the updated fe-libs event registry.\n const notificationEventBus = eventBus as unknown as NotificationAnalyticsEventBus;\n notificationEventBus.emit(name, payload, { component: 'microfe-notification' });\n },\n [eventBus]\n );\n\n const trackNotificationOpened = useCallback(\n (\n notification: Notification,\n source: NotificationAnalyticsSource,\n interaction: NotificationInteraction\n ) =>\n emit(\n 'notification.item.opened',\n toNotificationOpenPayload(notification, source, interaction)\n ),\n [emit]\n );\n\n const trackPreferenceUpdated = useCallback(\n (input: PreferenceUpdatedInput) =>\n emit('notification.preference.updated', {\n source: 'preferences',\n action: input.action,\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n enabled: input.enabled,\n }),\n [emit]\n );\n\n const trackNotificationSent = useCallback(\n (input: NotificationSentInput) =>\n emit('notification.admin.sent', {\n source: 'composer',\n action: 'send',\n mode: input.mode,\n channel: input.channel,\n type: input.type,\n priority: input.priority,\n recipientSource: input.recipientSource,\n recipientCount: input.recipientCount,\n successCount: input.successCount,\n failedCount: input.failedCount,\n scheduled: input.scheduled,\n includeInApp: input.includeInApp,\n hasActions: input.hasActions,\n hasMedia: input.hasMedia,\n }),\n [emit]\n );\n\n const trackTemplateSaved = useCallback(\n (input: TemplateSavedInput) =>\n emit('notification.template.saved', {\n source: 'template_editor',\n action: input.action,\n channel: input.channel,\n type: input.type,\n variableCount: input.variableCount,\n hasHtml: input.hasHtml,\n }),\n [emit]\n );\n\n const trackScheduleUpdated = useCallback(\n (input: ScheduleUpdatedInput) =>\n emit('notification.schedule.updated', {\n source: 'admin_history',\n action: input.action,\n scheduled: input.action === 'reschedule',\n }),\n [emit]\n );\n\n return {\n trackNotificationOpened,\n trackPreferenceUpdated,\n trackNotificationSent,\n trackTemplateSaved,\n trackScheduleUpdated,\n };\n}\n"],"mappings":";;;AA4FA,SAAS,EACP,GACA,GACA,GAC8B;AAC9B,QAAO;EACL;EACA,QAAQ;EACR;EACA,SAAS,EAAa;EACtB,MAAM,EAAa;EACnB,UAAU,EAAa;EACvB,YAAY,GAAQ,EAAa,aAAa,EAAa,QAAQ,SAAS;EAC5E,UAAU,EAAa,MAAM,SAAS;EACvC;;AAGH,SAAgB,IAA2B;CACzC,IAAM,IAAW,GAAa,EAExB,IAAO,GACV,GAAiC,MAA0C;AAI7C,IACR,KAAK,GAAM,GAAS,EAAE,WAAW,wBAAwB,CAAC;IAEjF,CAAC,EAAS,CACX;AAwED,QAAO;EACL,yBAvE8B,GAE5B,GACA,GACA,MAEA,EACE,4BACA,EAA0B,GAAc,GAAQ,EAAY,CAC7D,EACH,CAAC,EAAK,CACP;EA6DC,wBA3D6B,GAC5B,MACC,EAAK,mCAAmC;GACtC,QAAQ;GACR,QAAQ,EAAM;GACd,OAAO,EAAM;GACb,SAAS,EAAM;GACf,MAAM,EAAM;GACZ,SAAS,EAAM;GAChB,CAAC,EACJ,CAAC,EAAK,CACP;EAiDC,uBA/C4B,GAC3B,MACC,EAAK,2BAA2B;GAC9B,QAAQ;GACR,QAAQ;GACR,MAAM,EAAM;GACZ,SAAS,EAAM;GACf,MAAM,EAAM;GACZ,UAAU,EAAM;GAChB,iBAAiB,EAAM;GACvB,gBAAgB,EAAM;GACtB,cAAc,EAAM;GACpB,aAAa,EAAM;GACnB,WAAW,EAAM;GACjB,cAAc,EAAM;GACpB,YAAY,EAAM;GAClB,UAAU,EAAM;GACjB,CAAC,EACJ,CAAC,EAAK,CACP;EA6BC,oBA3ByB,GACxB,MACC,EAAK,+BAA+B;GAClC,QAAQ;GACR,QAAQ,EAAM;GACd,SAAS,EAAM;GACf,MAAM,EAAM;GACZ,eAAe,EAAM;GACrB,SAAS,EAAM;GAChB,CAAC,EACJ,CAAC,EAAK,CACP;EAiBC,sBAf2B,GAC1B,MACC,EAAK,iCAAiC;GACpC,QAAQ;GACR,QAAQ,EAAM;GACd,WAAW,EAAM,WAAW;GAC7B,CAAC,EACJ,CAAC,EAAK,CACP;EAQA"}
|
|
@@ -42,7 +42,7 @@ function f() {
|
|
|
42
42
|
limit: 100,
|
|
43
43
|
offset: 0
|
|
44
44
|
},
|
|
45
|
-
fetchPolicy: "
|
|
45
|
+
fetchPolicy: "cache-first"
|
|
46
46
|
})).data?.notificationPreferences.items || []).map(d));
|
|
47
47
|
} catch (e) {
|
|
48
48
|
console.error("[useNotificationPreferences] Failed to fetch preferences:", e), y(e instanceof Error ? e.message : "Failed to fetch notification preferences");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationPreferences.js","names":[],"sources":["../../src/hooks/useNotificationPreferences.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport { useNotification } from '../providers/NotificationProvider';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n CreateNotificationPreferenceMutation,\n CreateNotificationPreferenceMutationVariables,\n DeleteNotificationPreferenceMutation,\n DeleteNotificationPreferenceMutationVariables,\n GetNotificationPreferencesQuery,\n NotificationPreferenceFieldsFragment,\n UpdateNotificationPreferenceMutation,\n UpdateNotificationPreferenceMutationVariables,\n} from '../generated/global-operations';\nimport type {\n NotificationPreference,\n NotificationPreferenceScope,\n UpsertNotificationPreferenceInput,\n} from '../types';\n\nfunction buildPreferenceKey(input: {\n scope: NotificationPreferenceScope;\n channel?: string;\n type?: string;\n topicId?: string;\n}): string {\n if (input.scope === 'CHANNEL') return `CHANNEL:${input.channel || ''}`;\n if (input.scope === 'TYPE') return `TYPE:${input.type || ''}`;\n if (input.scope === 'TOPIC') return `TOPIC:${input.topicId || ''}`;\n return 'GLOBAL';\n}\n\nfunction mapPreference(preference: NotificationPreferenceFieldsFragment): NotificationPreference {\n return {\n id: preference.id,\n userId: preference.userId,\n preferenceKey: preference.preferenceKey,\n scope: preference.scope,\n channel: preference.channel ?? undefined,\n type: preference.type ?? undefined,\n topicId: preference.topicId ?? undefined,\n enabled: preference.enabled,\n frequency: preference.frequency,\n quietHoursStart: preference.quietHoursStart ?? undefined,\n quietHoursEnd: preference.quietHoursEnd ?? undefined,\n timezone: preference.timezone ?? undefined,\n metadata: preference.metadata ?? undefined,\n createdAt: preference.createdAt,\n updatedAt: preference.updatedAt,\n topic: preference.topic\n ? {\n id: preference.topic.id,\n name: preference.topic.name,\n slug: preference.topic.slug,\n type: preference.topic.type,\n description: preference.topic.description ?? undefined,\n }\n : undefined,\n };\n}\n\nexport function useNotificationPreferences() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [preferences, setPreferences] = useState<NotificationPreference[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const preferencesByKey = useMemo(() => {\n return new Map(preferences.map((preference) => [preference.preferenceKey, preference]));\n }, [preferences]);\n\n const fetchPreferences = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationPreferencesQuery>({\n query: NotificationOps.GetNotificationPreferencesDocument,\n variables: { limit: 100, offset: 0 },\n fetchPolicy: '
|
|
1
|
+
{"version":3,"file":"useNotificationPreferences.js","names":[],"sources":["../../src/hooks/useNotificationPreferences.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport { useNotification } from '../providers/NotificationProvider';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n CreateNotificationPreferenceMutation,\n CreateNotificationPreferenceMutationVariables,\n DeleteNotificationPreferenceMutation,\n DeleteNotificationPreferenceMutationVariables,\n GetNotificationPreferencesQuery,\n NotificationPreferenceFieldsFragment,\n UpdateNotificationPreferenceMutation,\n UpdateNotificationPreferenceMutationVariables,\n} from '../generated/global-operations';\nimport type {\n NotificationPreference,\n NotificationPreferenceScope,\n UpsertNotificationPreferenceInput,\n} from '../types';\n\nfunction buildPreferenceKey(input: {\n scope: NotificationPreferenceScope;\n channel?: string;\n type?: string;\n topicId?: string;\n}): string {\n if (input.scope === 'CHANNEL') return `CHANNEL:${input.channel || ''}`;\n if (input.scope === 'TYPE') return `TYPE:${input.type || ''}`;\n if (input.scope === 'TOPIC') return `TOPIC:${input.topicId || ''}`;\n return 'GLOBAL';\n}\n\nfunction mapPreference(preference: NotificationPreferenceFieldsFragment): NotificationPreference {\n return {\n id: preference.id,\n userId: preference.userId,\n preferenceKey: preference.preferenceKey,\n scope: preference.scope,\n channel: preference.channel ?? undefined,\n type: preference.type ?? undefined,\n topicId: preference.topicId ?? undefined,\n enabled: preference.enabled,\n frequency: preference.frequency,\n quietHoursStart: preference.quietHoursStart ?? undefined,\n quietHoursEnd: preference.quietHoursEnd ?? undefined,\n timezone: preference.timezone ?? undefined,\n metadata: preference.metadata ?? undefined,\n createdAt: preference.createdAt,\n updatedAt: preference.updatedAt,\n topic: preference.topic\n ? {\n id: preference.topic.id,\n name: preference.topic.name,\n slug: preference.topic.slug,\n type: preference.topic.type,\n description: preference.topic.description ?? undefined,\n }\n : undefined,\n };\n}\n\nexport function useNotificationPreferences() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [preferences, setPreferences] = useState<NotificationPreference[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const preferencesByKey = useMemo(() => {\n return new Map(preferences.map((preference) => [preference.preferenceKey, preference]));\n }, [preferences]);\n\n const fetchPreferences = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationPreferencesQuery>({\n query: NotificationOps.GetNotificationPreferencesDocument,\n variables: { limit: 100, offset: 0 },\n fetchPolicy: 'cache-first',\n });\n setPreferences((result.data?.notificationPreferences.items || []).map(mapPreference));\n } catch (err) {\n console.error('[useNotificationPreferences] Failed to fetch preferences:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch notification preferences');\n } finally {\n setIsLoading(false);\n }\n }, [getClient]);\n\n useEffect(() => {\n fetchPreferences();\n }, [fetchPreferences]);\n\n const setPreference = useCallback(\n async (input: UpsertNotificationPreferenceInput): Promise<NotificationPreference | null> => {\n const client = getClient();\n const preferenceKey = buildPreferenceKey(input);\n const existing = preferencesByKey.get(preferenceKey);\n\n if (existing) {\n const result = await client.mutate<\n UpdateNotificationPreferenceMutation,\n UpdateNotificationPreferenceMutationVariables\n >({\n mutation: NotificationOps.UpdateNotificationPreferenceDocument,\n variables: {\n id: existing.id,\n input: {\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n topicId: input.topicId,\n enabled: input.enabled,\n frequency: input.frequency,\n quietHoursStart: input.quietHoursStart,\n quietHoursEnd: input.quietHoursEnd,\n timezone: input.timezone,\n metadata: input.metadata,\n } as UpdateNotificationPreferenceMutationVariables['input'],\n },\n });\n const updated = result.data?.updateNotificationPreference;\n if (!updated) return null;\n const mapped = mapPreference(updated);\n setPreferences((prev) => prev.map((item) => (item.id === mapped.id ? mapped : item)));\n return mapped;\n }\n\n const result = await client.mutate<\n CreateNotificationPreferenceMutation,\n CreateNotificationPreferenceMutationVariables\n >({\n mutation: NotificationOps.CreateNotificationPreferenceDocument,\n variables: {\n input: {\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n topicId: input.topicId,\n enabled: input.enabled,\n frequency: input.frequency || 'IMMEDIATE',\n quietHoursStart: input.quietHoursStart,\n quietHoursEnd: input.quietHoursEnd,\n timezone: input.timezone,\n metadata: input.metadata,\n } as CreateNotificationPreferenceMutationVariables['input'],\n },\n });\n const created = result.data?.createNotificationPreference;\n if (!created) return null;\n const mapped = mapPreference(created);\n setPreferences((prev) => [mapped, ...prev]);\n return mapped;\n },\n [getClient, preferencesByKey]\n );\n\n const deletePreference = useCallback(\n async (id: string): Promise<boolean> => {\n const client = getClient();\n const result = await client.mutate<\n DeleteNotificationPreferenceMutation,\n DeleteNotificationPreferenceMutationVariables\n >({\n mutation: NotificationOps.DeleteNotificationPreferenceDocument,\n variables: { id },\n });\n if (result.data?.deleteNotificationPreference) {\n setPreferences((prev) => prev.filter((preference) => preference.id !== id));\n return true;\n }\n return false;\n },\n [getClient]\n );\n\n return {\n preferences,\n preferencesByKey,\n isLoading,\n error,\n refetch: fetchPreferences,\n setPreference,\n deletePreference,\n };\n}\n"],"mappings":";;;;;AAoBA,SAAS,EAAmB,GAKjB;AAIT,QAHI,EAAM,UAAU,YAAkB,WAAW,EAAM,WAAW,OAC9D,EAAM,UAAU,SAAe,QAAQ,EAAM,QAAQ,OACrD,EAAM,UAAU,UAAgB,SAAS,EAAM,WAAW,OACvD;;AAGT,SAAS,EAAc,GAA0E;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,QAAQ,EAAW;EACnB,eAAe,EAAW;EAC1B,OAAO,EAAW;EAClB,SAAS,EAAW,WAAW,KAAA;EAC/B,MAAM,EAAW,QAAQ,KA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QAAQ,MAAe,EAAW,OAAO,EAAG,CAAC,EACpE,MAEF,IAET,CAAC,EAAU,CACZ;EAUA"}
|
|
@@ -17,7 +17,7 @@ function u(i) {
|
|
|
17
17
|
limit: 50,
|
|
18
18
|
offset: 0
|
|
19
19
|
},
|
|
20
|
-
fetchPolicy: "
|
|
20
|
+
fetchPolicy: "cache-first"
|
|
21
21
|
});
|
|
22
22
|
e.data?.notificationTemplates && (p(e.data.notificationTemplates.items || []), D(e.data.notificationTemplates.total || 0), T(e.data.notificationTemplates.hasMore || !1), k(50));
|
|
23
23
|
} catch (e) {
|
|
@@ -83,7 +83,7 @@ function u(i) {
|
|
|
83
83
|
limit: 50,
|
|
84
84
|
offset: O
|
|
85
85
|
},
|
|
86
|
-
fetchPolicy: "
|
|
86
|
+
fetchPolicy: "cache-first"
|
|
87
87
|
});
|
|
88
88
|
if (e.data?.notificationTemplates) {
|
|
89
89
|
let t = e.data.notificationTemplates.items || [];
|
|
@@ -138,7 +138,7 @@ function d(n, r) {
|
|
|
138
138
|
slug: n,
|
|
139
139
|
locale: r
|
|
140
140
|
},
|
|
141
|
-
fetchPolicy: "
|
|
141
|
+
fetchPolicy: "cache-first"
|
|
142
142
|
});
|
|
143
143
|
e.data?.notificationTemplate && d(e.data.notificationTemplate);
|
|
144
144
|
} catch (e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationTemplates.js","names":[],"sources":["../../src/hooks/useNotificationTemplates.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationType } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTemplatesQuery,\n GetNotificationTemplateQuery,\n CreateNotificationTemplateMutation,\n UpdateNotificationTemplateMutation,\n} from '../generated/global-operations';\n\n/**\n * Backend template type derived from the generated query\n */\nexport type BackendNotificationTemplate =\n GetNotificationTemplatesQuery['notificationTemplates']['items'][number];\n/**\n * Input type for creating a template (matches backend CreateTemplateInput)\n * Note: Templates are content-only - channel is specified at send time\n */\nexport interface CreateTemplateInput {\n slug: string;\n name: string;\n description?: string;\n type: NotificationType;\n channel?: string;\n locale?: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input type for updating a template (matches backend UpdateTemplateInput)\n */\nexport interface UpdateTemplateInput {\n name?: string;\n description?: string;\n subject?: string;\n bodyTemplate?: string;\n htmlTemplate?: string;\n variables?: Record<string, unknown>;\n enabled?: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Filter options for templates (matches backend TemplateFilterInput)\n * Note: channel filter removed - templates are content-only\n */\nexport interface TemplateFilter {\n type?: NotificationType;\n locale?: string;\n enabled?: boolean;\n search?: string; // Local filter only\n}\n\n/**\n * Hook to manage notification templates\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplates(initialFilter?: TemplateFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [templates, setTemplates] = useState<BackendNotificationTemplate[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isCreating, setIsCreating] = useState(false);\n const [isUpdating, setIsUpdating] = useState(false);\n const [isDeleting, setIsDeleting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [total, setTotal] = useState(0);\n const [offset, setOffset] = useState(0);\n const [filter, setFilter] = useState<TemplateFilter>(initialFilter || {});\n\n const LIMIT = 50;\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Build backend filter (excludes local-only 'search')\n const buildBackendFilter = useCallback(() => {\n const backendFilter: Record<string, unknown> = {};\n if (filter.type) backendFilter.type = filter.type;\n if (filter.locale) backendFilter.locale = filter.locale;\n if (filter.enabled !== undefined) backendFilter.enabled = filter.enabled;\n return Object.keys(backendFilter).length > 0 ? backendFilter : undefined;\n }, [filter]);\n\n // Fetch templates\n const fetchTemplates = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplatesQuery>({\n query: NotificationOps.GetNotificationTemplatesDocument,\n variables: {\n filter: buildBackendFilter(),\n limit: LIMIT,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notificationTemplates) {\n setTemplates(result.data.notificationTemplates.items || []);\n setTotal(result.data.notificationTemplates.total || 0);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset(LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch templates';\n console.error('[useNotificationTemplates] Failed to fetch templates:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, buildBackendFilter]);\n\n // Initial fetch\n useEffect(() => {\n fetchTemplates();\n }, [fetchTemplates]);\n\n // Filter by search locally\n const filteredTemplates = filter.search\n ? templates.filter(\n (t) =>\n t.name.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.slug.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.description?.toLowerCase().includes(filter.search!.toLowerCase())\n )\n : templates;\n\n // Create template\n const createTemplate = useCallback(\n async (input: CreateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsCreating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTemplateMutation>({\n mutation: NotificationOps.CreateNotificationTemplateDocument,\n variables: { input },\n });\n await fetchTemplates();\n return result.data!.createNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to create template';\n console.error('Failed to create template:', err);\n setError(message);\n throw err;\n } finally {\n setIsCreating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Update template\n const updateTemplate = useCallback(\n async (id: string, input: UpdateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsUpdating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTemplateMutation>({\n mutation: NotificationOps.UpdateNotificationTemplateDocument,\n variables: { id, input },\n });\n await fetchTemplates();\n return result.data!.updateNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to update template';\n console.error('Failed to update template:', err);\n setError(message);\n throw err;\n } finally {\n setIsUpdating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Delete template\n const deleteTemplate = useCallback(\n async (id: string): Promise<boolean> => {\n setIsDeleting(true);\n setError(null);\n\n try {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTemplateDocument,\n variables: { id },\n });\n await fetchTemplates();\n return true;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to delete template';\n console.error('Failed to delete template:', err);\n setError(message);\n throw err;\n } finally {\n setIsDeleting(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Load more templates\n const loadMore = useCallback(async () => {\n if (!hasMore) return;\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplatesQuery>({\n query: NotificationOps.GetNotificationTemplatesDocument,\n variables: {\n filter: buildBackendFilter(),\n limit: LIMIT,\n offset: offset,\n },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notificationTemplates) {\n const moreTemplates = result.data.notificationTemplates.items || [];\n setTemplates((prev) => [...prev, ...moreTemplates]);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset((prev) => prev + LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to load more templates';\n console.error('Failed to load more templates:', err);\n setError(message);\n }\n }, [getClient, buildBackendFilter, hasMore, offset]);\n\n // Update filter\n const updateFilter = useCallback((newFilter: Partial<TemplateFilter>) => {\n setFilter((prev) => ({ ...prev, ...newFilter }));\n }, []);\n\n // Reset filter\n const resetFilter = useCallback(() => {\n setFilter({});\n }, []);\n\n return {\n templates: filteredTemplates,\n allTemplates: templates,\n isLoading,\n isCreating,\n isUpdating,\n isDeleting,\n isMutating: isCreating || isUpdating || isDeleting,\n error,\n hasMore,\n total,\n filter,\n refetch: fetchTemplates,\n loadMore,\n createTemplate,\n updateTemplate,\n deleteTemplate,\n updateFilter,\n resetFilter,\n };\n}\n\n/**\n * Hook to fetch a single template by slug\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplate(slug: string | undefined, locale?: string) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [template, setTemplate] = useState<BackendNotificationTemplate | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Fetch template\n const fetchTemplate = useCallback(async () => {\n if (!slug) return;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplateQuery>({\n query: NotificationOps.GetNotificationTemplateDocument,\n variables: { slug, locale },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notificationTemplate) {\n setTemplate(result.data.notificationTemplate);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch template';\n console.error('[useNotificationTemplate] Failed to fetch template:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, slug, locale]);\n\n // Fetch on mount and when slug changes\n useEffect(() => {\n fetchTemplate();\n }, [fetchTemplate]);\n\n return {\n template,\n isLoading,\n error,\n refetch: fetchTemplate,\n };\n}\n"],"mappings":";;;;;AAgEA,SAAgB,EAAyB,GAAgC;CACvE,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAW,KAAgB,EAAwC,EAAE,CAAC,EACvE,CAAC,GAAW,KAAgB,EAAS,GAAM,EAC3C,CAAC,GAAY,KAAiB,EAAS,GAAM,EAC7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IAAY,QACT,EAA4B,KAAiB,KAAA,GAAW,KAAa,KAAA,EAAU,EACrF,CAAC,GAAe,EAAU,CAAC,EAGxB,IAAgB,EAAY,YAAY;AACvC,SAGL;GADA,EAAa,GAAK,EAClB,EAAS,KAAK;AAEd,OAAI;IAEF,IAAM,IAAS,MADA,GAAW,CACE,MAAoC;KAC9D,OAAO;KACP,WAAW;MAAE;MAAM;MAAQ;KAC3B,aAAa;KACd,CAAC;AAEF,IAAI,EAAO,MAAM,wBACf,EAAY,EAAO,KAAK,qBAAqB;YAExC,GAAc;IACrB,IAAM,IAAU,aAAe,QAAQ,EAAI,UAAU;AAErD,IADA,QAAQ,MAAM,uDAAuD,EAAI,EACzE,EAAS,EAAQ;aACT;AACR,MAAa,GAAM;;;IAEpB;EAAC;EAAW;EAAM;EAAO,CAAC;AAO7B,QAJA,QAAgB;AACd,KAAe;IACd,CAAC,EAAc,CAAC,EAEZ;EACL;EACA;EACA;EACA,SAAS;EACV"}
|
|
1
|
+
{"version":3,"file":"useNotificationTemplates.js","names":[],"sources":["../../src/hooks/useNotificationTemplates.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationType } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTemplatesQuery,\n GetNotificationTemplateQuery,\n CreateNotificationTemplateMutation,\n UpdateNotificationTemplateMutation,\n} from '../generated/global-operations';\n\n/**\n * Backend template type derived from the generated query\n */\nexport type BackendNotificationTemplate =\n GetNotificationTemplatesQuery['notificationTemplates']['items'][number];\n/**\n * Input type for creating a template (matches backend CreateTemplateInput)\n * Note: Templates are content-only - channel is specified at send time\n */\nexport interface CreateTemplateInput {\n slug: string;\n name: string;\n description?: string;\n type: NotificationType;\n channel?: string;\n locale?: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input type for updating a template (matches backend UpdateTemplateInput)\n */\nexport interface UpdateTemplateInput {\n name?: string;\n description?: string;\n subject?: string;\n bodyTemplate?: string;\n htmlTemplate?: string;\n variables?: Record<string, unknown>;\n enabled?: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Filter options for templates (matches backend TemplateFilterInput)\n * Note: channel filter removed - templates are content-only\n */\nexport interface TemplateFilter {\n type?: NotificationType;\n locale?: string;\n enabled?: boolean;\n search?: string; // Local filter only\n}\n\n/**\n * Hook to manage notification templates\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplates(initialFilter?: TemplateFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [templates, setTemplates] = useState<BackendNotificationTemplate[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isCreating, setIsCreating] = useState(false);\n const [isUpdating, setIsUpdating] = useState(false);\n const [isDeleting, setIsDeleting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [total, setTotal] = useState(0);\n const [offset, setOffset] = useState(0);\n const [filter, setFilter] = useState<TemplateFilter>(initialFilter || {});\n\n const LIMIT = 50;\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Build backend filter (excludes local-only 'search')\n const buildBackendFilter = useCallback(() => {\n const backendFilter: Record<string, unknown> = {};\n if (filter.type) backendFilter.type = filter.type;\n if (filter.locale) backendFilter.locale = filter.locale;\n if (filter.enabled !== undefined) backendFilter.enabled = filter.enabled;\n return Object.keys(backendFilter).length > 0 ? backendFilter : undefined;\n }, [filter]);\n\n // Fetch templates\n const fetchTemplates = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplatesQuery>({\n query: NotificationOps.GetNotificationTemplatesDocument,\n variables: {\n filter: buildBackendFilter(),\n limit: LIMIT,\n offset: 0,\n },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplates) {\n setTemplates(result.data.notificationTemplates.items || []);\n setTotal(result.data.notificationTemplates.total || 0);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset(LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch templates';\n console.error('[useNotificationTemplates] Failed to fetch templates:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, buildBackendFilter]);\n\n // Initial fetch\n useEffect(() => {\n fetchTemplates();\n }, [fetchTemplates]);\n\n // Filter by search locally\n const filteredTemplates = filter.search\n ? templates.filter(\n (t) =>\n t.name.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.slug.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.description?.toLowerCase().includes(filter.search!.toLowerCase())\n )\n : templates;\n\n // Create template\n const createTemplate = useCallback(\n async (input: CreateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsCreating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTemplateMutation>({\n mutation: NotificationOps.CreateNotificationTemplateDocument,\n variables: { input },\n });\n await fetchTemplates();\n return result.data!.createNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to create template';\n console.error('Failed to create template:', err);\n setError(message);\n throw err;\n } finally {\n setIsCreating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Update template\n const updateTemplate = useCallback(\n async (id: string, input: UpdateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsUpdating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTemplateMutation>({\n mutation: NotificationOps.UpdateNotificationTemplateDocument,\n variables: { id, input },\n });\n await fetchTemplates();\n return result.data!.updateNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to update template';\n console.error('Failed to update template:', err);\n setError(message);\n throw err;\n } finally {\n setIsUpdating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Delete template\n const deleteTemplate = useCallback(\n async (id: string): Promise<boolean> => {\n setIsDeleting(true);\n setError(null);\n\n try {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTemplateDocument,\n variables: { id },\n });\n await fetchTemplates();\n return true;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to delete template';\n console.error('Failed to delete template:', err);\n setError(message);\n throw err;\n } finally {\n setIsDeleting(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Load more templates\n const loadMore = useCallback(async () => {\n if (!hasMore) return;\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplatesQuery>({\n query: NotificationOps.GetNotificationTemplatesDocument,\n variables: {\n filter: buildBackendFilter(),\n limit: LIMIT,\n offset: offset,\n },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplates) {\n const moreTemplates = result.data.notificationTemplates.items || [];\n setTemplates((prev) => [...prev, ...moreTemplates]);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset((prev) => prev + LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to load more templates';\n console.error('Failed to load more templates:', err);\n setError(message);\n }\n }, [getClient, buildBackendFilter, hasMore, offset]);\n\n // Update filter\n const updateFilter = useCallback((newFilter: Partial<TemplateFilter>) => {\n setFilter((prev) => ({ ...prev, ...newFilter }));\n }, []);\n\n // Reset filter\n const resetFilter = useCallback(() => {\n setFilter({});\n }, []);\n\n return {\n templates: filteredTemplates,\n allTemplates: templates,\n isLoading,\n isCreating,\n isUpdating,\n isDeleting,\n isMutating: isCreating || isUpdating || isDeleting,\n error,\n hasMore,\n total,\n filter,\n refetch: fetchTemplates,\n loadMore,\n createTemplate,\n updateTemplate,\n deleteTemplate,\n updateFilter,\n resetFilter,\n };\n}\n\n/**\n * Hook to fetch a single template by slug\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplate(slug: string | undefined, locale?: string) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [template, setTemplate] = useState<BackendNotificationTemplate | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Fetch template\n const fetchTemplate = useCallback(async () => {\n if (!slug) return;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplateQuery>({\n query: NotificationOps.GetNotificationTemplateDocument,\n variables: { slug, locale },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplate) {\n setTemplate(result.data.notificationTemplate);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch template';\n console.error('[useNotificationTemplate] Failed to fetch template:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, slug, locale]);\n\n // Fetch on mount and when slug changes\n useEffect(() => {\n fetchTemplate();\n }, [fetchTemplate]);\n\n return {\n template,\n isLoading,\n error,\n refetch: fetchTemplate,\n };\n}\n"],"mappings":";;;;;AAgEA,SAAgB,EAAyB,GAAgC;CACvE,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAW,KAAgB,EAAwC,EAAE,CAAC,EACvE,CAAC,GAAW,KAAgB,EAAS,GAAM,EAC3C,CAAC,GAAY,KAAiB,EAAS,GAAM,EAC7C,CAAC,GAAY,KAAiB,EAAS,GAAM,EAC7C,CAAC,GAAY,KAAiB,EAAS,GAAM,EAC7C,CAAC,GAAO,KAAY,EAAwB,KAAK,EACjD,CAAC,GAAS,KAAc,EAAS,GAAM,EACvC,CAAC,GAAO,KAAY,EAAS,EAAE,EAC/B,CAAC,GAAQ,KAAa,EAAS,EAAE,EACjC,CA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WAAW;MAAE;MAAM;MAAQ;KAC3B,aAAa;KACd,CAAC;AAEF,IAAI,EAAO,MAAM,wBACf,EAAY,EAAO,KAAK,qBAAqB;YAExC,GAAc;IACrB,IAAM,IAAU,aAAe,QAAQ,EAAI,UAAU;AAErD,IADA,QAAQ,MAAM,uDAAuD,EAAI,EACzE,EAAS,EAAQ;aACT;AACR,MAAa,GAAM;;;IAEpB;EAAC;EAAW;EAAM;EAAO,CAAC;AAO7B,QAJA,QAAgB;AACd,KAAe;IACd,CAAC,EAAc,CAAC,EAEZ;EACL;EACA;EACA;EACA,SAAS;EACV"}
|
|
@@ -39,7 +39,7 @@ function d(d) {
|
|
|
39
39
|
limit: 100,
|
|
40
40
|
offset: 0
|
|
41
41
|
},
|
|
42
|
-
fetchPolicy: "
|
|
42
|
+
fetchPolicy: "cache-first"
|
|
43
43
|
})).data?.notificationTopics.items || []).map(u));
|
|
44
44
|
} catch (e) {
|
|
45
45
|
console.error("[useNotificationTopics] Failed to fetch topics:", e), y(e instanceof Error ? e.message : "Failed to fetch topics"), h([]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationTopics.js","names":[],"sources":["../../src/hooks/useNotificationTopics.ts"],"sourcesContent":["import { useState, useEffect, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationTopic, NotificationTopicSubscription } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTopicsQuery,\n CreateNotificationTopicMutation,\n UpdateNotificationTopicMutation,\n SetNotificationTopicSubscriptionMutation,\n} from '../generated/global-operations';\n\nexport interface NotificationTopicFilter {\n search?: string;\n type?: string;\n isActive?: boolean;\n}\n\nexport interface CreateNotificationTopicInput {\n name: string;\n slug: string;\n description?: string;\n type: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateNotificationTopicInput {\n name?: string;\n slug?: string;\n description?: string;\n type?: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nfunction mapTopic(\n topic: GetNotificationTopicsQuery['notificationTopics']['items'][number]\n): NotificationTopic {\n return {\n id: topic.id,\n slug: topic.slug,\n name: topic.name,\n description: topic.description ?? undefined,\n type: topic.type as NotificationTopic['type'],\n isActive: topic.isActive,\n metadata: topic.metadata ?? undefined,\n subscriberCount: topic.subscriberCount ?? 0,\n mySubscription: topic.mySubscription\n ? {\n id: topic.mySubscription.id,\n subscribed: topic.mySubscription.subscribed,\n unsubscribedAt: topic.mySubscription.unsubscribedAt ?? undefined,\n topicId: topic.mySubscription.topicId,\n userId: topic.mySubscription.userId,\n }\n : undefined,\n createdAt: topic.createdAt,\n updatedAt: topic.updatedAt,\n };\n}\n\nexport function useNotificationTopics(initialFilter?: NotificationTopicFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [topics, setTopics] = useState<NotificationTopic[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [filter, setFilter] = useState<NotificationTopicFilter>(initialFilter || {});\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchTopics = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTopicsQuery>({\n query: NotificationOps.GetNotificationTopicsDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search } : {}),\n ...(filter.type ? { type: filter.type } : {}),\n ...(filter.isActive !== undefined ? { isActive: filter.isActive } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: '
|
|
1
|
+
{"version":3,"file":"useNotificationTopics.js","names":[],"sources":["../../src/hooks/useNotificationTopics.ts"],"sourcesContent":["import { useState, useEffect, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationTopic, NotificationTopicSubscription } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTopicsQuery,\n CreateNotificationTopicMutation,\n UpdateNotificationTopicMutation,\n SetNotificationTopicSubscriptionMutation,\n} from '../generated/global-operations';\n\nexport interface NotificationTopicFilter {\n search?: string;\n type?: string;\n isActive?: boolean;\n}\n\nexport interface CreateNotificationTopicInput {\n name: string;\n slug: string;\n description?: string;\n type: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateNotificationTopicInput {\n name?: string;\n slug?: string;\n description?: string;\n type?: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nfunction mapTopic(\n topic: GetNotificationTopicsQuery['notificationTopics']['items'][number]\n): NotificationTopic {\n return {\n id: topic.id,\n slug: topic.slug,\n name: topic.name,\n description: topic.description ?? undefined,\n type: topic.type as NotificationTopic['type'],\n isActive: topic.isActive,\n metadata: topic.metadata ?? undefined,\n subscriberCount: topic.subscriberCount ?? 0,\n mySubscription: topic.mySubscription\n ? {\n id: topic.mySubscription.id,\n subscribed: topic.mySubscription.subscribed,\n unsubscribedAt: topic.mySubscription.unsubscribedAt ?? undefined,\n topicId: topic.mySubscription.topicId,\n userId: topic.mySubscription.userId,\n }\n : undefined,\n createdAt: topic.createdAt,\n updatedAt: topic.updatedAt,\n };\n}\n\nexport function useNotificationTopics(initialFilter?: NotificationTopicFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [topics, setTopics] = useState<NotificationTopic[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [filter, setFilter] = useState<NotificationTopicFilter>(initialFilter || {});\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchTopics = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTopicsQuery>({\n query: NotificationOps.GetNotificationTopicsDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search } : {}),\n ...(filter.type ? { type: filter.type } : {}),\n ...(filter.isActive !== undefined ? { isActive: filter.isActive } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'cache-first',\n });\n\n setTopics((result.data?.notificationTopics.items || []).map(mapTopic));\n } catch (err) {\n console.error('[useNotificationTopics] Failed to fetch topics:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch topics');\n setTopics([]);\n } finally {\n setIsLoading(false);\n }\n }, [filter, getClient]);\n\n useEffect(() => {\n fetchTopics();\n }, [fetchTopics]);\n\n const createTopic = useCallback(\n async (input: CreateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTopicMutation>({\n mutation: NotificationOps.CreateNotificationTopicDocument,\n variables: { input },\n });\n await fetchTopics();\n const created = result.data?.createNotificationTopic;\n return created\n ? {\n id: created.id,\n slug: created.slug,\n name: created.name,\n description: created.description ?? undefined,\n type: created.type as NotificationTopic['type'],\n isActive: created.isActive,\n subscriberCount: 0,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const updateTopic = useCallback(\n async (id: string, input: UpdateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTopicMutation>({\n mutation: NotificationOps.UpdateNotificationTopicDocument,\n variables: { id, input },\n });\n await fetchTopics();\n const updated = result.data?.updateNotificationTopic;\n return updated\n ? {\n id: updated.id,\n slug: updated.slug,\n name: updated.name,\n description: updated.description ?? undefined,\n type: updated.type as NotificationTopic['type'],\n isActive: updated.isActive,\n subscriberCount: 0,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const deleteTopic = useCallback(\n async (id: string): Promise<boolean> => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTopicDocument,\n variables: { id },\n });\n await fetchTopics();\n return true;\n },\n [fetchTopics, getClient]\n );\n\n const setTopicSubscription = useCallback(\n async (topicId: string, subscribed: boolean): Promise<NotificationTopicSubscription | null> => {\n const client = getClient();\n const result = await client.mutate<SetNotificationTopicSubscriptionMutation>({\n mutation: NotificationOps.SetNotificationTopicSubscriptionDocument,\n variables: {\n input: {\n topicId,\n subscribed,\n },\n },\n });\n await fetchTopics();\n\n const subscription = result.data?.setNotificationTopicSubscription;\n return subscription\n ? {\n id: subscription.id,\n subscribed: subscription.subscribed,\n unsubscribedAt: subscription.unsubscribedAt ?? undefined,\n topicId: subscription.topicId,\n userId: subscription.userId,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n return {\n topics,\n isLoading,\n error,\n filter,\n setFilter,\n refetch: fetchTopics,\n createTopic,\n updateTopic,\n deleteTopic,\n setTopicSubscription,\n };\n}\n"],"mappings":";;;;;AAoCA,SAAS,EACP,GACmB;AACnB,QAAO;EACL,IAAI,EAAM;EACV,MAAM,EAAM;EACZ,MAAM,EAAM;EACZ,aAAa,EAAM,eAAe,KAAA;EAClC,MAAM,EAAM;EACZ,UAAU,EAAM;EAChB,UAAU,EAAM,YAAY,KAAA;EAC5B,iBAAiB,EAAM,mBAAmB;EAC1C,gBAAgB,EAAM,iBAClB;GACE,IAAI,EAAM,eAAe;GACzB,YAAY,EAAM,eAAe;GACjC,gBAAgB,EAAM,eAAe,kBAAkB,KAAA;GACvD,SAAS,EAAM,eAAe;GAC9B,QAAQ,EAAM,eAAe;GAC9B,GACD,KAAA;EACJ,WAAW,EAAM;EACjB,WAAW,EAAM;EAClB;;AAGH,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAQ,KAAa,EAA8B,EAAE,CAAC,EACvD,CAAC,GAAW,KAAgB,EAAS,GAAM,EAC3C,CAAC,GAAO,KAAY,EAAwB,KAAK,EACjD,CAAC,GAAQ,KAAa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AEN,CAAC,GAAa,EAAU,CACzB;EA6EC,aA3EkB,EAClB,OAAO,GAAY,MAA2E;GAE5F,IAAM,IAAS,MADA,GAAW,CACE,OAAwC;IAClE,UAAU;IACV,WAAW;KAAE;KAAI;KAAO;IACzB,CAAC;AACF,SAAM,GAAa;GACnB,IAAM,IAAU,EAAO,MAAM;AAC7B,UAAO,IACH;IACE,IAAI,EAAQ;IACZ,MAAM,EAAQ;IACd,MAAM,EAAQ;IACd,aAAa,EAAQ,eAAe,KAAA;IACpC,MAAM,EAAQ;IACd,UAAU,EAAQ;IAClB,iBAAiB;IACjB,WAAW,EAAQ;IACnB,WAAW,EAAQ;IACpB,GACD;KAEN,CAAC,GAAa,EAAU,CACzB;EAoDC,aAlDkB,EAClB,OAAO,OAEL,MADe,GAAW,CACb,OAAO;GAClB,UAAU;GACV,WAAW,EAAE,OAAI;GAClB,CAAC,EACF,MAAM,GAAa,EACZ,KAET,CAAC,GAAa,EAAU,CACzB;EAwCC,sBAtC2B,EAC3B,OAAO,GAAiB,MAAuE;GAE7F,IAAM,IAAS,MADA,GAAW,CACE,OAAiD;IAC3E,UAAU;IACV,WAAW,EACT,OAAO;KACL;KACA;KACD,EACF;IACF,CAAC;AACF,SAAM,GAAa;GAEnB,IAAM,IAAe,EAAO,MAAM;AAClC,UAAO,IACH;IACE,IAAI,EAAa;IACjB,YAAY,EAAa;IACzB,gBAAgB,EAAa,kBAAkB,KAAA;IAC/C,SAAS,EAAa;IACtB,QAAQ,EAAa;IACtB,GACD;KAEN,CAAC,GAAa,EAAU,CACzB;EAaA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotifications.d.ts","sourceRoot":"","sources":["../../src/hooks/useNotifications.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAmBjE,UAAU,uBAAuB;IAC/B,UAAU,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACzC,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACxC;AAoMD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,uBAA4B;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"useNotifications.d.ts","sourceRoot":"","sources":["../../src/hooks/useNotifications.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAmBjE,UAAU,uBAAuB;IAC/B,UAAU,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACzC,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACxC;AAoMD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,uBAA4B;;;;;;;;;;iCA2H3C,MAAM;;0CAsCN,MAAM;mCAqBL,MAAM,EAAE;4CAoBT,MAAM;mCAoBN,MAAM,aAAa,MAAM;;;;;;EA+InD"}
|