@burdenoff/microfe-notification 2026.1029.2 → 2026.1109.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.
Files changed (218) hide show
  1. package/dist/AdminNotificationRoot.d.ts +33 -0
  2. package/dist/AdminNotificationRoot.js +9 -6
  3. package/dist/AdminNotificationRoot.js.map +1 -1
  4. package/dist/AdminNotificationRoutes.d.ts +1 -0
  5. package/dist/AdminNotificationRoutes.js +22 -23
  6. package/dist/AdminNotificationRoutes.js.map +1 -1
  7. package/dist/NotificationRoot.d.ts +29 -0
  8. package/dist/NotificationRoot.js +9 -6
  9. package/dist/NotificationRoot.js.map +1 -1
  10. package/dist/NotificationRoutes.d.ts +18 -0
  11. package/dist/NotificationRoutes.js +1 -2
  12. package/dist/NotificationRoutes.js.map +1 -1
  13. package/dist/UserNotificationRoot.d.ts +32 -0
  14. package/dist/UserNotificationRoot.js +9 -6
  15. package/dist/UserNotificationRoot.js.map +1 -1
  16. package/dist/UserNotificationRoutes.d.ts +16 -0
  17. package/dist/UserNotificationRoutes.js +9 -10
  18. package/dist/UserNotificationRoutes.js.map +1 -1
  19. package/dist/components/FeatureDisabledPage.d.ts +6 -0
  20. package/dist/components/FeatureDisabledPage.js +1 -2
  21. package/dist/components/FeatureDisabledPage.js.map +1 -1
  22. package/dist/components/NotificationBell.d.ts +13 -0
  23. package/dist/components/NotificationBell.js +6 -7
  24. package/dist/components/NotificationBell.js.map +1 -1
  25. package/dist/components/NotificationCard.d.ts +18 -0
  26. package/dist/components/NotificationCard.js +10 -11
  27. package/dist/components/NotificationCard.js.map +1 -1
  28. package/dist/components/NotificationPanel.d.ts +10 -0
  29. package/dist/components/NotificationPanel.js +5 -6
  30. package/dist/components/NotificationPanel.js.map +1 -1
  31. package/dist/components/RecipientSelector.d.ts +32 -0
  32. package/dist/components/RecipientSelector.js +2 -3
  33. package/dist/components/RecipientSelector.js.map +1 -1
  34. package/dist/components/TemplatePreview.d.ts +21 -0
  35. package/dist/components/TemplatePreview.js +3 -4
  36. package/dist/components/TemplatePreview.js.map +1 -1
  37. package/dist/components/VariableInserter.d.ts +11 -0
  38. package/dist/components/index.d.ts +3 -0
  39. package/dist/components/index.js +4 -3
  40. package/dist/constants/permissions.d.ts +23 -0
  41. package/dist/constants/permissions.js +1 -2
  42. package/dist/constants/permissions.js.map +1 -1
  43. package/dist/dev/main.d.ts +0 -0
  44. package/dist/generated/global-operations.d.ts +2119 -0
  45. package/dist/generated/global-operations.js +80 -69
  46. package/dist/generated/global-operations.js.map +1 -1
  47. package/dist/generated/global-types.d.ts +23507 -0
  48. package/dist/generated/wspace-operations.d.ts +4 -0
  49. package/dist/generated/wspace-types.d.ts +57831 -0
  50. package/dist/graphql/global-client.d.ts +32 -0
  51. package/dist/graphql/global-client.js +23 -30
  52. package/dist/graphql/global-client.js.map +1 -1
  53. package/dist/hooks/index.d.ts +7 -0
  54. package/dist/hooks/index.js +7 -6
  55. package/dist/hooks/useNotificationAdmin.d.ts +46 -0
  56. package/dist/hooks/useNotificationAdmin.js +18 -17
  57. package/dist/hooks/useNotificationAdmin.js.map +1 -1
  58. package/dist/hooks/useNotificationAnalytics.d.ts +65 -0
  59. package/dist/hooks/useNotificationAnalytics.js +1 -2
  60. package/dist/hooks/useNotificationAnalytics.js.map +1 -1
  61. package/dist/hooks/useNotificationPreferences.d.ts +10 -0
  62. package/dist/hooks/useNotificationPreferences.js +7 -7
  63. package/dist/hooks/useNotificationPreferences.js.map +1 -1
  64. package/dist/hooks/useNotificationTemplates.d.ts +131 -0
  65. package/dist/hooks/useNotificationTemplates.js +1 -2
  66. package/dist/hooks/useNotificationTemplates.js.map +1 -1
  67. package/dist/hooks/useNotificationTopics.d.ts +35 -0
  68. package/dist/hooks/useNotificationTopics.js +22 -22
  69. package/dist/hooks/useNotificationTopics.js.map +1 -1
  70. package/dist/hooks/useNotifications.d.ts +39 -0
  71. package/dist/hooks/useNotifications.js +6 -4
  72. package/dist/hooks/useNotifications.js.map +1 -1
  73. package/dist/hooks/useSendNotification.d.ts +158 -0
  74. package/dist/hooks/useSendNotification.js +12 -10
  75. package/dist/hooks/useSendNotification.js.map +1 -1
  76. package/dist/hooks/useUserSearch.d.ts +26 -0
  77. package/dist/hooks/useUserSearch.js +8 -10
  78. package/dist/hooks/useUserSearch.js.map +1 -1
  79. package/dist/index.d.ts +36 -0
  80. package/dist/index.js +8 -8
  81. package/dist/node_modules/@apollo/client/errors/CombinedGraphQLErrors.js +1 -2
  82. package/dist/node_modules/@apollo/client/errors/CombinedGraphQLErrors.js.map +1 -1
  83. package/dist/node_modules/@apollo/client/errors/utils.js +1 -2
  84. package/dist/node_modules/@apollo/client/errors/utils.js.map +1 -1
  85. package/dist/node_modules/@apollo/client/link/core/ApolloLink.js +7 -8
  86. package/dist/node_modules/@apollo/client/link/core/ApolloLink.js.map +1 -1
  87. package/dist/node_modules/@apollo/client/link/subscriptions/index.js +9 -10
  88. package/dist/node_modules/@apollo/client/link/subscriptions/index.js.map +1 -1
  89. package/dist/node_modules/@apollo/client/link/utils/createOperation.js +5 -6
  90. package/dist/node_modules/@apollo/client/link/utils/createOperation.js.map +1 -1
  91. package/dist/node_modules/@apollo/client/utilities/caching/sizes.js +0 -1
  92. package/dist/node_modules/@apollo/client/utilities/caching/sizes.js.map +1 -1
  93. package/dist/node_modules/@apollo/client/utilities/graphql/print.js +4 -5
  94. package/dist/node_modules/@apollo/client/utilities/graphql/print.js.map +1 -1
  95. package/dist/node_modules/@apollo/client/utilities/internal/caches.js +1 -2
  96. package/dist/node_modules/@apollo/client/utilities/internal/caches.js.map +1 -1
  97. package/dist/node_modules/@apollo/client/utilities/internal/checkDocument.js +1 -2
  98. package/dist/node_modules/@apollo/client/utilities/internal/checkDocument.js.map +1 -1
  99. package/dist/node_modules/@apollo/client/utilities/internal/getMainDefinition.js +2 -3
  100. package/dist/node_modules/@apollo/client/utilities/internal/getMainDefinition.js.map +1 -1
  101. package/dist/node_modules/@apollo/client/utilities/internal/getMemoryInternals.js +1 -2
  102. package/dist/node_modules/@apollo/client/utilities/internal/getMemoryInternals.js.map +1 -1
  103. package/dist/node_modules/@apollo/client/utilities/internal/getOperationDefinition.js +1 -2
  104. package/dist/node_modules/@apollo/client/utilities/internal/getOperationDefinition.js.map +1 -1
  105. package/dist/node_modules/@apollo/client/utilities/internal/getOperationName.js +1 -2
  106. package/dist/node_modules/@apollo/client/utilities/internal/getOperationName.js.map +1 -1
  107. package/dist/node_modules/@apollo/client/utilities/internal/globals/global.js +1 -2
  108. package/dist/node_modules/@apollo/client/utilities/internal/globals/global.js.map +1 -1
  109. package/dist/node_modules/@apollo/client/utilities/internal/globals/maybe.js +1 -2
  110. package/dist/node_modules/@apollo/client/utilities/internal/globals/maybe.js.map +1 -1
  111. package/dist/node_modules/@apollo/client/utilities/internal/isNonNullObject.js +1 -2
  112. package/dist/node_modules/@apollo/client/utilities/internal/isNonNullObject.js.map +1 -1
  113. package/dist/node_modules/@apollo/client/utilities/internal/makeUniqueId.js +1 -2
  114. package/dist/node_modules/@apollo/client/utilities/internal/makeUniqueId.js.map +1 -1
  115. package/dist/node_modules/@apollo/client/utilities/internal/memoize.js +1 -2
  116. package/dist/node_modules/@apollo/client/utilities/internal/memoize.js.map +1 -1
  117. package/dist/node_modules/@apollo/client/utilities/internal/stringifyForDisplay.js +1 -2
  118. package/dist/node_modules/@apollo/client/utilities/internal/stringifyForDisplay.js.map +1 -1
  119. package/dist/node_modules/@apollo/client/utilities/invariant/index.js +2 -3
  120. package/dist/node_modules/@apollo/client/utilities/invariant/index.js.map +1 -1
  121. package/dist/node_modules/@apollo/client/version.js +2 -3
  122. package/dist/node_modules/@apollo/client/version.js.map +1 -1
  123. package/dist/node_modules/@wry/caches/lib/weak.js +1 -2
  124. package/dist/node_modules/@wry/caches/lib/weak.js.map +1 -1
  125. package/dist/node_modules/@wry/trie/lib/index.js +2 -3
  126. package/dist/node_modules/@wry/trie/lib/index.js.map +1 -1
  127. package/dist/node_modules/graphql-ws/dist/client.js +76 -69
  128. package/dist/node_modules/graphql-ws/dist/client.js.map +1 -1
  129. package/dist/node_modules/graphql-ws/dist/common-CGW11Fyb.js +2 -3
  130. package/dist/node_modules/graphql-ws/dist/common-CGW11Fyb.js.map +1 -1
  131. package/dist/node_modules/rxjs/dist/esm5/internal/NotificationFactories.js +2 -3
  132. package/dist/node_modules/rxjs/dist/esm5/internal/NotificationFactories.js.map +1 -1
  133. package/dist/node_modules/rxjs/dist/esm5/internal/Observable.js +41 -42
  134. package/dist/node_modules/rxjs/dist/esm5/internal/Observable.js.map +1 -1
  135. package/dist/node_modules/rxjs/dist/esm5/internal/Subscriber.js +14 -15
  136. package/dist/node_modules/rxjs/dist/esm5/internal/Subscriber.js.map +1 -1
  137. package/dist/node_modules/rxjs/dist/esm5/internal/Subscription.js +21 -18
  138. package/dist/node_modules/rxjs/dist/esm5/internal/Subscription.js.map +1 -1
  139. package/dist/node_modules/rxjs/dist/esm5/internal/config.js +1 -2
  140. package/dist/node_modules/rxjs/dist/esm5/internal/config.js.map +1 -1
  141. package/dist/node_modules/rxjs/dist/esm5/internal/observable/empty.js +1 -2
  142. package/dist/node_modules/rxjs/dist/esm5/internal/observable/empty.js.map +1 -1
  143. package/dist/node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js +2 -3
  144. package/dist/node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js.map +1 -1
  145. package/dist/node_modules/rxjs/dist/esm5/internal/symbol/observable.js +1 -2
  146. package/dist/node_modules/rxjs/dist/esm5/internal/symbol/observable.js.map +1 -1
  147. package/dist/node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js +1 -2
  148. package/dist/node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js.map +1 -1
  149. package/dist/node_modules/rxjs/dist/esm5/internal/util/arrRemove.js +1 -2
  150. package/dist/node_modules/rxjs/dist/esm5/internal/util/arrRemove.js.map +1 -1
  151. package/dist/node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js +1 -2
  152. package/dist/node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js.map +1 -1
  153. package/dist/node_modules/rxjs/dist/esm5/internal/util/errorContext.js +1 -2
  154. package/dist/node_modules/rxjs/dist/esm5/internal/util/errorContext.js.map +1 -1
  155. package/dist/node_modules/rxjs/dist/esm5/internal/util/identity.js +1 -2
  156. package/dist/node_modules/rxjs/dist/esm5/internal/util/identity.js.map +1 -1
  157. package/dist/node_modules/rxjs/dist/esm5/internal/util/isFunction.js +1 -2
  158. package/dist/node_modules/rxjs/dist/esm5/internal/util/isFunction.js.map +1 -1
  159. package/dist/node_modules/rxjs/dist/esm5/internal/util/noop.js +1 -2
  160. package/dist/node_modules/rxjs/dist/esm5/internal/util/noop.js.map +1 -1
  161. package/dist/node_modules/rxjs/dist/esm5/internal/util/pipe.js +1 -2
  162. package/dist/node_modules/rxjs/dist/esm5/internal/util/pipe.js.map +1 -1
  163. package/dist/node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js +1 -2
  164. package/dist/node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js.map +1 -1
  165. package/dist/node_modules/{rxjs/node_modules/tslib → tslib}/tslib.es6.js +1 -2
  166. package/dist/node_modules/tslib/tslib.es6.js.map +1 -0
  167. package/dist/pages/CreateNotificationPage.d.ts +5 -0
  168. package/dist/pages/CreateNotificationPage.js +18 -19
  169. package/dist/pages/CreateNotificationPage.js.map +1 -1
  170. package/dist/pages/NotificationCenterPage.d.ts +6 -0
  171. package/dist/pages/NotificationCenterPage.js +13 -14
  172. package/dist/pages/NotificationCenterPage.js.map +1 -1
  173. package/dist/pages/NotificationHistoryAdminPage.d.ts +2 -0
  174. package/dist/pages/NotificationHistoryAdminPage.js +7 -8
  175. package/dist/pages/NotificationHistoryAdminPage.js.map +1 -1
  176. package/dist/pages/NotificationHistoryPage.d.ts +2 -0
  177. package/dist/pages/NotificationHistoryPage.js +13 -14
  178. package/dist/pages/NotificationHistoryPage.js.map +1 -1
  179. package/dist/pages/NotificationLandingPage.d.ts +10 -0
  180. package/dist/pages/NotificationLandingPage.js +5 -6
  181. package/dist/pages/NotificationLandingPage.js.map +1 -1
  182. package/dist/pages/NotificationPreferencesPage.d.ts +1 -0
  183. package/dist/pages/NotificationPreferencesPage.js +14 -15
  184. package/dist/pages/NotificationPreferencesPage.js.map +1 -1
  185. package/dist/pages/NotificationTemplatesPage.d.ts +7 -0
  186. package/dist/pages/NotificationTemplatesPage.js +25 -23
  187. package/dist/pages/NotificationTemplatesPage.js.map +1 -1
  188. package/dist/pages/NotificationTopicsPage.d.ts +1 -0
  189. package/dist/pages/NotificationTopicsPage.js +6 -7
  190. package/dist/pages/NotificationTopicsPage.js.map +1 -1
  191. package/dist/pages/TemplateEditorPage.d.ts +12 -0
  192. package/dist/pages/TemplateEditorPage.js +294 -285
  193. package/dist/pages/TemplateEditorPage.js.map +1 -1
  194. package/dist/providers/NotificationProvider.d.ts +11 -0
  195. package/dist/providers/NotificationProvider.js +1 -2
  196. package/dist/providers/NotificationProvider.js.map +1 -1
  197. package/dist/shared/hooks/useTr.d.ts +13 -0
  198. package/dist/shared/hooks/useTr.js +1 -2
  199. package/dist/shared/hooks/useTr.js.map +1 -1
  200. package/dist/store/notificationStore.d.ts +30 -0
  201. package/dist/store/notificationStore.js +1 -2
  202. package/dist/store/notificationStore.js.map +1 -1
  203. package/dist/test/happydom.d.ts +1 -0
  204. package/dist/translations/en.d.ts +468 -0
  205. package/dist/types/index.d.ts +249 -0
  206. package/dist/utils/inAppNavigation.d.ts +37 -0
  207. package/dist/utils/inAppNavigation.js +2 -3
  208. package/dist/utils/inAppNavigation.js.map +1 -1
  209. package/dist/utils/index.d.ts +68 -0
  210. package/dist/utils/index.js +1 -2
  211. package/dist/utils/index.js.map +1 -1
  212. package/dist/utils/nativeBridge.d.ts +2 -0
  213. package/dist/utils/nativeBridge.js +1 -2
  214. package/dist/utils/notificationHistoryExport.d.ts +12 -0
  215. package/dist/utils/notificationHistoryExport.js +1 -2
  216. package/dist/utils/notificationHistoryExport.js.map +1 -1
  217. package/package.json +66 -48
  218. package/dist/node_modules/rxjs/node_modules/tslib/tslib.es6.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"useNotifications.js","names":[],"sources":["../../src/hooks/useNotifications.ts"],"sourcesContent":["import { useState, useCallback, useEffect, useMemo } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient, USER_NOTIFICATION_CONTEXT } from '../graphql/global-client';\nimport { useNotificationStore } from '../store/notificationStore';\nimport type { Notification, NotificationFilter } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationsQuery,\n GetMyUnreadNotificationCountQuery,\n NotificationFieldsFragment,\n NotificationReceivedSubscription,\n UnreadCountUpdatedSubscription,\n} from '../generated/global-operations';\n\n// ---------------------------------------------------------------------------\n// GraphQL Operations — using generated Document nodes from global-operations\n// ---------------------------------------------------------------------------\n\n/**\n * Backend Notification item type derived from the generated query\n */\ntype BackendNotification = NotificationFieldsFragment;\n\ninterface UseNotificationsOptions {\n baseFilter?: Partial<NotificationFilter>;\n unreadFilter?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Mapping helpers — backend → MFE types\n// ---------------------------------------------------------------------------\n\nfunction mapBackendToMfeNotification(n: BackendNotification): Notification {\n return {\n id: n.id,\n type: mapNotificationType(n.type),\n priority: mapPriority(n.priority),\n title: n.title,\n body: n.message,\n actionUrl: n.redirectUrl ?? undefined,\n actions: (n.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 appName: n.appName ?? undefined,\n archivedAt: n.archivedAt ?? undefined,\n channel: n.channel as Notification['channel'],\n clickedAt: n.clickedAt ?? undefined,\n deliveredAt: n.deliveredAt ?? undefined,\n deliveryStatus: n.deliveryStatus ?? undefined,\n htmlBody: n.htmlMessage ?? undefined,\n media: (n.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 openedAt: n.openedAt ?? undefined,\n recipientEmail: n.recipientEmail ?? undefined,\n recipientPhone: n.recipientPhone ?? undefined,\n scheduledFor: n.scheduledFor ?? undefined,\n scheduledNotification: n.scheduledNotification\n ? {\n id: n.scheduledNotification.id,\n scheduledFor: n.scheduledNotification.scheduledFor,\n status: n.scheduledNotification.status,\n timezone: n.scheduledNotification.timezone ?? undefined,\n }\n : undefined,\n sentAt: n.sentAt ?? undefined,\n status: mapStatus(n.status),\n readAt: n.readAt ?? undefined,\n createdAt: n.createdAt,\n channels: [\n {\n id: n.id,\n channel: n.channel as Notification['channel'],\n status: mapStatus(n.status),\n sentAt: n.sentAt ?? undefined,\n deliveredAt: n.deliveredAt ?? undefined,\n failedAt: n.failedAt ?? undefined,\n errorCode: n.errorCode ?? undefined,\n errorMessage: n.errorMessage ?? undefined,\n },\n ],\n metadata: n.metadata ?? undefined,\n topic: n.topic\n ? {\n id: n.topic.id,\n name: n.topic.name,\n slug: n.topic.slug,\n type: mapNotificationType(n.topic.type),\n }\n : undefined,\n topicId: n.topicId ?? undefined,\n };\n}\n\nfunction mapNotificationType(t: string) {\n const map: Record<string, Notification['type']> = {\n SYSTEM: 'SYSTEM',\n TRANSACTIONAL: 'TRANSACTIONAL',\n MARKETING: 'MARKETING',\n ALERT: 'ALERT',\n };\n return map[t] || 'SYSTEM';\n}\n\nfunction mapPriority(p: string) {\n const map: Record<string, Notification['priority']> = {\n LOW: 'LOW',\n MEDIUM: 'NORMAL',\n HIGH: 'HIGH',\n URGENT: 'URGENT',\n };\n return map[p] || 'NORMAL';\n}\n\nfunction mapStatus(s: string) {\n const map: Record<string, Notification['status']> = {\n DRAFT: 'PENDING',\n PENDING: 'PENDING',\n SCHEDULED: 'PENDING',\n TRIGGERED: 'SENT',\n SENT: 'SENT',\n DELIVERED: 'DELIVERED',\n READ: 'DELIVERED',\n FAILED: 'FAILED',\n CANCELLED: 'ARCHIVED',\n EXPIRED: 'ARCHIVED',\n };\n return map[s] || 'PENDING';\n}\n\n// ---------------------------------------------------------------------------\n// Build the backend filter from the MFE NotificationFilter shape\n// ---------------------------------------------------------------------------\n\nfunction buildBackendFilter(filter: NotificationFilter) {\n const backend: Record<string, unknown> = {};\n\n // Type filter — map MFE type names to backend enum\n if (filter.type !== 'ALL') {\n const typeMap: Record<string, string> = {\n SYSTEM: 'SYSTEM',\n ACTIVITY: 'TRANSACTIONAL',\n BILLING: 'TRANSACTIONAL',\n SECURITY: 'ALERT',\n SOCIAL: 'MARKETING',\n REMINDER: 'SYSTEM',\n };\n backend.type = typeMap[filter.type] || filter.type;\n }\n\n // Priority filter\n if (filter.priority !== 'ALL') {\n const prioMap: Record<string, string> = {\n LOW: 'LOW',\n NORMAL: 'MEDIUM',\n HIGH: 'HIGH',\n URGENT: 'URGENT',\n };\n backend.priority = prioMap[filter.priority] || filter.priority;\n }\n\n // Read/unread filter — coerce null to undefined\n if (filter.isRead !== null && filter.isRead !== undefined) {\n backend.isRead = filter.isRead;\n }\n\n if (filter.topicId) {\n backend.topicId = filter.topicId;\n }\n\n if (filter.channel && filter.channel !== 'ALL') {\n backend.channel = filter.channel;\n }\n\n if (filter.archived !== null && filter.archived !== undefined) {\n backend.archived = filter.archived;\n }\n\n if (filter.search) {\n backend.search = filter.search;\n }\n\n // Date range\n if (filter.dateRange.start) {\n backend.startDate = filter.dateRange.start.toISOString();\n }\n if (filter.dateRange.end) {\n backend.endDate = filter.dateRange.end.toISOString();\n }\n\n return Object.keys(backend).length > 0 ? backend : undefined;\n}\n\nfunction mergeNotificationFilter(\n filter: NotificationFilter,\n baseFilter?: Partial<NotificationFilter>\n): NotificationFilter {\n if (!baseFilter) return filter;\n\n return {\n ...filter,\n ...baseFilter,\n dateRange: {\n ...filter.dateRange,\n ...(baseFilter.dateRange || {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Hook to manage notifications with real GraphQL backend integration.\n *\n * Uses the global Apollo client to query the notification service via the\n * public gateway (https://gw-global.local.burdenoff.com/global/graphql).\n *\n * @example\n * ```tsx\n * const { notifications, unreadCount, markAsRead } = useNotifications();\n * ```\n */\nexport function useNotifications(options: UseNotificationsOptions = {}) {\n const { authToken, apiGatewayUrl, currentUser, eventBus } = useNotification();\n const {\n notificationFilter,\n updateNotificationFilter,\n resetNotificationFilter,\n unreadCount,\n setUnreadCount: setStoreUnreadCount,\n setIsLoadingNotifications,\n } = useNotificationStore();\n\n const [notifications, setNotifications] = useState<Notification[]>([]);\n const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);\n const [isLoading, setIsLoading] = 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\n const LIMIT = 50;\n const effectiveFilter = useMemo(\n () => mergeNotificationFilter(notificationFilter, options.baseFilter),\n [notificationFilter, options.baseFilter]\n );\n const [debouncedFilter, setDebouncedFilter] = useState(effectiveFilter);\n\n useEffect(() => {\n const timeout = window.setTimeout(() => setDebouncedFilter(effectiveFilter), 250);\n return () => window.clearTimeout(timeout);\n }, [effectiveFilter]);\n\n // Client accessor — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // ---- Fetch notifications ------------------------------------------------\n\n const fetchNotifications = useCallback(async () => {\n setIsLoading(true);\n setIsLoadingNotifications(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: buildBackendFilter(debouncedFilter),\n limit: LIMIT,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notifications) {\n const mapped = result.data.notifications.items.map(mapBackendToMfeNotification);\n setNotifications(mapped);\n setTotal(result.data.notifications.total);\n setHasMore(result.data.notifications.hasMore);\n setOffset(LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch notifications';\n console.error('[useNotifications] Failed to fetch notifications:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n setIsLoadingNotifications(false);\n }\n }, [debouncedFilter, getClient, setIsLoadingNotifications]);\n\n // ---- Fetch unread count -------------------------------------------------\n\n const fetchUnreadCount = useCallback(async () => {\n try {\n const client = getClient();\n const result = await client.query<GetMyUnreadNotificationCountQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: NotificationOps.GetMyUnreadNotificationCountDocument,\n variables: { filter: options.unreadFilter || { channel: 'IN_APP' } },\n fetchPolicy: 'network-only',\n });\n if (result.data) {\n setStoreUnreadCount(result.data.myUnreadNotificationCount);\n }\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to fetch unread count:', err);\n }\n }, [getClient, options.unreadFilter, setStoreUnreadCount]);\n\n // ---- Load more ----------------------------------------------------------\n\n const loadMore = useCallback(async () => {\n if (!hasMore) return;\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: buildBackendFilter(debouncedFilter),\n limit: LIMIT,\n offset,\n },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notifications) {\n const more = result.data.notifications.items.map(mapBackendToMfeNotification);\n setNotifications((prev) => [...prev, ...more]);\n setHasMore(result.data.notifications.hasMore);\n setOffset((prev) => prev + LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to load more notifications';\n console.error('[useNotifications] Failed to load more:', err);\n setError(message);\n }\n }, [debouncedFilter, getClient, hasMore, offset]);\n\n // ---- Mutations ----------------------------------------------------------\n\n const handleMarkAsRead = useCallback(\n async (notificationId: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.MarkNotificationAsReadDocument,\n variables: { id: notificationId },\n });\n // Optimistic: update local state\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === notificationId ? { ...n, readAt: new Date().toISOString() } : n\n )\n );\n setStoreUnreadCount(Math.max(0, unreadCount - 1));\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to mark as read:', err);\n setError('Failed to mark notification as read');\n }\n },\n [getClient, setStoreUnreadCount, unreadCount]\n );\n\n const handleMarkAllAsRead = useCallback(async () => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.MarkAllMyNotificationsAsReadDocument,\n });\n // Optimistic: update all local\n setNotifications((prev) =>\n prev.map((n) => ({ ...n, readAt: n.readAt || new Date().toISOString() }))\n );\n setStoreUnreadCount(0);\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to mark all as read:', err);\n setError('Failed to mark all notifications as read');\n }\n }, [getClient, setStoreUnreadCount]);\n\n const handleArchive = useCallback(\n async (notificationId: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.ArchiveNotificationDocument,\n variables: { id: notificationId },\n });\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === notificationId ? { ...n, archivedAt: new Date().toISOString() } : n\n )\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to archive notification:', err);\n setError('Failed to archive notification');\n }\n },\n [getClient]\n );\n\n const handleBulkArchive = useCallback(\n async (notificationIds: string[]) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.ArchiveNotificationsDocument,\n variables: { notificationIds },\n });\n const idsSet = new Set(notificationIds);\n setNotifications((prev) =>\n prev.map((n) => (idsSet.has(n.id) ? { ...n, archivedAt: new Date().toISOString() } : n))\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to bulk archive:', err);\n setError('Failed to archive notifications');\n }\n },\n [getClient]\n );\n\n const handleUnarchive = useCallback(\n async (notificationId: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.UnarchiveNotificationDocument,\n variables: { id: notificationId },\n });\n\n setNotifications((prev) =>\n prev.map((n) => (n.id === notificationId ? { ...n, archivedAt: undefined } : n))\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to unarchive notification:', err);\n setError('Failed to restore notification');\n }\n },\n [getClient]\n );\n\n const handleRecordAction = useCallback(\n async (notificationId: string, actionId?: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.RecordNotificationActionDocument,\n variables: { input: { notificationId, actionId } },\n });\n\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === notificationId\n ? {\n ...n,\n clickedAt: new Date().toISOString(),\n readAt: n.readAt || new Date().toISOString(),\n }\n : n\n )\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to record notification action:', err);\n setError('Failed to record notification action');\n }\n },\n [getClient]\n );\n\n // ---- Initial fetch on mount + when filter changes -----------------------\n\n useEffect(() => {\n fetchNotifications();\n }, [fetchNotifications]);\n\n useEffect(() => {\n fetchUnreadCount();\n }, [fetchUnreadCount]);\n\n // ---- Live notification subscriptions ------------------------------------\n\n useEffect(() => {\n if (!currentUser?.id) return undefined;\n\n const client = getClient();\n const notificationSubscription = client\n .subscribe<NotificationReceivedSubscription>({\n query: NotificationOps.NotificationReceivedDocument,\n variables: { userId: currentUser.id },\n })\n .subscribe({\n next: (result) => {\n const notification = result.data?.notificationReceived;\n if (!notification) return;\n const mapped = mapBackendToMfeNotification(notification);\n setNotifications((prev) => [mapped, ...prev.filter((item) => item.id !== mapped.id)]);\n eventBus?.emit('notification:received', { notification: mapped });\n },\n error: (err) => {\n console.error('[useNotifications] Notification subscription failed:', err);\n },\n });\n\n const unreadSubscription = client\n .subscribe<UnreadCountUpdatedSubscription>({\n query: NotificationOps.UnreadCountUpdatedDocument,\n variables: { userId: currentUser.id },\n })\n .subscribe({\n next: (result) => {\n const nextCount = result.data?.unreadCountUpdated;\n if (typeof nextCount === 'number') {\n setStoreUnreadCount(nextCount);\n eventBus?.emit('notification:unread-count-updated', { unreadCount: nextCount });\n }\n },\n error: (err) => {\n console.error('[useNotifications] Unread count subscription failed:', err);\n },\n });\n\n return () => {\n notificationSubscription.unsubscribe();\n unreadSubscription.unsubscribe();\n };\n }, [currentUser?.id, eventBus, getClient, setStoreUnreadCount]);\n\n useEffect(() => {\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'visible') {\n fetchNotifications();\n fetchUnreadCount();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n return () => document.removeEventListener('visibilitychange', handleVisibilityChange);\n }, [fetchNotifications, fetchUnreadCount]);\n\n const visibleNotifications = useMemo(\n () =>\n notifications.filter((notification) => {\n if (notification.deliveryStatus === 'UNSUBSCRIBED') {\n return false;\n }\n\n if (notification.status === 'ARCHIVED' && !notification.archivedAt) {\n return false;\n }\n\n if (effectiveFilter.archived === true) {\n return Boolean(notification.archivedAt);\n }\n\n if (effectiveFilter.archived === false) {\n return !notification.archivedAt;\n }\n\n return true;\n }),\n [effectiveFilter.archived, notifications]\n );\n\n return {\n notifications: visibleNotifications,\n allNotifications: notifications,\n unreadCount,\n selectedNotification,\n notificationFilter: effectiveFilter,\n isLoading,\n error,\n hasMore,\n total,\n markAsRead: handleMarkAsRead,\n markAllAsRead: handleMarkAllAsRead,\n archiveNotification: handleArchive,\n bulkArchive: handleBulkArchive,\n unarchiveNotification: handleUnarchive,\n recordAction: handleRecordAction,\n setSelectedNotification,\n updateFilter: updateNotificationFilter,\n resetFilter: resetNotificationFilter,\n refetch: fetchNotifications,\n loadMore,\n };\n}\n"],"mappings":";;;;;;AAgCA,SAAS,EAA4B,GAAsC;AACzE,QAAO;EACL,IA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cAC/B,GAAoB,EACpB,GAAkB;;AAKtB,SADA,SAAS,iBAAiB,oBAAoB,EAAuB,QACxD,SAAS,oBAAoB,oBAAoB,EAAuB;IACpF,CAAC,GAAoB,EAAiB,CAAC,EA0BnC;EACL,eAzB2B,QAEzB,EAAc,QAAQ,MAChB,EAAa,mBAAmB,kBAIhC,EAAa,WAAW,cAAc,CAAC,EAAa,aAC/C,KAGL,EAAgB,aAAa,KACxB,EAAQ,EAAa,aAG1B,EAAgB,aAAa,KACxB,CAAC,EAAa,aAGhB,GACP,EACJ,CAAC,EAAgB,UAAU,EAAc,CAC1C;EAIC,kBAAkB;EAClB;EACA;EACA,oBAAoB;EACpB;EACA;EACA;EACA;EACA,YAAY;EACZ,eAAe;EACf,qBAAqB;EACrB,aAAa;EACb,uBAAuB;EACvB,cAAc;EACd;EACA,cAAc;EACd,aAAa;EACb,SAAS;EACT;EACD"}
1
+ {"version":3,"file":"useNotifications.js","names":["NotificationOps.GetNotificationsDocument","NotificationOps.GetMyUnreadNotificationCountDocument","NotificationOps.MarkNotificationAsReadDocument","NotificationOps.MarkAllMyNotificationsAsReadDocument","NotificationOps.ArchiveNotificationDocument","NotificationOps.ArchiveNotificationsDocument","NotificationOps.UnarchiveNotificationDocument","NotificationOps.RecordNotificationActionDocument","NotificationOps.NotificationReceivedDocument","NotificationOps.UnreadCountUpdatedDocument","mapBackendToMfeNotification","n","mapNotificationType","mapPriority","action","item","mapStatus","t","p","s","buildBackendFilter","backend","filter","mergeNotificationFilter","baseFilter","useNotifications","useNotification","setStoreUnreadCount","useNotificationStore","notifications","setNotifications","useState","selectedNotification","setSelectedNotification","isLoading","setIsLoading","error","setError","hasMore","setHasMore","total","setTotal","offset","setOffset","effectiveFilter","useMemo","notificationFilter","options","debouncedFilter","setDebouncedFilter","timeout","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","fetchNotifications","setIsLoadingNotifications","result","USER_NOTIFICATION_CONTEXT","GetNotificationsDocument","mapped","err","message","fetchUnreadCount","GetMyUnreadNotificationCountDocument","loadMore","more","prev","handleMarkAsRead","MarkNotificationAsReadDocument","notificationId","unreadCount","handleMarkAllAsRead","MarkAllMyNotificationsAsReadDocument","handleArchive","ArchiveNotificationDocument","handleBulkArchive","ArchiveNotificationsDocument","idsSet","notificationIds","handleUnarchive","UnarchiveNotificationDocument","handleRecordAction","RecordNotificationActionDocument","useEffect","currentUser","client","notificationSubscription","NotificationReceivedDocument","notification","eventBus","unreadSubscription","UnreadCountUpdatedDocument","nextCount","handleVisibilityChange","updateNotificationFilter","resetNotificationFilter"],"sources":["../../src/hooks/useNotifications.ts"],"sourcesContent":["import { useState, useCallback, useEffect, useMemo } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient, USER_NOTIFICATION_CONTEXT } from '../graphql/global-client';\nimport { useNotificationStore } from '../store/notificationStore';\nimport type { Notification, NotificationFilter } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationsQuery,\n GetMyUnreadNotificationCountQuery,\n NotificationFieldsFragment,\n NotificationReceivedSubscription,\n UnreadCountUpdatedSubscription,\n} from '../generated/global-operations';\n\n// ---------------------------------------------------------------------------\n// GraphQL Operations — using generated Document nodes from global-operations\n// ---------------------------------------------------------------------------\n\n/**\n * Backend Notification item type derived from the generated query\n */\ntype BackendNotification = NotificationFieldsFragment;\n\ninterface UseNotificationsOptions {\n baseFilter?: Partial<NotificationFilter>;\n unreadFilter?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Mapping helpers — backend → MFE types\n// ---------------------------------------------------------------------------\n\nfunction mapBackendToMfeNotification(n: BackendNotification): Notification {\n return {\n id: n.id,\n type: mapNotificationType(n.type),\n priority: mapPriority(n.priority),\n title: n.title,\n body: n.message,\n actionUrl: n.redirectUrl ?? undefined,\n actions: (n.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 appName: n.appName ?? undefined,\n archivedAt: n.archivedAt ?? undefined,\n channel: n.channel as Notification['channel'],\n clickedAt: n.clickedAt ?? undefined,\n deliveredAt: n.deliveredAt ?? undefined,\n deliveryStatus: n.deliveryStatus ?? undefined,\n htmlBody: n.htmlMessage ?? undefined,\n media: (n.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 openedAt: n.openedAt ?? undefined,\n recipientEmail: n.recipientEmail ?? undefined,\n recipientPhone: n.recipientPhone ?? undefined,\n scheduledFor: n.scheduledFor ?? undefined,\n scheduledNotification: n.scheduledNotification\n ? {\n id: n.scheduledNotification.id,\n scheduledFor: n.scheduledNotification.scheduledFor,\n status: n.scheduledNotification.status,\n timezone: n.scheduledNotification.timezone ?? undefined,\n }\n : undefined,\n sentAt: n.sentAt ?? undefined,\n status: mapStatus(n.status),\n readAt: n.readAt ?? undefined,\n createdAt: n.createdAt,\n channels: [\n {\n id: n.id,\n channel: n.channel as Notification['channel'],\n status: mapStatus(n.status),\n sentAt: n.sentAt ?? undefined,\n deliveredAt: n.deliveredAt ?? undefined,\n failedAt: n.failedAt ?? undefined,\n errorCode: n.errorCode ?? undefined,\n errorMessage: n.errorMessage ?? undefined,\n },\n ],\n metadata: n.metadata ?? undefined,\n topic: n.topic\n ? {\n id: n.topic.id,\n name: n.topic.name,\n slug: n.topic.slug,\n type: mapNotificationType(n.topic.type),\n }\n : undefined,\n topicId: n.topicId ?? undefined,\n };\n}\n\nfunction mapNotificationType(t: string) {\n const map: Record<string, Notification['type']> = {\n SYSTEM: 'SYSTEM',\n TRANSACTIONAL: 'TRANSACTIONAL',\n MARKETING: 'MARKETING',\n ALERT: 'ALERT',\n };\n return map[t] || 'SYSTEM';\n}\n\nfunction mapPriority(p: string) {\n const map: Record<string, Notification['priority']> = {\n LOW: 'LOW',\n MEDIUM: 'NORMAL',\n HIGH: 'HIGH',\n URGENT: 'URGENT',\n };\n return map[p] || 'NORMAL';\n}\n\nfunction mapStatus(s: string) {\n const map: Record<string, Notification['status']> = {\n DRAFT: 'PENDING',\n PENDING: 'PENDING',\n SCHEDULED: 'PENDING',\n TRIGGERED: 'SENT',\n SENT: 'SENT',\n DELIVERED: 'DELIVERED',\n READ: 'DELIVERED',\n FAILED: 'FAILED',\n CANCELLED: 'ARCHIVED',\n EXPIRED: 'ARCHIVED',\n };\n return map[s] || 'PENDING';\n}\n\n// ---------------------------------------------------------------------------\n// Build the backend filter from the MFE NotificationFilter shape\n// ---------------------------------------------------------------------------\n\nfunction buildBackendFilter(filter: NotificationFilter) {\n const backend: Record<string, unknown> = {};\n\n // Type filter — map MFE type names to backend enum\n if (filter.type !== 'ALL') {\n const typeMap: Record<string, string> = {\n SYSTEM: 'SYSTEM',\n ACTIVITY: 'TRANSACTIONAL',\n BILLING: 'TRANSACTIONAL',\n SECURITY: 'ALERT',\n SOCIAL: 'MARKETING',\n REMINDER: 'SYSTEM',\n };\n backend.type = typeMap[filter.type] || filter.type;\n }\n\n // Priority filter\n if (filter.priority !== 'ALL') {\n const prioMap: Record<string, string> = {\n LOW: 'LOW',\n NORMAL: 'MEDIUM',\n HIGH: 'HIGH',\n URGENT: 'URGENT',\n };\n backend.priority = prioMap[filter.priority] || filter.priority;\n }\n\n // Read/unread filter — coerce null to undefined\n if (filter.isRead !== null && filter.isRead !== undefined) {\n backend.isRead = filter.isRead;\n }\n\n if (filter.topicId) {\n backend.topicId = filter.topicId;\n }\n\n if (filter.channel && filter.channel !== 'ALL') {\n backend.channel = filter.channel;\n }\n\n if (filter.archived !== null && filter.archived !== undefined) {\n backend.archived = filter.archived;\n }\n\n if (filter.search) {\n backend.search = filter.search;\n }\n\n // Date range\n if (filter.dateRange.start) {\n backend.startDate = filter.dateRange.start.toISOString();\n }\n if (filter.dateRange.end) {\n backend.endDate = filter.dateRange.end.toISOString();\n }\n\n return Object.keys(backend).length > 0 ? backend : undefined;\n}\n\nfunction mergeNotificationFilter(\n filter: NotificationFilter,\n baseFilter?: Partial<NotificationFilter>\n): NotificationFilter {\n if (!baseFilter) return filter;\n\n return {\n ...filter,\n ...baseFilter,\n dateRange: {\n ...filter.dateRange,\n ...(baseFilter.dateRange || {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Hook to manage notifications with real GraphQL backend integration.\n *\n * Uses the global Apollo client to query the notification service via the\n * public gateway (https://gw-global.local.burdenoff.com/global/graphql).\n *\n * @example\n * ```tsx\n * const { notifications, unreadCount, markAsRead } = useNotifications();\n * ```\n */\nexport function useNotifications(options: UseNotificationsOptions = {}) {\n const { authToken, apiGatewayUrl, currentUser, eventBus } = useNotification();\n const {\n notificationFilter,\n updateNotificationFilter,\n resetNotificationFilter,\n unreadCount,\n setUnreadCount: setStoreUnreadCount,\n setIsLoadingNotifications,\n } = useNotificationStore();\n\n const [notifications, setNotifications] = useState<Notification[]>([]);\n const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);\n const [isLoading, setIsLoading] = 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\n const LIMIT = 50;\n const effectiveFilter = useMemo(\n () => mergeNotificationFilter(notificationFilter, options.baseFilter),\n [notificationFilter, options.baseFilter]\n );\n const [debouncedFilter, setDebouncedFilter] = useState(effectiveFilter);\n\n useEffect(() => {\n const timeout = window.setTimeout(() => setDebouncedFilter(effectiveFilter), 250);\n return () => window.clearTimeout(timeout);\n }, [effectiveFilter]);\n\n // Client accessor — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // ---- Fetch notifications ------------------------------------------------\n\n const fetchNotifications = useCallback(async () => {\n setIsLoading(true);\n setIsLoadingNotifications(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: buildBackendFilter(debouncedFilter),\n limit: LIMIT,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notifications) {\n const mapped = result.data.notifications.items.map(mapBackendToMfeNotification);\n setNotifications(mapped);\n setTotal(result.data.notifications.total);\n setHasMore(result.data.notifications.hasMore);\n setOffset(LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch notifications';\n console.error('[useNotifications] Failed to fetch notifications:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n setIsLoadingNotifications(false);\n }\n }, [debouncedFilter, getClient, setIsLoadingNotifications]);\n\n // ---- Fetch unread count -------------------------------------------------\n\n const fetchUnreadCount = useCallback(async () => {\n try {\n const client = getClient();\n const result = await client.query<GetMyUnreadNotificationCountQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: NotificationOps.GetMyUnreadNotificationCountDocument,\n variables: { filter: options.unreadFilter || { channel: 'IN_APP' } },\n fetchPolicy: 'network-only',\n });\n if (result.data) {\n setStoreUnreadCount(result.data.myUnreadNotificationCount);\n }\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to fetch unread count:', err);\n }\n }, [getClient, options.unreadFilter, setStoreUnreadCount]);\n\n // ---- Load more ----------------------------------------------------------\n\n const loadMore = useCallback(async () => {\n if (!hasMore) return;\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n context: USER_NOTIFICATION_CONTEXT,\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: buildBackendFilter(debouncedFilter),\n limit: LIMIT,\n offset,\n },\n fetchPolicy: 'network-only',\n });\n\n if (result.data?.notifications) {\n const more = result.data.notifications.items.map(mapBackendToMfeNotification);\n setNotifications((prev) => [...prev, ...more]);\n setHasMore(result.data.notifications.hasMore);\n setOffset((prev) => prev + LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to load more notifications';\n console.error('[useNotifications] Failed to load more:', err);\n setError(message);\n }\n }, [debouncedFilter, getClient, hasMore, offset]);\n\n // ---- Mutations ----------------------------------------------------------\n\n const handleMarkAsRead = useCallback(\n async (notificationId: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.MarkNotificationAsReadDocument,\n variables: { id: notificationId },\n });\n // Optimistic: update local state\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === notificationId ? { ...n, readAt: new Date().toISOString() } : n\n )\n );\n setStoreUnreadCount(Math.max(0, unreadCount - 1));\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to mark as read:', err);\n setError('Failed to mark notification as read');\n }\n },\n [getClient, setStoreUnreadCount, unreadCount]\n );\n\n const handleMarkAllAsRead = useCallback(async () => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.MarkAllMyNotificationsAsReadDocument,\n });\n // Optimistic: update all local\n setNotifications((prev) =>\n prev.map((n) => ({ ...n, readAt: n.readAt || new Date().toISOString() }))\n );\n setStoreUnreadCount(0);\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to mark all as read:', err);\n setError('Failed to mark all notifications as read');\n }\n }, [getClient, setStoreUnreadCount]);\n\n const handleArchive = useCallback(\n async (notificationId: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.ArchiveNotificationDocument,\n variables: { id: notificationId },\n });\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === notificationId ? { ...n, archivedAt: new Date().toISOString() } : n\n )\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to archive notification:', err);\n setError('Failed to archive notification');\n }\n },\n [getClient]\n );\n\n const handleBulkArchive = useCallback(\n async (notificationIds: string[]) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.ArchiveNotificationsDocument,\n variables: { notificationIds },\n });\n const idsSet = new Set(notificationIds);\n setNotifications((prev) =>\n prev.map((n) => (idsSet.has(n.id) ? { ...n, archivedAt: new Date().toISOString() } : n))\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to bulk archive:', err);\n setError('Failed to archive notifications');\n }\n },\n [getClient]\n );\n\n const handleUnarchive = useCallback(\n async (notificationId: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.UnarchiveNotificationDocument,\n variables: { id: notificationId },\n });\n\n setNotifications((prev) =>\n prev.map((n) => (n.id === notificationId ? { ...n, archivedAt: undefined } : n))\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to unarchive notification:', err);\n setError('Failed to restore notification');\n }\n },\n [getClient]\n );\n\n const handleRecordAction = useCallback(\n async (notificationId: string, actionId?: string) => {\n try {\n const client = getClient();\n await client.mutate({\n context: USER_NOTIFICATION_CONTEXT,\n mutation: NotificationOps.RecordNotificationActionDocument,\n variables: { input: { notificationId, actionId } },\n });\n\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === notificationId\n ? {\n ...n,\n clickedAt: new Date().toISOString(),\n readAt: n.readAt || new Date().toISOString(),\n }\n : n\n )\n );\n } catch (err: unknown) {\n console.error('[useNotifications] Failed to record notification action:', err);\n setError('Failed to record notification action');\n }\n },\n [getClient]\n );\n\n // ---- Initial fetch on mount + when filter changes -----------------------\n\n useEffect(() => {\n fetchNotifications();\n }, [fetchNotifications]);\n\n useEffect(() => {\n fetchUnreadCount();\n }, [fetchUnreadCount]);\n\n // ---- Live notification subscriptions ------------------------------------\n\n useEffect(() => {\n if (!currentUser?.id) return undefined;\n\n const client = getClient();\n const notificationSubscription = client\n .subscribe<NotificationReceivedSubscription>({\n query: NotificationOps.NotificationReceivedDocument,\n variables: { userId: currentUser.id },\n })\n .subscribe({\n next: (result) => {\n const notification = result.data?.notificationReceived;\n if (!notification) return;\n const mapped = mapBackendToMfeNotification(notification);\n setNotifications((prev) => [mapped, ...prev.filter((item) => item.id !== mapped.id)]);\n eventBus?.emit('notification:received', { notification: mapped });\n },\n error: (err) => {\n console.error('[useNotifications] Notification subscription failed:', err);\n },\n });\n\n const unreadSubscription = client\n .subscribe<UnreadCountUpdatedSubscription>({\n query: NotificationOps.UnreadCountUpdatedDocument,\n variables: { userId: currentUser.id },\n })\n .subscribe({\n next: (result) => {\n const nextCount = result.data?.unreadCountUpdated;\n if (typeof nextCount === 'number') {\n setStoreUnreadCount(nextCount);\n eventBus?.emit('notification:unread-count-updated', { unreadCount: nextCount });\n }\n },\n error: (err) => {\n console.error('[useNotifications] Unread count subscription failed:', err);\n },\n });\n\n return () => {\n notificationSubscription.unsubscribe();\n unreadSubscription.unsubscribe();\n };\n }, [currentUser?.id, eventBus, getClient, setStoreUnreadCount]);\n\n useEffect(() => {\n const handleVisibilityChange = () => {\n if (document.visibilityState === 'visible') {\n fetchNotifications();\n fetchUnreadCount();\n }\n };\n\n document.addEventListener('visibilitychange', handleVisibilityChange);\n return () => document.removeEventListener('visibilitychange', handleVisibilityChange);\n }, [fetchNotifications, fetchUnreadCount]);\n\n const visibleNotifications = useMemo(\n () =>\n notifications.filter((notification) => {\n if (notification.deliveryStatus === 'UNSUBSCRIBED') {\n return false;\n }\n\n if (notification.status === 'ARCHIVED' && !notification.archivedAt) {\n return false;\n }\n\n if (effectiveFilter.archived === true) {\n return Boolean(notification.archivedAt);\n }\n\n if (effectiveFilter.archived === false) {\n return !notification.archivedAt;\n }\n\n return true;\n }),\n [effectiveFilter.archived, notifications]\n );\n\n return {\n notifications: visibleNotifications,\n allNotifications: notifications,\n unreadCount,\n selectedNotification,\n notificationFilter: effectiveFilter,\n isLoading,\n error,\n hasMore,\n total,\n markAsRead: handleMarkAsRead,\n markAllAsRead: handleMarkAllAsRead,\n archiveNotification: handleArchive,\n bulkArchive: handleBulkArchive,\n unarchiveNotification: handleUnarchive,\n recordAction: handleRecordAction,\n setSelectedNotification,\n updateFilter: updateNotificationFilter,\n resetFilter: resetNotificationFilter,\n refetch: fetchNotifications,\n loadMore,\n };\n}\n"],"mappings":";;;;;;AAgCA,SAASU,EAA4B,GAAsC;CACzE,OAAO;EACL,IAAIC,EAAE;EACN,MAAMC,EAAoBD,EAAE,IAAI;EAChC,UAAUE,EAAYF,EAAE,QAAQ;EAChC,OAAOA,EAAE;EACT,MAAMA,EAAE;EACR,WAAWA,EAAE,eAAe,KAAA;EAC5B,UAAUA,EAAE,WAAW,CAAC,EAAA,CAAG,KAAK,OAAY;GAC1C,IAAIG,EAAO;GACX,OAAOA,EAAO;GACd,KAAKA,EAAO;GACZ,OAAOA,EAAO,SAAS,KAAA;GACvB,YAAYA,EAAO,cAAc,KAAA;GACjC,UAAUA,EAAO,YAAY,KAAA;EAC/B,EAAE;EACF,SAASH,EAAE,WAAW,KAAA;EACtB,YAAYA,EAAE,cAAc,KAAA;EAC5B,SAASA,EAAE;EACX,WAAWA,EAAE,aAAa,KAAA;EAC1B,aAAaA,EAAE,eAAe,KAAA;EAC9B,gBAAgBA,EAAE,kBAAkB,KAAA;EACpC,UAAUA,EAAE,eAAe,KAAA;EAC3B,QAAQA,EAAE,SAAS,CAAC,EAAA,CAAG,KAAK,OAAU;GACpC,KAAKI,EAAK;GACV,OAAOA,EAAK,SAAS,KAAA;GACrB,MAAMA,EAAK,QAAQ,KAAA;GACnB,aAAaA,EAAK,eAAe,KAAA;GACjC,cAAcA,EAAK,gBAAgB,KAAA;EACrC,EAAE;EACF,UAAUJ,EAAE,YAAY,KAAA;EACxB,gBAAgBA,EAAE,kBAAkB,KAAA;EACpC,gBAAgBA,EAAE,kBAAkB,KAAA;EACpC,cAAcA,EAAE,gBAAgB,KAAA;EAChC,uBAAuBA,EAAE,wBACrB;GACE,IAAIA,EAAE,sBAAsB;GAC5B,cAAcA,EAAE,sBAAsB;GACtC,QAAQA,E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,GAAoBQ,CAAgB,CAAC,GA0BlC;EACL,eAzB2BnB,QAEzBhB,EAAc,QAAQ,MAChB6D,EAAa,mBAAmB,kBAIhCA,EAAa,WAAW,cAAc,CAACA,EAAa,aAC/C,KAGL9C,EAAgB,aAAa,KACxB,EAAQ8C,EAAa,aAG1B9C,EAAgB,aAAa,MACxB,CAAC8C,EAAa,UAIxB,GACH,CAAC9C,EAAgB,UAAUf,CAAa,CAIzB;EACf,kBAAkBA;EAClB;EACA;EACA,oBAAoBe;EACpB;EACA;EACA;EACA;EACA,YAAYyB;EACZ,eAAeI;EACf,qBAAqBE;EACrB,aAAaE;EACb,uBAAuBI;EACvB,cAAcE;EACd;EACA,cAAca;EACd,aAAaC;EACb,SAASzC;EACT;CACF;AACF"}
@@ -0,0 +1,158 @@
1
+ export type NotificationChannelType = 'DISCORD' | 'EMAIL' | 'PUSH' | 'SLACK' | 'SMS' | 'TEAMS' | 'TELEGRAM' | 'WEBHOOK' | 'WHATSAPP';
2
+ export type NotificationTypeEnum = 'ALERT' | 'MARKETING' | 'SYSTEM' | 'TRANSACTIONAL';
3
+ export type NotificationPriorityEnum = 'HIGH' | 'LOW' | 'MEDIUM' | 'URGENT';
4
+ export type NotificationStatusEnum = 'CANCELLED' | 'DELIVERED' | 'DRAFT' | 'EXPIRED' | 'FAILED' | 'PENDING' | 'READ' | 'SCHEDULED' | 'SENT' | 'TRIGGERED';
5
+ export type NotificationDeliveryStatusEnum = 'BOUNCED' | 'CLICKED' | 'COMPLAINED' | 'DELIVERED' | 'DELIVERING' | 'FAILED' | 'OPENED' | 'PENDING' | 'PROCESSING' | 'QUEUED' | 'RETRYING' | 'SENT' | 'UNSUBSCRIBED';
6
+ export type TriggerStatusEnum = 'CANCELLED' | 'FAILED' | 'PENDING' | 'TRIGGERED';
7
+ export interface RecipientInput {
8
+ email?: string;
9
+ locale?: string;
10
+ name?: string;
11
+ phoneNumber?: string;
12
+ pushToken?: string;
13
+ slackUserId?: string;
14
+ teamsUserId?: string;
15
+ timezone?: string;
16
+ userId?: string;
17
+ webhookUrl?: string;
18
+ whatsappNumber?: string;
19
+ }
20
+ export interface CreateNotificationInput {
21
+ actions?: Array<{
22
+ id?: string;
23
+ label: string;
24
+ url: string;
25
+ style?: string;
26
+ actionType?: string;
27
+ metadata?: Record<string, unknown>;
28
+ }>;
29
+ appName?: string;
30
+ body: string;
31
+ channel: NotificationChannelType;
32
+ data?: Record<string, unknown>;
33
+ expiresAt?: string;
34
+ htmlBody?: string;
35
+ media?: Array<{
36
+ url: string;
37
+ label?: string;
38
+ kind?: string;
39
+ contentType?: string;
40
+ thumbnailUrl?: string;
41
+ }>;
42
+ metadata?: Record<string, unknown>;
43
+ priority?: NotificationPriorityEnum;
44
+ recipient: RecipientInput;
45
+ redirectUrl?: string;
46
+ subject?: string;
47
+ trackClicks?: boolean;
48
+ trackOpens?: boolean;
49
+ topicId?: string;
50
+ type?: NotificationTypeEnum;
51
+ }
52
+ export interface TriggerNotificationInput {
53
+ notificationId?: string;
54
+ notification?: CreateNotificationInput;
55
+ channelId?: string;
56
+ platform?: NotificationChannelType;
57
+ includeInApp?: boolean;
58
+ userIds?: string[];
59
+ }
60
+ export interface TemplateNotificationResult {
61
+ totalRequested: number;
62
+ totalTriggered: number;
63
+ totalFailed: number;
64
+ notifications: TriggerNotificationResult[];
65
+ }
66
+ export interface TriggerWithTemplateInput {
67
+ actions?: Array<{
68
+ id?: string;
69
+ label: string;
70
+ url: string;
71
+ style?: string;
72
+ actionType?: string;
73
+ metadata?: Record<string, unknown>;
74
+ }>;
75
+ channelId?: string;
76
+ platform?: NotificationChannelType;
77
+ includeInApp?: boolean;
78
+ userIds?: string[];
79
+ expiresAt?: string;
80
+ redirectUrl?: string;
81
+ priority?: NotificationPriorityEnum;
82
+ /** Single recipient (use this OR recipients, not both) */
83
+ recipient?: RecipientInput;
84
+ /** Multiple recipients for bulk delivery (use this OR recipient, not both) */
85
+ recipients?: RecipientInput[];
86
+ templateSlug: string;
87
+ trackClicks?: boolean;
88
+ trackOpens?: boolean;
89
+ media?: Array<{
90
+ url: string;
91
+ label?: string;
92
+ kind?: string;
93
+ contentType?: string;
94
+ thumbnailUrl?: string;
95
+ }>;
96
+ topicId?: string;
97
+ variables: Record<string, unknown>;
98
+ scheduledFor?: string;
99
+ timezone?: string;
100
+ }
101
+ export interface TriggerBatchInput {
102
+ notificationIds?: string[];
103
+ notifications?: CreateNotificationInput[];
104
+ priority?: NotificationPriorityEnum;
105
+ delayBetweenBatches?: number;
106
+ batchSize?: number;
107
+ scheduledFor?: string;
108
+ timezone?: string;
109
+ }
110
+ export interface TriggerNotificationResult {
111
+ id: string;
112
+ status: NotificationStatusEnum;
113
+ deliveryStatus?: NotificationDeliveryStatusEnum;
114
+ triggerStatus: TriggerStatusEnum;
115
+ sentAt?: string;
116
+ title: string;
117
+ message: string;
118
+ }
119
+ export interface BatchNotificationResult {
120
+ batchId: string;
121
+ totalRequested: number;
122
+ totalTriggered: number;
123
+ totalFailed: number;
124
+ successCount: number;
125
+ failureCount: number;
126
+ results: Record<string, unknown>;
127
+ }
128
+ /**
129
+ * Hook to send notifications
130
+ * Provides methods for triggering single, batch, and template-based notifications
131
+ */
132
+ export declare function useSendNotification(): {
133
+ isLoading: boolean;
134
+ isSending: boolean;
135
+ error: string | null;
136
+ lastResult: TemplateNotificationResult | TriggerNotificationResult | BatchNotificationResult | null;
137
+ sendNotification: (input: TriggerNotificationInput) => Promise<TriggerNotificationResult | null>;
138
+ sendWithTemplate: (input: TriggerWithTemplateInput) => Promise<TemplateNotificationResult | null>;
139
+ sendBatch: (input: TriggerBatchInput) => Promise<BatchNotificationResult | null>;
140
+ sendSimple: (params: {
141
+ recipient: RecipientInput;
142
+ channel: NotificationChannelType;
143
+ body: string;
144
+ subject?: string;
145
+ type?: NotificationTypeEnum;
146
+ priority?: NotificationPriorityEnum;
147
+ }) => Promise<TriggerNotificationResult | null>;
148
+ sendToMultiple: (params: {
149
+ recipients: RecipientInput[];
150
+ channel: NotificationChannelType;
151
+ body: string;
152
+ subject?: string;
153
+ type?: NotificationTypeEnum;
154
+ priority?: NotificationPriorityEnum;
155
+ }) => Promise<BatchNotificationResult | null>;
156
+ clearError: () => void;
157
+ clearResult: () => void;
158
+ };
@@ -2,7 +2,7 @@ import { useNotification as e } from "../providers/NotificationProvider.js";
2
2
  import { getGlobalNotificationClient as t } from "../graphql/global-client.js";
3
3
  import { TriggerBatchNotificationsDocument as n, TriggerNotificationDocument as r, TriggerNotificationWithTemplateDocument as i } from "../generated/global-operations.js";
4
4
  import { useCallback as a, useState as o } from "react";
5
- //#region src/hooks/useSendNotification.ts
5
+ // src/hooks/useSendNotification.ts
6
6
  function s() {
7
7
  let { authToken: s, apiGatewayUrl: c } = e(), [l, u] = o(!1), [d, f] = o(!1), [p, m] = o(null), [h, g] = o(null), _ = a(() => t(c ?? void 0, s ?? void 0), [c, s]), v = a(async (e) => {
8
8
  f(!0), m(null);
@@ -101,14 +101,17 @@ function s() {
101
101
  },
102
102
  platform: e.channel
103
103
  }), [v]),
104
- sendToMultiple: a(async (e) => b({ notifications: e.recipients.map((t) => ({
105
- body: e.body,
106
- channel: e.channel,
107
- recipient: t,
108
- subject: e.subject,
109
- type: e.type || "MARKETING",
110
- priority: e.priority || "MEDIUM"
111
- })) }), [b]),
104
+ sendToMultiple: a(async (e) => {
105
+ let t = e.recipients.map((t) => ({
106
+ body: e.body,
107
+ channel: e.channel,
108
+ recipient: t,
109
+ subject: e.subject,
110
+ type: e.type || "MARKETING",
111
+ priority: e.priority || "MEDIUM"
112
+ }));
113
+ return b({ notifications: t });
114
+ }, [b]),
112
115
  clearError: a(() => {
113
116
  m(null);
114
117
  }, []),
@@ -117,7 +120,6 @@ function s() {
117
120
  }, [])
118
121
  };
119
122
  }
120
- //#endregion
121
123
  export { s as useSendNotification };
122
124
 
123
125
  //# sourceMappingURL=useSendNotification.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSendNotification.js","names":[],"sources":["../../src/hooks/useSendNotification.ts"],"sourcesContent":["import { useState, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n TriggerNotificationMutation,\n TriggerNotificationWithTemplateMutation,\n TriggerBatchNotificationsMutation,\n} from '../generated/global-operations';\n\n// =============================================================================\n// Type Definitions (aligned with backend GraphQL schema)\n// =============================================================================\n\nexport type NotificationChannelType =\n | 'DISCORD'\n | 'EMAIL'\n | 'PUSH'\n | 'SLACK'\n | 'SMS'\n | 'TEAMS'\n | 'TELEGRAM'\n | 'WEBHOOK'\n | 'WHATSAPP';\n\nexport type NotificationTypeEnum = 'ALERT' | 'MARKETING' | 'SYSTEM' | 'TRANSACTIONAL';\n\nexport type NotificationPriorityEnum = 'HIGH' | 'LOW' | 'MEDIUM' | 'URGENT';\n\nexport type NotificationStatusEnum =\n | 'CANCELLED'\n | 'DELIVERED'\n | 'DRAFT'\n | 'EXPIRED'\n | 'FAILED'\n | 'PENDING'\n | 'READ'\n | 'SCHEDULED'\n | 'SENT'\n | 'TRIGGERED';\n\nexport type NotificationDeliveryStatusEnum =\n | 'BOUNCED'\n | 'CLICKED'\n | 'COMPLAINED'\n | 'DELIVERED'\n | 'DELIVERING'\n | 'FAILED'\n | 'OPENED'\n | 'PENDING'\n | 'PROCESSING'\n | 'QUEUED'\n | 'RETRYING'\n | 'SENT'\n | 'UNSUBSCRIBED';\n\nexport type TriggerStatusEnum = 'CANCELLED' | 'FAILED' | 'PENDING' | 'TRIGGERED';\n\nexport interface RecipientInput {\n email?: string;\n locale?: string;\n name?: string;\n phoneNumber?: string;\n pushToken?: string;\n slackUserId?: string;\n teamsUserId?: string;\n timezone?: string;\n userId?: string;\n webhookUrl?: string;\n whatsappNumber?: string;\n}\n\nexport interface CreateNotificationInput {\n actions?: Array<{\n id?: string;\n label: string;\n url: string;\n style?: string;\n actionType?: string;\n metadata?: Record<string, unknown>;\n }>;\n appName?: string;\n body: string;\n channel: NotificationChannelType;\n data?: Record<string, unknown>;\n expiresAt?: string;\n htmlBody?: string;\n media?: Array<{\n url: string;\n label?: string;\n kind?: string;\n contentType?: string;\n thumbnailUrl?: string;\n }>;\n metadata?: Record<string, unknown>;\n priority?: NotificationPriorityEnum;\n recipient: RecipientInput;\n redirectUrl?: string;\n subject?: string;\n trackClicks?: boolean;\n trackOpens?: boolean;\n topicId?: string;\n type?: NotificationTypeEnum;\n}\n\nexport interface TriggerNotificationInput {\n notificationId?: string;\n notification?: CreateNotificationInput;\n channelId?: string;\n platform?: NotificationChannelType;\n includeInApp?: boolean;\n userIds?: string[];\n}\n\nexport interface TemplateNotificationResult {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: TriggerNotificationResult[];\n}\n\nexport interface TriggerWithTemplateInput {\n actions?: Array<{\n id?: string;\n label: string;\n url: string;\n style?: string;\n actionType?: string;\n metadata?: Record<string, unknown>;\n }>;\n channelId?: string;\n platform?: NotificationChannelType;\n includeInApp?: boolean;\n userIds?: string[];\n expiresAt?: string;\n redirectUrl?: string;\n priority?: NotificationPriorityEnum;\n /** Single recipient (use this OR recipients, not both) */\n recipient?: RecipientInput;\n /** Multiple recipients for bulk delivery (use this OR recipient, not both) */\n recipients?: RecipientInput[];\n templateSlug: string;\n trackClicks?: boolean;\n trackOpens?: boolean;\n media?: Array<{\n url: string;\n label?: string;\n kind?: string;\n contentType?: string;\n thumbnailUrl?: string;\n }>;\n topicId?: string;\n variables: Record<string, unknown>;\n scheduledFor?: string;\n timezone?: string;\n}\n\nexport interface TriggerBatchInput {\n notificationIds?: string[];\n notifications?: CreateNotificationInput[];\n priority?: NotificationPriorityEnum;\n delayBetweenBatches?: number;\n batchSize?: number;\n scheduledFor?: string;\n timezone?: string;\n}\n\nexport interface TriggerNotificationResult {\n id: string;\n status: NotificationStatusEnum;\n deliveryStatus?: NotificationDeliveryStatusEnum;\n triggerStatus: TriggerStatusEnum;\n sentAt?: string;\n title: string;\n message: string;\n}\n\nexport interface BatchNotificationResult {\n batchId: string;\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n successCount: number;\n failureCount: number;\n results: Record<string, unknown>;\n}\n\n// =============================================================================\n\n/**\n * Hook to send notifications\n * Provides methods for triggering single, batch, and template-based notifications\n */\nexport function useSendNotification() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [isLoading, _setIsLoading] = useState(false);\n const [isSending, setIsSending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [lastResult, setLastResult] = useState<\n TriggerNotificationResult | BatchNotificationResult | TemplateNotificationResult | null\n >(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 /**\n * Send a single notification.\n * @throws the underlying GraphQL/network error after setting the hook's `error` state, so callers can inspect it (e.g. detect gateway FORBIDDEN via `isPermissionError`).\n */\n const sendNotification = useCallback(\n async (input: TriggerNotificationInput): Promise<TriggerNotificationResult | null> => {\n setIsSending(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<TriggerNotificationMutation>({\n mutation: NotificationOps.TriggerNotificationDocument,\n variables: { input },\n });\n\n const raw = result.data?.triggerNotification ?? null;\n if (!raw) return null;\n const notification: TriggerNotificationResult = {\n id: raw.id,\n status: raw.status as unknown as NotificationStatusEnum,\n deliveryStatus: (raw.deliveryStatus ?? undefined) as\n | NotificationDeliveryStatusEnum\n | undefined,\n triggerStatus: raw.triggerStatus as unknown as TriggerStatusEnum,\n sentAt: raw.sentAt ?? undefined,\n title: raw.title,\n message: raw.message,\n };\n setLastResult(notification);\n return notification;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to send notification';\n console.error('[useSendNotification] Failed to send notification:', err);\n setError(message);\n // Re-throw so the caller's catch block can inspect the raw error (e.g.,\n // detect gateway FORBIDDEN via isPermissionError) — matches the\n // useNotificationTemplates pattern.\n throw err;\n } finally {\n setIsSending(false);\n }\n },\n [getClient]\n );\n\n /**\n * Send notification using a template. Supports single recipient (recipient) or bulk delivery (recipients).\n * @throws the underlying error after setting `error` state — same contract as `sendNotification`.\n */\n const sendWithTemplate = useCallback(\n async (input: TriggerWithTemplateInput): Promise<TemplateNotificationResult | null> => {\n setIsSending(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<TriggerNotificationWithTemplateMutation>({\n mutation: NotificationOps.TriggerNotificationWithTemplateDocument,\n variables: { input },\n });\n\n const raw = result.data?.triggerNotificationWithTemplate ?? null;\n if (!raw) return null;\n const templateResult: TemplateNotificationResult = {\n totalRequested: raw.totalRequested,\n totalTriggered: raw.totalTriggered,\n totalFailed: raw.totalFailed,\n notifications: raw.notifications.map((n) => ({\n id: n.id,\n status: n.status as unknown as NotificationStatusEnum,\n deliveryStatus: undefined,\n triggerStatus: 'TRIGGERED' as TriggerStatusEnum,\n sentAt: n.sentAt ?? undefined,\n title: n.title,\n message: n.message,\n })),\n };\n setLastResult(templateResult);\n return templateResult;\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : 'Failed to send notification with template';\n console.error('[useSendNotification] Failed to send notification with template:', err);\n setError(message);\n throw err;\n } finally {\n setIsSending(false);\n }\n },\n [getClient]\n );\n\n /**\n * Send notifications to multiple recipients.\n * @throws the underlying error after setting `error` state — same contract as `sendNotification`.\n */\n const sendBatch = useCallback(\n async (input: TriggerBatchInput): Promise<BatchNotificationResult | null> => {\n setIsSending(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<TriggerBatchNotificationsMutation>({\n mutation: NotificationOps.TriggerBatchNotificationsDocument,\n variables: { input },\n });\n\n const raw = result.data?.triggerBatchNotifications ?? null;\n if (!raw) return null;\n const batchResult: BatchNotificationResult = {\n batchId: raw.batchId,\n totalRequested: raw.totalRequested,\n totalTriggered: raw.totalTriggered,\n totalFailed: raw.totalFailed,\n successCount: raw.totalTriggered,\n failureCount: raw.totalFailed,\n results: raw.results,\n };\n setLastResult(batchResult);\n return batchResult;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to send batch notifications';\n console.error('[useSendNotification] Failed to send batch notifications:', err);\n setError(message);\n throw err;\n } finally {\n setIsSending(false);\n }\n },\n [getClient]\n );\n\n /**\n * Helper: Send a simple notification to one recipient\n * Simplified interface for common use case\n */\n const sendSimple = useCallback(\n async (params: {\n recipient: RecipientInput;\n channel: NotificationChannelType;\n body: string;\n subject?: string;\n type?: NotificationTypeEnum;\n priority?: NotificationPriorityEnum;\n }): Promise<TriggerNotificationResult | null> => {\n return sendNotification({\n notification: {\n body: params.body,\n channel: params.channel,\n recipient: params.recipient,\n subject: params.subject,\n type: params.type || 'TRANSACTIONAL',\n priority: params.priority || 'MEDIUM',\n },\n platform: params.channel,\n });\n },\n [sendNotification]\n );\n\n /**\n * Helper: Send to multiple recipients with same message\n */\n const sendToMultiple = useCallback(\n async (params: {\n recipients: RecipientInput[];\n channel: NotificationChannelType;\n body: string;\n subject?: string;\n type?: NotificationTypeEnum;\n priority?: NotificationPriorityEnum;\n }): Promise<BatchNotificationResult | null> => {\n const notifications: CreateNotificationInput[] = params.recipients.map((recipient) => ({\n body: params.body,\n channel: params.channel,\n recipient,\n subject: params.subject,\n type: params.type || 'MARKETING',\n priority: params.priority || 'MEDIUM',\n }));\n\n return sendBatch({ notifications });\n },\n [sendBatch]\n );\n\n /**\n * Clear error state\n */\n const clearError = useCallback(() => {\n setError(null);\n }, []);\n\n /**\n * Clear last result\n */\n const clearResult = useCallback(() => {\n setLastResult(null);\n }, []);\n\n return {\n // State\n isLoading,\n isSending,\n error,\n lastResult,\n\n // Core methods\n sendNotification,\n sendWithTemplate,\n sendBatch,\n\n // Helper methods\n sendSimple,\n sendToMultiple,\n\n // Utilities\n clearError,\n clearResult,\n };\n}\n"],"mappings":";;;;;AAiMA,SAAgB,IAAsB;CACpC,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAW,KAAiB,E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ACb,SAAS,EAAO;GAChB;GACA,SAAS,EAAO;GAChB,MAAM,EAAO,QAAQ;GACrB,UAAU,EAAO,YAAY;GAC9B,EAAE,EAE+B,CAAC,EAErC,CAAC,EAAU,CACZ;EAiCC,YA5BiB,QAAkB;AACnC,KAAS,KAAK;KACb,EAAE,CAAC;EA2BJ,aAtBkB,QAAkB;AACpC,KAAc,KAAK;KAClB,EAAE,CAAC;EAqBL"}
1
+ {"version":3,"file":"useSendNotification.js","names":["NotificationOps.TriggerNotificationDocument","NotificationOps.TriggerNotificationWithTemplateDocument","NotificationOps.TriggerBatchNotificationsDocument","useSendNotification","useNotification","isLoading","_setIsLoading","useState","isSending","setIsSending","error","setError","lastResult","setLastResult","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","sendNotification","raw","TriggerNotificationDocument","notification","err","message","sendWithTemplate","TriggerNotificationWithTemplateDocument","templateResult","n","sendBatch","TriggerBatchNotificationsDocument","batchResult","params","notifications"],"sources":["../../src/hooks/useSendNotification.ts"],"sourcesContent":["import { useState, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n TriggerNotificationMutation,\n TriggerNotificationWithTemplateMutation,\n TriggerBatchNotificationsMutation,\n} from '../generated/global-operations';\n\n// =============================================================================\n// Type Definitions (aligned with backend GraphQL schema)\n// =============================================================================\n\nexport type NotificationChannelType =\n 'DISCORD' | 'EMAIL' | 'PUSH' | 'SLACK' | 'SMS' | 'TEAMS' | 'TELEGRAM' | 'WEBHOOK' | 'WHATSAPP';\n\nexport type NotificationTypeEnum = 'ALERT' | 'MARKETING' | 'SYSTEM' | 'TRANSACTIONAL';\n\nexport type NotificationPriorityEnum = 'HIGH' | 'LOW' | 'MEDIUM' | 'URGENT';\n\nexport type NotificationStatusEnum =\n | 'CANCELLED'\n | 'DELIVERED'\n | 'DRAFT'\n | 'EXPIRED'\n | 'FAILED'\n | 'PENDING'\n | 'READ'\n | 'SCHEDULED'\n | 'SENT'\n | 'TRIGGERED';\n\nexport type NotificationDeliveryStatusEnum =\n | 'BOUNCED'\n | 'CLICKED'\n | 'COMPLAINED'\n | 'DELIVERED'\n | 'DELIVERING'\n | 'FAILED'\n | 'OPENED'\n | 'PENDING'\n | 'PROCESSING'\n | 'QUEUED'\n | 'RETRYING'\n | 'SENT'\n | 'UNSUBSCRIBED';\n\nexport type TriggerStatusEnum = 'CANCELLED' | 'FAILED' | 'PENDING' | 'TRIGGERED';\n\nexport interface RecipientInput {\n email?: string;\n locale?: string;\n name?: string;\n phoneNumber?: string;\n pushToken?: string;\n slackUserId?: string;\n teamsUserId?: string;\n timezone?: string;\n userId?: string;\n webhookUrl?: string;\n whatsappNumber?: string;\n}\n\nexport interface CreateNotificationInput {\n actions?: Array<{\n id?: string;\n label: string;\n url: string;\n style?: string;\n actionType?: string;\n metadata?: Record<string, unknown>;\n }>;\n appName?: string;\n body: string;\n channel: NotificationChannelType;\n data?: Record<string, unknown>;\n expiresAt?: string;\n htmlBody?: string;\n media?: Array<{\n url: string;\n label?: string;\n kind?: string;\n contentType?: string;\n thumbnailUrl?: string;\n }>;\n metadata?: Record<string, unknown>;\n priority?: NotificationPriorityEnum;\n recipient: RecipientInput;\n redirectUrl?: string;\n subject?: string;\n trackClicks?: boolean;\n trackOpens?: boolean;\n topicId?: string;\n type?: NotificationTypeEnum;\n}\n\nexport interface TriggerNotificationInput {\n notificationId?: string;\n notification?: CreateNotificationInput;\n channelId?: string;\n platform?: NotificationChannelType;\n includeInApp?: boolean;\n userIds?: string[];\n}\n\nexport interface TemplateNotificationResult {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: TriggerNotificationResult[];\n}\n\nexport interface TriggerWithTemplateInput {\n actions?: Array<{\n id?: string;\n label: string;\n url: string;\n style?: string;\n actionType?: string;\n metadata?: Record<string, unknown>;\n }>;\n channelId?: string;\n platform?: NotificationChannelType;\n includeInApp?: boolean;\n userIds?: string[];\n expiresAt?: string;\n redirectUrl?: string;\n priority?: NotificationPriorityEnum;\n /** Single recipient (use this OR recipients, not both) */\n recipient?: RecipientInput;\n /** Multiple recipients for bulk delivery (use this OR recipient, not both) */\n recipients?: RecipientInput[];\n templateSlug: string;\n trackClicks?: boolean;\n trackOpens?: boolean;\n media?: Array<{\n url: string;\n label?: string;\n kind?: string;\n contentType?: string;\n thumbnailUrl?: string;\n }>;\n topicId?: string;\n variables: Record<string, unknown>;\n scheduledFor?: string;\n timezone?: string;\n}\n\nexport interface TriggerBatchInput {\n notificationIds?: string[];\n notifications?: CreateNotificationInput[];\n priority?: NotificationPriorityEnum;\n delayBetweenBatches?: number;\n batchSize?: number;\n scheduledFor?: string;\n timezone?: string;\n}\n\nexport interface TriggerNotificationResult {\n id: string;\n status: NotificationStatusEnum;\n deliveryStatus?: NotificationDeliveryStatusEnum;\n triggerStatus: TriggerStatusEnum;\n sentAt?: string;\n title: string;\n message: string;\n}\n\nexport interface BatchNotificationResult {\n batchId: string;\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n successCount: number;\n failureCount: number;\n results: Record<string, unknown>;\n}\n\n// =============================================================================\n\n/**\n * Hook to send notifications\n * Provides methods for triggering single, batch, and template-based notifications\n */\nexport function useSendNotification() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [isLoading, _setIsLoading] = useState(false);\n const [isSending, setIsSending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [lastResult, setLastResult] = useState<\n TriggerNotificationResult | BatchNotificationResult | TemplateNotificationResult | null\n >(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 /**\n * Send a single notification.\n * @throws the underlying GraphQL/network error after setting the hook's `error` state, so callers can inspect it (e.g. detect gateway FORBIDDEN via `isPermissionError`).\n */\n const sendNotification = useCallback(\n async (input: TriggerNotificationInput): Promise<TriggerNotificationResult | null> => {\n setIsSending(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<TriggerNotificationMutation>({\n mutation: NotificationOps.TriggerNotificationDocument,\n variables: { input },\n });\n\n const raw = result.data?.triggerNotification ?? null;\n if (!raw) return null;\n const notification: TriggerNotificationResult = {\n id: raw.id,\n status: raw.status as unknown as NotificationStatusEnum,\n deliveryStatus: (raw.deliveryStatus ?? undefined) as\n NotificationDeliveryStatusEnum | undefined,\n triggerStatus: raw.triggerStatus as unknown as TriggerStatusEnum,\n sentAt: raw.sentAt ?? undefined,\n title: raw.title,\n message: raw.message,\n };\n setLastResult(notification);\n return notification;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to send notification';\n console.error('[useSendNotification] Failed to send notification:', err);\n setError(message);\n // Re-throw so the caller's catch block can inspect the raw error (e.g.,\n // detect gateway FORBIDDEN via isPermissionError) — matches the\n // useNotificationTemplates pattern.\n throw err;\n } finally {\n setIsSending(false);\n }\n },\n [getClient]\n );\n\n /**\n * Send notification using a template. Supports single recipient (recipient) or bulk delivery (recipients).\n * @throws the underlying error after setting `error` state — same contract as `sendNotification`.\n */\n const sendWithTemplate = useCallback(\n async (input: TriggerWithTemplateInput): Promise<TemplateNotificationResult | null> => {\n setIsSending(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<TriggerNotificationWithTemplateMutation>({\n mutation: NotificationOps.TriggerNotificationWithTemplateDocument,\n variables: { input },\n });\n\n const raw = result.data?.triggerNotificationWithTemplate ?? null;\n if (!raw) return null;\n const templateResult: TemplateNotificationResult = {\n totalRequested: raw.totalRequested,\n totalTriggered: raw.totalTriggered,\n totalFailed: raw.totalFailed,\n notifications: raw.notifications.map((n) => ({\n id: n.id,\n status: n.status as unknown as NotificationStatusEnum,\n deliveryStatus: undefined,\n triggerStatus: 'TRIGGERED' as TriggerStatusEnum,\n sentAt: n.sentAt ?? undefined,\n title: n.title,\n message: n.message,\n })),\n };\n setLastResult(templateResult);\n return templateResult;\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : 'Failed to send notification with template';\n console.error('[useSendNotification] Failed to send notification with template:', err);\n setError(message);\n throw err;\n } finally {\n setIsSending(false);\n }\n },\n [getClient]\n );\n\n /**\n * Send notifications to multiple recipients.\n * @throws the underlying error after setting `error` state — same contract as `sendNotification`.\n */\n const sendBatch = useCallback(\n async (input: TriggerBatchInput): Promise<BatchNotificationResult | null> => {\n setIsSending(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<TriggerBatchNotificationsMutation>({\n mutation: NotificationOps.TriggerBatchNotificationsDocument,\n variables: { input },\n });\n\n const raw = result.data?.triggerBatchNotifications ?? null;\n if (!raw) return null;\n const batchResult: BatchNotificationResult = {\n batchId: raw.batchId,\n totalRequested: raw.totalRequested,\n totalTriggered: raw.totalTriggered,\n totalFailed: raw.totalFailed,\n successCount: raw.totalTriggered,\n failureCount: raw.totalFailed,\n results: raw.results,\n };\n setLastResult(batchResult);\n return batchResult;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to send batch notifications';\n console.error('[useSendNotification] Failed to send batch notifications:', err);\n setError(message);\n throw err;\n } finally {\n setIsSending(false);\n }\n },\n [getClient]\n );\n\n /**\n * Helper: Send a simple notification to one recipient\n * Simplified interface for common use case\n */\n const sendSimple = useCallback(\n async (params: {\n recipient: RecipientInput;\n channel: NotificationChannelType;\n body: string;\n subject?: string;\n type?: NotificationTypeEnum;\n priority?: NotificationPriorityEnum;\n }): Promise<TriggerNotificationResult | null> => {\n return sendNotification({\n notification: {\n body: params.body,\n channel: params.channel,\n recipient: params.recipient,\n subject: params.subject,\n type: params.type || 'TRANSACTIONAL',\n priority: params.priority || 'MEDIUM',\n },\n platform: params.channel,\n });\n },\n [sendNotification]\n );\n\n /**\n * Helper: Send to multiple recipients with same message\n */\n const sendToMultiple = useCallback(\n async (params: {\n recipients: RecipientInput[];\n channel: NotificationChannelType;\n body: string;\n subject?: string;\n type?: NotificationTypeEnum;\n priority?: NotificationPriorityEnum;\n }): Promise<BatchNotificationResult | null> => {\n const notifications: CreateNotificationInput[] = params.recipients.map((recipient) => ({\n body: params.body,\n channel: params.channel,\n recipient,\n subject: params.subject,\n type: params.type || 'MARKETING',\n priority: params.priority || 'MEDIUM',\n }));\n\n return sendBatch({ notifications });\n },\n [sendBatch]\n );\n\n /**\n * Clear error state\n */\n const clearError = useCallback(() => {\n setError(null);\n }, []);\n\n /**\n * Clear last result\n */\n const clearResult = useCallback(() => {\n setLastResult(null);\n }, []);\n\n return {\n // State\n isLoading,\n isSending,\n error,\n lastResult,\n\n // Core methods\n sendNotification,\n sendWithTemplate,\n sendBatch,\n\n // Helper methods\n sendSimple,\n sendToMultiple,\n\n // Utilities\n clearError,\n clearResult,\n };\n}\n"],"mappings":";;;;;AAyLA,SAAgBG,IAAsB;CACpC,IAAM,EAAE,cAAW,qBAAkBC,EAAgB,GAC/C,CAACC,GAAWC,KAAiBC,EAAS,EAAK,GAC3C,CAACC,GAAWC,KAAgBF,EAAS,EAAK,GAC1C,CAACG,GAAOC,KAAYJ,EAAwB,IAAI,GAChD,CAACK,GAAYC,KAAiBN,EAElC,IAAI,GAGAO,IAAYC,QACTC,EAA4BC,KAAiB,KAAA,GAAWC,KAAa,KAAA,CAAS,GACpF,CAACD,GAAeC,CAAS,CAAC,GAMvBC,IAAmBJ,EACvB,OAAO,MAA+E;EAEpF,AADAN,EAAa,EAAI,GACjBE,EAAS,IAAI;EAEb,IAAI;GAOF,IAAMS,KAAM,MANGN,EACM,CAAA,CAAO,OAAoC;IAC9D,UAAUd;IACV,WAAW,EAAE,SAAM;GACrB,CAAC,EAAA,CAEkB,MAAM,uBAAuB;GAChD,IAAI,CAACoB,GAAK,OAAO;GACjB,IAAME,IAA0C;IAC9C,IAAIF,EAAI;IACR,QAAQA,EAAI;IACZ,gBAAiBA,EAAI,kBAAkB,KAAA;IAEvC,eAAeA,EAAI;IACnB,QAAQA,EAAI,UAAU,K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6B;GACtD,IAAI,CAACkB,GAAK,OAAO;GACjB,IAAMW,IAAuC;IAC3C,SAASX,EAAI;IACb,gBAAgBA,EAAI;IACpB,gBAAgBA,EAAI;IACpB,aAAaA,EAAI;IACjB,cAAcA,EAAI;IAClB,cAAcA,EAAI;IAClB,SAASA,EAAI;GACf;GAEA,OADAP,EAAckB,CAAW,GAClBA;EACT,SAASR,GAAc;GACrB,IAAMC,IAAUD,aAAe,QAAQA,EAAI,UAAU;GAGrD,MAFA,QAAQ,MAAM,6DAA6DA,CAAG,GAC9EZ,EAASa,CAAO,GACVD;EACR,UAAU;GACR,EAAa,EAAK;EACpB;CACF,GACA,CAACT,CAAS,CACZ;CAsEA,OAAO;EAEL;EACA;EACA;EACA;EAGA;EACA;EACA;EAGA,YA7EiBC,EACjB,OAAO,MAQEI,EAAiB;GACtB,cAAc;IACZ,MAAMa,EAAO;IACb,SAASA,EAAO;IAChB,WAAWA,EAAO;IAClB,SAASA,EAAO;IAChB,MAAMA,EAAO,QAAQ;IACrB,UAAUA,EAAO,YAAY;GAC/B;GACA,UAAUA,EAAO;EACnB,CAAC,GAEH,CAACb,CAAgB,CAwDjB;EACA,gBAnDqBJ,EACrB,OAAO,MAOwC;GAC7C,IAAMkB,IAA2CD,EAAO,WAAW,KAAK,OAAe;IACrF,MAAMA,EAAO;IACb,SAASA,EAAO;IAChB;IACA,SAASA,EAAO;IAChB,MAAMA,EAAO,QAAQ;IACrB,UAAUA,EAAO,YAAY;GAC/B,EAAE;GAEF,OAAOH,EAAU,EAAE,iBAAc,CAAC;EACpC,GACA,CAACA,CAAS,CA+BV;EAGA,YA5BiBd,QAAkB;GACnC,EAAS,IAAI;EACf,GAAG,CAAC,CA0BF;EACA,aAtBkBA,QAAkB;GACpC,EAAc,IAAI;EACpB,GAAG,CAAC,CAoBF;CACF;AACF"}
@@ -0,0 +1,26 @@
1
+ export interface User {
2
+ id: string;
3
+ name: string;
4
+ email: string;
5
+ phoneNumber?: string;
6
+ role?: string;
7
+ status?: string;
8
+ username?: string;
9
+ }
10
+ export interface UserSearchFilter {
11
+ search?: string;
12
+ role?: string;
13
+ status?: string;
14
+ }
15
+ /**
16
+ * Hook for searching users via the global auth service.
17
+ * Uses the Apollo client from notification context (not raw fetch).
18
+ */
19
+ export declare function useUserSearch(): {
20
+ searchUsers: (query: string, extraFilter?: Omit<UserSearchFilter, "search">) => void;
21
+ fetchAllUsers: (filter: UserSearchFilter) => Promise<User[]>;
22
+ results: User[];
23
+ isLoading: boolean;
24
+ error: string | null;
25
+ clearResults: () => void;
26
+ };
@@ -2,7 +2,7 @@ import { useNotification as e } from "../providers/NotificationProvider.js";
2
2
  import { getGlobalNotificationClient as t } from "../graphql/global-client.js";
3
3
  import { SearchUsersDocument as n } from "../generated/global-operations.js";
4
4
  import { useCallback as r, useEffect as i, useRef as a, useState as o } from "react";
5
- //#region src/hooks/useUserSearch.ts
5
+ // src/hooks/useUserSearch.ts
6
6
  function s() {
7
7
  let { authToken: s, apiGatewayUrl: c } = e(), [l, u] = o(!1), [d, f] = o(null), [p, m] = o([]), h = a(null), g = r(() => t(c ?? void 0, s ?? void 0), [c, s]), _ = r(async (e, t = 10, r = 0) => ((await g().query({
8
8
  query: n,
@@ -27,17 +27,14 @@ function s() {
27
27
  status: e.status,
28
28
  username: e.username
29
29
  })), [g]), v = r((e, t) => {
30
- if (h.current && clearTimeout(h.current), !e.trim() && !t?.role && !t?.status) {
31
- m([]);
32
- return;
33
- }
34
- h.current = setTimeout(async () => {
30
+ h.current && clearTimeout(h.current), !e.trim() && !t?.role && !t?.status ? m([]) : h.current = setTimeout(async () => {
35
31
  u(!0), f(null);
36
32
  try {
37
- m(await _({
33
+ let n = await _({
38
34
  search: e.trim(),
39
35
  ...t
40
- }, 20, 0));
36
+ }, 20, 0);
37
+ m(n);
41
38
  } catch (e) {
42
39
  console.error("User search error:", e), f(e instanceof Error ? e.message : "Failed to search users"), m([]);
43
40
  } finally {
@@ -54,7 +51,9 @@ function s() {
54
51
  }
55
52
  return r;
56
53
  } catch (e) {
57
- return console.error("Fetch all users error:", e), f(e instanceof Error ? e.message : "Failed to fetch users"), [];
54
+ console.error("Fetch all users error:", e);
55
+ let t = e instanceof Error ? e.message : "Failed to fetch users";
56
+ return f(t), [];
58
57
  } finally {
59
58
  u(!1);
60
59
  }
@@ -70,7 +69,6 @@ function s() {
70
69
  clearResults: () => m([])
71
70
  };
72
71
  }
73
- //#endregion
74
72
  export { s as useUserSearch };
75
73
 
76
74
  //# sourceMappingURL=useUserSearch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useUserSearch.js","names":[],"sources":["../../src/hooks/useUserSearch.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport * as NotificationOps from '../generated/global-operations';\nimport type { SearchUsersQuery } from '../generated/global-operations';\n\nexport interface User {\n id: string;\n name: string;\n email: string;\n phoneNumber?: string;\n role?: string;\n status?: string;\n username?: string;\n}\n\nexport interface UserSearchFilter {\n search?: string;\n role?: string;\n status?: string;\n}\n\n/**\n * Hook for searching users via the global auth service.\n * Uses the Apollo client from notification context (not raw fetch).\n */\nexport function useUserSearch() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [results, setResults] = useState<User[]>([]);\n const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Debounced search function\n const runQuery = useCallback(\n async (filter: UserSearchFilter, limit = 10, offset = 0): Promise<User[]> => {\n const client = getClient();\n const result = await client.query<SearchUsersQuery>({\n query: NotificationOps.SearchUsersDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search.trim() } : {}),\n ...(filter.role ? { role: filter.role } : {}),\n ...(filter.status ? { status: filter.status } : {}),\n },\n pagination: { limit, offset },\n },\n fetchPolicy: 'network-only',\n });\n\n return (result.data?.users?.users || []).map((u) => ({\n id: u.id,\n name: u.name || '',\n email: u.email,\n phoneNumber: u.phoneNumber ?? undefined,\n role: (u as { role?: string }).role,\n status: (u as { status?: string }).status,\n username: u.username,\n }));\n },\n [getClient]\n );\n\n const searchUsers = useCallback(\n (query: string, extraFilter?: Omit<UserSearchFilter, 'search'>) => {\n if (debounceTimer.current) {\n clearTimeout(debounceTimer.current);\n }\n\n if (!query.trim() && !extraFilter?.role && !extraFilter?.status) {\n setResults([]);\n return;\n }\n\n debounceTimer.current = setTimeout(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const users = await runQuery({ search: query.trim(), ...extraFilter }, 20, 0);\n setResults(users);\n } catch (err) {\n console.error('User search error:', err);\n setError(err instanceof Error ? err.message : 'Failed to search users');\n setResults([]);\n } finally {\n setIsLoading(false);\n }\n }, 300);\n },\n [runQuery]\n );\n\n const fetchAllUsers = useCallback(\n async (filter: UserSearchFilter): Promise<User[]> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const pageSize = 100;\n let offset = 0;\n let hasMore = true;\n const allUsers: User[] = [];\n\n while (hasMore) {\n const page = await runQuery(filter, pageSize, offset);\n allUsers.push(...page);\n hasMore = page.length === pageSize;\n offset += pageSize;\n }\n\n return allUsers;\n } catch (err) {\n console.error('Fetch all users error:', err);\n const message = err instanceof Error ? err.message : 'Failed to fetch users';\n setError(message);\n return [];\n } finally {\n setIsLoading(false);\n }\n },\n [runQuery]\n );\n\n // Clear timer on unmount\n useEffect(() => {\n return () => {\n if (debounceTimer.current) {\n clearTimeout(debounceTimer.current);\n }\n };\n }, []);\n\n return {\n searchUsers,\n fetchAllUsers,\n results,\n isLoading,\n error,\n clearResults: () => setResults([]),\n };\n}\n"],"mappings":";;;;;AA0BA,SAAgB,IAAgB;CAC9B,IAAM,EAAE,cAAW,qBAAkB,GAAiB,EAChD,CAAC,GAAW,KAAgB,E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S,aAAe,QAAQ,EAAI,UAAU,yBAAyB,EACvE,EAAW,EAAE,CAAC;aACN;AACR,MAAa,GAAM;;KAEpB,IAAI;IAET,CAAC,EAAS,CACX,EAEK,IAAgB,EACpB,OAAO,MAA8C;AAEnD,EADA,EAAa,GAAK,EAClB,EAAS,KAAK;AAEd,MAAI;GACF,IACI,IAAS,GACT,IAAU,IACR,IAAmB,EAAE;AAE3B,UAAO,IAAS;IACd,IAAM,IAAO,MAAM,EAAS,GAAQ,KAAU,EAAO;AAGrD,IAFA,EAAS,KAAK,GAAG,EAAK,EACtB,IAAU,EAAK,WAAW,KAC1B,KAAU;;AAGZ,UAAO;WACA,GAAK;AAIZ,UAHA,QAAQ,MAAM,0BAA0B,EAAI,EAE5C,EADgB,aAAe,QAAQ,EAAI,UAAU,wBACpC,EACV,EAAE;YACD;AACR,KAAa,GAAM;;IAGvB,CAAC,EAAS,CACX;AAWD,QARA,cACe;AACX,EAAI,EAAc,WAChB,aAAa,EAAc,QAAQ;IAGtC,EAAE,CAAC,EAEC;EACL;EACA;EACA;EACA;EACA;EACA,oBAAoB,EAAW,EAAE,CAAC;EACnC"}
1
+ {"version":3,"file":"useUserSearch.js","names":["NotificationOps.SearchUsersDocument","useUserSearch","useNotification","isLoading","setIsLoading","useState","error","setError","results","setResults","debounceTimer","useRef","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","runQuery","SearchUsersDocument","filter","u","searchUsers","query","extraFilter","users","err","fetchAllUsers","offset","hasMore","allUsers","page","message","useEffect"],"sources":["../../src/hooks/useUserSearch.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport * as NotificationOps from '../generated/global-operations';\nimport type { SearchUsersQuery } from '../generated/global-operations';\n\nexport interface User {\n id: string;\n name: string;\n email: string;\n phoneNumber?: string;\n role?: string;\n status?: string;\n username?: string;\n}\n\nexport interface UserSearchFilter {\n search?: string;\n role?: string;\n status?: string;\n}\n\n/**\n * Hook for searching users via the global auth service.\n * Uses the Apollo client from notification context (not raw fetch).\n */\nexport function useUserSearch() {\n const { authToken, apiGatewayUrl } = useNotification();\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [results, setResults] = useState<User[]>([]);\n const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Debounced search function\n const runQuery = useCallback(\n async (filter: UserSearchFilter, limit = 10, offset = 0): Promise<User[]> => {\n const client = getClient();\n const result = await client.query<SearchUsersQuery>({\n query: NotificationOps.SearchUsersDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search.trim() } : {}),\n ...(filter.role ? { role: filter.role } : {}),\n ...(filter.status ? { status: filter.status } : {}),\n },\n pagination: { limit, offset },\n },\n fetchPolicy: 'network-only',\n });\n\n return (result.data?.users?.users || []).map((u) => ({\n id: u.id,\n name: u.name || '',\n email: u.email,\n phoneNumber: u.phoneNumber ?? undefined,\n role: (u as { role?: string }).role,\n status: (u as { status?: string }).status,\n username: u.username,\n }));\n },\n [getClient]\n );\n\n const searchUsers = useCallback(\n (query: string, extraFilter?: Omit<UserSearchFilter, 'search'>) => {\n if (debounceTimer.current) {\n clearTimeout(debounceTimer.current);\n }\n\n if (!query.trim() && !extraFilter?.role && !extraFilter?.status) {\n setResults([]);\n return;\n }\n\n debounceTimer.current = setTimeout(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const users = await runQuery({ search: query.trim(), ...extraFilter }, 20, 0);\n setResults(users);\n } catch (err) {\n console.error('User search error:', err);\n setError(err instanceof Error ? err.message : 'Failed to search users');\n setResults([]);\n } finally {\n setIsLoading(false);\n }\n }, 300);\n },\n [runQuery]\n );\n\n const fetchAllUsers = useCallback(\n async (filter: UserSearchFilter): Promise<User[]> => {\n setIsLoading(true);\n setError(null);\n\n try {\n const pageSize = 100;\n let offset = 0;\n let hasMore = true;\n const allUsers: User[] = [];\n\n while (hasMore) {\n const page = await runQuery(filter, pageSize, offset);\n allUsers.push(...page);\n hasMore = page.length === pageSize;\n offset += pageSize;\n }\n\n return allUsers;\n } catch (err) {\n console.error('Fetch all users error:', err);\n const message = err instanceof Error ? err.message : 'Failed to fetch users';\n setError(message);\n return [];\n } finally {\n setIsLoading(false);\n }\n },\n [runQuery]\n );\n\n // Clear timer on unmount\n useEffect(() => {\n return () => {\n if (debounceTimer.current) {\n clearTimeout(debounceTimer.current);\n }\n };\n }, []);\n\n return {\n searchUsers,\n fetchAllUsers,\n results,\n isLoading,\n error,\n clearResults: () => setResults([]),\n };\n}\n"],"mappings":";;;;;AA0BA,SAAgBC,IAAgB;CAC9B,IAAM,EAAE,cAAW,qBAAkBC,EAAgB,GAC/C,CAACC,GAAWC,KAAgBC,EAAS,EAAK,GAC1C,CAACC,GAAOC,KAAYF,EAAwB,IAAI,GAChD,CAACG,GAASC,KAAcJ,EAAiB,CAAC,CAAC,GAC3CK,IAAgBC,EAA6C,IAAI,GAEjEC,IAAYC,QACTC,EAA4BC,KAAiB,KAAA,GAAWC,KAAa,KAAA,CAAS,GACpF,CAACD,GAAeC,CAAS,CAAC,GAGvBC,IAAWJ,EACf,OAAO,GAA0B,IAAQ,IAAI,IAAS,QAe5C,MAdOD,EACM,CAAA,CAAO,MAAwB;EAClD,OAAOZ;EACP,WAAW;GACT,QAAQ;IACN,GAAImB,EAAO,SAAS,EAAE,QAAQA,EAAO,OAAO,KAAK,EAAE,IAAI,CAAC;IACxD,GAAIA,EAAO,OAAO,EAAE,MAAMA,EAAO,KAAK,IAAI,CAAC;IAC3C,GAAIA,EAAO,SAAS,EAAE,QAAQA,EAAO,OAAO,IAAI,CAAC;GACnD;GACA,YAAY;IAAE;IAAO;GAAO;EAC9B;EACA,aAAa;CACf,CAAC,EAAA,CAEc,MAAM,OAAO,SAAS,C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wB,CAAO,GACT,CAAC;EACV,UAAU;GACR,EAAa,EAAK;EACpB;CACF,GACA,CAACd,CAAQ,CACX;CAWA,OARAe,cACe;EACX,AAAItB,EAAc,WAChB,aAAaA,EAAc,OAAO;CAEtC,GACC,CAAC,CAAC,GAEE;EACL;EACA;EACA;EACA;EACA;EACA,oBAAoBD,EAAW,CAAC,CAAC;CACnC;AACF"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Notification Microfrontend
3
+ *
4
+ * Provides a UI for managing multi-channel notifications,
5
+ * notification history, and notification templates.
6
+ * This is a GLOBAL module that integrates with the global API gateway (gw-global.local.burdenoff.com).
7
+ *
8
+ * @example
9
+ * ```tsx
10
+ * import { NotificationRoot, type NotificationRootProps } from '@burdenoff/micro-fe/notification';
11
+ *
12
+ * function App() {
13
+ * const props: NotificationRootProps = {
14
+ * basePath: '/notifications',
15
+ * navigate: (path) => router.push(path),
16
+ * currentUser: { id: '1', email: 'user@example.com' },
17
+ * workspaceId: 'ws-123',
18
+ * apiGatewayUrl: 'https://gw-global.local.burdenoff.com/global/graphql',
19
+ * authToken: 'token',
20
+ * registerNavItems: (items) => { return () => {}; },
21
+ * onNotificationClick: (notification) => console.log('Clicked:', notification),
22
+ * };
23
+ *
24
+ * return <NotificationRoot {...props} />;
25
+ * }
26
+ * ```
27
+ *
28
+ * @module @burdenoff/micro-fe/notification
29
+ */
30
+ export { NotificationRoot } from './NotificationRoot';
31
+ export { UserNotificationRoot } from './UserNotificationRoot';
32
+ export { AdminNotificationRoot } from './AdminNotificationRoot';
33
+ export type { NotificationRootProps, NavItem, FooterItem, Notification, NotificationType, NotificationPriority, NotificationStatus, NotificationChannel, NotificationTemplate, NotificationFilter, } from './types';
34
+ export { useNotifications, useNotificationStore, useNotification } from './hooks';
35
+ export { NotificationBell, NotificationCard, NotificationPanel } from './components';
36
+ export { formatRelativeTime, getPriorityColor, getPriorityIcon, getNotificationTypeLabel, getNotificationTypeIcon, filterNotifications, sortNotificationsByDate, groupNotificationsByDate, truncateText, validateTemplateVariables, substituteTemplateVariables, } from './utils';
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { useNotification as e } from "./providers/NotificationProvider.js";
2
2
  import { useNotificationStore as t } from "./store/notificationStore.js";
3
3
  import { useNotifications as n } from "./hooks/useNotifications.js";
4
- import { filterNotifications as r, formatRelativeTime as i, getNotificationTypeIcon as a, getNotificationTypeLabel as o, getPriorityColor as s, getPriorityIcon as c, groupNotificationsByDate as l, sortNotificationsByDate as u, substituteTemplateVariables as d, truncateText as f, validateTemplateVariables as p } from "./utils/index.js";
4
+ import { NotificationRoot as r } from "./NotificationRoot.js";
5
+ import { UserNotificationRoot as i } from "./UserNotificationRoot.js";
6
+ import { NotificationCard as a } from "./components/NotificationCard.js";
7
+ import { AdminNotificationRoot as o } from "./AdminNotificationRoot.js";
5
8
  import "./hooks/index.js";
6
- import { NotificationCard as m } from "./components/NotificationCard.js";
7
- import { NotificationRoot as h } from "./NotificationRoot.js";
8
- import { UserNotificationRoot as g } from "./UserNotificationRoot.js";
9
- import { AdminNotificationRoot as _ } from "./AdminNotificationRoot.js";
10
- import { NotificationBell as v } from "./components/NotificationBell.js";
11
- import { NotificationPanel as y } from "./components/NotificationPanel.js";
12
9
  import "./components/index.js";
13
- export { _ as AdminNotificationRoot, v as NotificationBell, m as NotificationCard, y as NotificationPanel, h as NotificationRoot, g as UserNotificationRoot, r as filterNotifications, i as formatRelativeTime, a as getNotificationTypeIcon, o as getNotificationTypeLabel, s as getPriorityColor, c as getPriorityIcon, l as groupNotificationsByDate, u as sortNotificationsByDate, d as substituteTemplateVariables, f as truncateText, e as useNotification, t as useNotificationStore, n as useNotifications, p as validateTemplateVariables };
10
+ import { NotificationBell as s } from "./components/NotificationBell.js";
11
+ import { NotificationPanel as c } from "./components/NotificationPanel.js";
12
+ import { filterNotifications as l, formatRelativeTime as u, getNotificationTypeIcon as d, getNotificationTypeLabel as f, getPriorityColor as p, getPriorityIcon as m, groupNotificationsByDate as h, sortNotificationsByDate as g, substituteTemplateVariables as _, truncateText as v, validateTemplateVariables as y } from "./utils/index.js";
13
+ export { o as AdminNotificationRoot, s as NotificationBell, a as NotificationCard, c as NotificationPanel, r as NotificationRoot, i as UserNotificationRoot, l as filterNotifications, u as formatRelativeTime, d as getNotificationTypeIcon, f as getNotificationTypeLabel, p as getPriorityColor, m as getPriorityIcon, h as groupNotificationsByDate, g as sortNotificationsByDate, _ as substituteTemplateVariables, v as truncateText, e as useNotification, t as useNotificationStore, n as useNotifications, y as validateTemplateVariables };
@@ -1,5 +1,5 @@
1
1
  import { brand as e, isBranded as t } from "./utils.js";
2
- //#region node_modules/@apollo/client/errors/CombinedGraphQLErrors.js
2
+ // node_modules/@apollo/client/errors/CombinedGraphQLErrors.js
3
3
  function n(e) {
4
4
  return e.filter((e) => e).map((e) => e.message || "Error message not found.").join("\n");
5
5
  }
@@ -18,7 +18,6 @@ var r = class r extends Error {
18
18
  })), this.errors = i, this.data = t.data, this.extensions = t.extensions, this.name = "CombinedGraphQLErrors", e(this), Object.setPrototypeOf(this, r.prototype);
19
19
  }
20
20
  };
21
- //#endregion
22
21
  export { r as CombinedGraphQLErrors };
23
22
 
24
23
  //# sourceMappingURL=CombinedGraphQLErrors.js.map