@burdenoff/microfe-notification 2026.1029.2 → 2026.1113.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AdminNotificationRoot.d.ts +33 -0
- package/dist/AdminNotificationRoot.js +9 -6
- package/dist/AdminNotificationRoot.js.map +1 -1
- package/dist/AdminNotificationRoutes.d.ts +1 -0
- package/dist/AdminNotificationRoutes.js +22 -23
- package/dist/AdminNotificationRoutes.js.map +1 -1
- package/dist/NotificationRoot.d.ts +29 -0
- package/dist/NotificationRoot.js +9 -6
- package/dist/NotificationRoot.js.map +1 -1
- package/dist/NotificationRoutes.d.ts +18 -0
- package/dist/NotificationRoutes.js +109 -38
- package/dist/NotificationRoutes.js.map +1 -1
- package/dist/UserNotificationRoot.d.ts +32 -0
- package/dist/UserNotificationRoot.js +9 -6
- package/dist/UserNotificationRoot.js.map +1 -1
- package/dist/UserNotificationRoutes.d.ts +16 -0
- package/dist/UserNotificationRoutes.js +9 -10
- package/dist/UserNotificationRoutes.js.map +1 -1
- package/dist/components/ConfirmDeleteDialog.d.ts +17 -0
- package/dist/components/ConfirmDeleteDialog.js +22 -0
- package/dist/components/ConfirmDeleteDialog.js.map +1 -0
- package/dist/components/FeatureDisabledPage.d.ts +6 -0
- package/dist/components/FeatureDisabledPage.js +1 -2
- package/dist/components/FeatureDisabledPage.js.map +1 -1
- package/dist/components/NotificationBell.d.ts +13 -0
- package/dist/components/NotificationBell.js +6 -7
- package/dist/components/NotificationBell.js.map +1 -1
- package/dist/components/NotificationCard.d.ts +27 -0
- package/dist/components/NotificationCard.js +106 -76
- package/dist/components/NotificationCard.js.map +1 -1
- package/dist/components/NotificationPanel.d.ts +10 -0
- package/dist/components/NotificationPanel.js +5 -6
- package/dist/components/NotificationPanel.js.map +1 -1
- package/dist/components/RecipientSelector.d.ts +32 -0
- package/dist/components/RecipientSelector.js +2 -3
- package/dist/components/RecipientSelector.js.map +1 -1
- package/dist/components/TemplatePreview.d.ts +21 -0
- package/dist/components/TemplatePreview.js +3 -4
- package/dist/components/TemplatePreview.js.map +1 -1
- package/dist/components/VariableInserter.d.ts +11 -0
- package/dist/components/index.d.ts +3 -0
- package/dist/components/index.js +4 -3
- package/dist/constants/permissions.d.ts +23 -0
- package/dist/constants/permissions.js +1 -2
- package/dist/constants/permissions.js.map +1 -1
- package/dist/dev/main.d.ts +0 -0
- package/dist/generated/global-operations.d.ts +2119 -0
- package/dist/generated/global-operations.js +80 -69
- package/dist/generated/global-operations.js.map +1 -1
- package/dist/generated/global-types.d.ts +23507 -0
- package/dist/generated/wspace-operations.d.ts +4 -0
- package/dist/generated/wspace-types.d.ts +57831 -0
- package/dist/graphql/global-client.d.ts +32 -0
- package/dist/graphql/global-client.js +23 -30
- package/dist/graphql/global-client.js.map +1 -1
- package/dist/hooks/index.d.ts +7 -0
- package/dist/hooks/index.js +7 -6
- package/dist/hooks/useNotificationAdmin.d.ts +46 -0
- package/dist/hooks/useNotificationAdmin.js +18 -17
- package/dist/hooks/useNotificationAdmin.js.map +1 -1
- package/dist/hooks/useNotificationAnalytics.d.ts +65 -0
- package/dist/hooks/useNotificationAnalytics.js +1 -2
- package/dist/hooks/useNotificationAnalytics.js.map +1 -1
- package/dist/hooks/useNotificationPreferences.d.ts +10 -0
- package/dist/hooks/useNotificationPreferences.js +7 -7
- package/dist/hooks/useNotificationPreferences.js.map +1 -1
- package/dist/hooks/useNotificationTemplates.d.ts +131 -0
- package/dist/hooks/useNotificationTemplates.js +1 -2
- package/dist/hooks/useNotificationTemplates.js.map +1 -1
- package/dist/hooks/useNotificationTopics.d.ts +35 -0
- package/dist/hooks/useNotificationTopics.js +22 -22
- package/dist/hooks/useNotificationTopics.js.map +1 -1
- package/dist/hooks/useNotifications.d.ts +39 -0
- package/dist/hooks/useNotifications.js +6 -4
- package/dist/hooks/useNotifications.js.map +1 -1
- package/dist/hooks/usePreferenceToggles.d.ts +27 -0
- package/dist/hooks/usePreferenceToggles.js +84 -0
- package/dist/hooks/usePreferenceToggles.js.map +1 -0
- package/dist/hooks/useSendNotification.d.ts +158 -0
- package/dist/hooks/useSendNotification.js +12 -10
- package/dist/hooks/useSendNotification.js.map +1 -1
- package/dist/hooks/useUserSearch.d.ts +26 -0
- package/dist/hooks/useUserSearch.js +8 -10
- package/dist/hooks/useUserSearch.js.map +1 -1
- package/dist/index.d.ts +36 -0
- package/dist/index.js +8 -8
- package/dist/navigation-v2/AdminPageV2.d.ts +14 -0
- package/dist/navigation-v2/AdminPageV2.js +51 -0
- package/dist/navigation-v2/AdminPageV2.js.map +1 -0
- package/dist/navigation-v2/AdminToolsMenu.d.ts +6 -0
- package/dist/navigation-v2/AdminToolsMenu.js +32 -0
- package/dist/navigation-v2/AdminToolsMenu.js.map +1 -0
- package/dist/navigation-v2/BackToNotifications.d.ts +2 -0
- package/dist/navigation-v2/BackToNotifications.js +20 -0
- package/dist/navigation-v2/BackToNotifications.js.map +1 -0
- package/dist/navigation-v2/FilterControls.d.ts +25 -0
- package/dist/navigation-v2/FilterControls.js +64 -0
- package/dist/navigation-v2/FilterControls.js.map +1 -0
- package/dist/navigation-v2/NotificationArchivedV2.d.ts +9 -0
- package/dist/navigation-v2/NotificationArchivedV2.js +174 -0
- package/dist/navigation-v2/NotificationArchivedV2.js.map +1 -0
- package/dist/navigation-v2/NotificationInboxV2.d.ts +9 -0
- package/dist/navigation-v2/NotificationInboxV2.js +309 -0
- package/dist/navigation-v2/NotificationInboxV2.js.map +1 -0
- package/dist/navigation-v2/NotificationSettingsV2.d.ts +9 -0
- package/dist/navigation-v2/NotificationSettingsV2.js +203 -0
- package/dist/navigation-v2/NotificationSettingsV2.js.map +1 -0
- package/dist/navigation-v2/NotificationsV2Landing.d.ts +9 -0
- package/dist/navigation-v2/NotificationsV2Landing.js +37 -0
- package/dist/navigation-v2/NotificationsV2Landing.js.map +1 -0
- package/dist/navigation-v2/__tests__/uiMocks.d.ts +71 -0
- package/dist/navigation-v2/inboxFilters.d.ts +8 -0
- package/dist/navigation-v2/inboxFilters.js +10 -0
- package/dist/navigation-v2/inboxFilters.js.map +1 -0
- package/dist/navigation-v2/paths.d.ts +24 -0
- package/dist/navigation-v2/paths.js +31 -0
- package/dist/navigation-v2/paths.js.map +1 -0
- package/dist/navigation-v2/settingsOptions.d.ts +12 -0
- package/dist/navigation-v2/settingsOptions.js +58 -0
- package/dist/navigation-v2/settingsOptions.js.map +1 -0
- package/dist/navigation-v2/useAdminTools.d.ts +22 -0
- package/dist/navigation-v2/useAdminTools.js +76 -0
- package/dist/navigation-v2/useAdminTools.js.map +1 -0
- package/dist/node_modules/@apollo/client/errors/CombinedGraphQLErrors.js +1 -2
- package/dist/node_modules/@apollo/client/errors/CombinedGraphQLErrors.js.map +1 -1
- package/dist/node_modules/@apollo/client/errors/utils.js +1 -2
- package/dist/node_modules/@apollo/client/errors/utils.js.map +1 -1
- package/dist/node_modules/@apollo/client/link/core/ApolloLink.js +7 -8
- package/dist/node_modules/@apollo/client/link/core/ApolloLink.js.map +1 -1
- package/dist/node_modules/@apollo/client/link/subscriptions/index.js +9 -10
- package/dist/node_modules/@apollo/client/link/subscriptions/index.js.map +1 -1
- package/dist/node_modules/@apollo/client/link/utils/createOperation.js +5 -6
- package/dist/node_modules/@apollo/client/link/utils/createOperation.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/caching/sizes.js +0 -1
- package/dist/node_modules/@apollo/client/utilities/caching/sizes.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/graphql/print.js +4 -5
- package/dist/node_modules/@apollo/client/utilities/graphql/print.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/caches.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/caches.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/checkDocument.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/checkDocument.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/getMainDefinition.js +2 -3
- package/dist/node_modules/@apollo/client/utilities/internal/getMainDefinition.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/getMemoryInternals.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/getMemoryInternals.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/getOperationDefinition.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/getOperationDefinition.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/getOperationName.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/getOperationName.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/globals/global.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/globals/global.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/globals/maybe.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/globals/maybe.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/isNonNullObject.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/isNonNullObject.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/makeUniqueId.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/makeUniqueId.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/memoize.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/memoize.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/internal/stringifyForDisplay.js +1 -2
- package/dist/node_modules/@apollo/client/utilities/internal/stringifyForDisplay.js.map +1 -1
- package/dist/node_modules/@apollo/client/utilities/invariant/index.js +2 -3
- package/dist/node_modules/@apollo/client/utilities/invariant/index.js.map +1 -1
- package/dist/node_modules/@apollo/client/version.js +2 -3
- package/dist/node_modules/@apollo/client/version.js.map +1 -1
- package/dist/node_modules/@wry/caches/lib/weak.js +1 -2
- package/dist/node_modules/@wry/caches/lib/weak.js.map +1 -1
- package/dist/node_modules/@wry/trie/lib/index.js +2 -3
- package/dist/node_modules/@wry/trie/lib/index.js.map +1 -1
- package/dist/node_modules/graphql-ws/dist/client.js +76 -69
- package/dist/node_modules/graphql-ws/dist/client.js.map +1 -1
- package/dist/node_modules/graphql-ws/dist/common-CGW11Fyb.js +2 -3
- package/dist/node_modules/graphql-ws/dist/common-CGW11Fyb.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/NotificationFactories.js +2 -3
- package/dist/node_modules/rxjs/dist/esm5/internal/NotificationFactories.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/Observable.js +41 -42
- package/dist/node_modules/rxjs/dist/esm5/internal/Observable.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/Subscriber.js +14 -15
- package/dist/node_modules/rxjs/dist/esm5/internal/Subscriber.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/Subscription.js +21 -18
- package/dist/node_modules/rxjs/dist/esm5/internal/Subscription.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/config.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/config.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/observable/empty.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/observable/empty.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js +2 -3
- package/dist/node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/symbol/observable.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/symbol/observable.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/arrRemove.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/arrRemove.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/errorContext.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/errorContext.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/identity.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/identity.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/isFunction.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/isFunction.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/noop.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/noop.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/pipe.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/pipe.js.map +1 -1
- package/dist/node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js +1 -2
- package/dist/node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js.map +1 -1
- package/dist/node_modules/{rxjs/node_modules/tslib → tslib}/tslib.es6.js +1 -2
- package/dist/node_modules/tslib/tslib.es6.js.map +1 -0
- package/dist/pages/CreateNotificationPage.d.ts +5 -0
- package/dist/pages/CreateNotificationPage.js +591 -573
- package/dist/pages/CreateNotificationPage.js.map +1 -1
- package/dist/pages/NotificationCenterPage.d.ts +8 -0
- package/dist/pages/NotificationCenterPage.js +87 -83
- package/dist/pages/NotificationCenterPage.js.map +1 -1
- package/dist/pages/NotificationHistoryAdminPage.d.ts +2 -0
- package/dist/pages/NotificationHistoryAdminPage.js +7 -8
- package/dist/pages/NotificationHistoryAdminPage.js.map +1 -1
- package/dist/pages/NotificationHistoryPage.d.ts +6 -0
- package/dist/pages/NotificationHistoryPage.js +59 -55
- package/dist/pages/NotificationHistoryPage.js.map +1 -1
- package/dist/pages/NotificationLandingPage.d.ts +10 -0
- package/dist/pages/NotificationLandingPage.js +5 -6
- package/dist/pages/NotificationLandingPage.js.map +1 -1
- package/dist/pages/NotificationPreferencesPage.d.ts +5 -0
- package/dist/pages/NotificationPreferencesPage.js +97 -159
- package/dist/pages/NotificationPreferencesPage.js.map +1 -1
- package/dist/pages/NotificationTemplatesPage.d.ts +7 -0
- package/dist/pages/NotificationTemplatesPage.js +192 -172
- package/dist/pages/NotificationTemplatesPage.js.map +1 -1
- package/dist/pages/NotificationTopicsPage.d.ts +1 -0
- package/dist/pages/NotificationTopicsPage.js +126 -112
- package/dist/pages/NotificationTopicsPage.js.map +1 -1
- package/dist/pages/TemplateEditorPage.d.ts +12 -0
- package/dist/pages/TemplateEditorPage.js +381 -341
- package/dist/pages/TemplateEditorPage.js.map +1 -1
- package/dist/providers/NotificationProvider.d.ts +11 -0
- package/dist/providers/NotificationProvider.js +7 -7
- package/dist/providers/NotificationProvider.js.map +1 -1
- package/dist/shared/hooks/useTr.d.ts +13 -0
- package/dist/shared/hooks/useTr.js +1 -2
- package/dist/shared/hooks/useTr.js.map +1 -1
- package/dist/store/notificationStore.d.ts +30 -0
- package/dist/store/notificationStore.js +1 -2
- package/dist/store/notificationStore.js.map +1 -1
- package/dist/test/happydom.d.ts +1 -0
- package/dist/translations/en.d.ts +468 -0
- package/dist/types/index.d.ts +257 -0
- package/dist/utils/inAppNavigation.d.ts +37 -0
- package/dist/utils/inAppNavigation.js +2 -3
- package/dist/utils/inAppNavigation.js.map +1 -1
- package/dist/utils/index.d.ts +68 -0
- package/dist/utils/index.js +1 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/nativeBridge.d.ts +2 -0
- package/dist/utils/nativeBridge.js +1 -2
- package/dist/utils/notificationHistoryExport.d.ts +12 -0
- package/dist/utils/notificationHistoryExport.js +1 -2
- package/dist/utils/notificationHistoryExport.js.map +1 -1
- package/package.json +67 -49
- 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,IAAI,EAAE;EACN,MAAM,EAAoB,EAAE,KAAK;EACjC,UAAU,EAAY,EAAE,SAAS;EACjC,OAAO,EAAE;EACT,MAAM,EAAE;EACR,WAAW,EAAE,eAAe,KAAA;EAC5B,UAAU,EAAE,WAAW,EAAE,EAAE,KAAK,OAAY;GAC1C,IAAI,EAAO;GACX,OA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,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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AAa,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,27 @@
|
|
|
1
|
+
import { NotificationChannel, NotificationPreferenceScope, NotificationType } from '../types';
|
|
2
|
+
export interface PreferenceTarget {
|
|
3
|
+
scope: NotificationPreferenceScope;
|
|
4
|
+
channel?: NotificationChannel;
|
|
5
|
+
type?: NotificationType;
|
|
6
|
+
topicId?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface PreferenceFeedback {
|
|
9
|
+
key: string;
|
|
10
|
+
type: 'success' | 'error';
|
|
11
|
+
message: string;
|
|
12
|
+
}
|
|
13
|
+
/** The key a preference is stored under: the same as the backend's `preferenceKey`. */
|
|
14
|
+
export declare function preferenceKey(input: PreferenceTarget): string;
|
|
15
|
+
/**
|
|
16
|
+
* Toggling and resetting one notification preference, with the saved/failed
|
|
17
|
+
* status line. Shared by the classic Preferences page and FluidGrids'
|
|
18
|
+
* Notification settings (BOFF-11872) so both make exactly the same calls.
|
|
19
|
+
*/
|
|
20
|
+
export declare function usePreferenceToggles(): {
|
|
21
|
+
preferencesByKey: Map<string, import('../types').NotificationPreference>;
|
|
22
|
+
preferencesLoading: boolean;
|
|
23
|
+
savingKey: string | null;
|
|
24
|
+
saveFeedback: PreferenceFeedback | null;
|
|
25
|
+
togglePreference: (input: PreferenceTarget) => Promise<void>;
|
|
26
|
+
resetPreference: (key: string) => Promise<void>;
|
|
27
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { useNotificationPreferences as e } from "./useNotificationPreferences.js";
|
|
2
|
+
import { useNotificationAnalytics as t } from "./useNotificationAnalytics.js";
|
|
3
|
+
import { useTr as n } from "../shared/hooks/useTr.js";
|
|
4
|
+
import { nativeImpact as r, nativeNotify as i } from "../utils/nativeBridge.js";
|
|
5
|
+
import { useEffect as a, useRef as o, useState as s } from "react";
|
|
6
|
+
// src/hooks/usePreferenceToggles.ts
|
|
7
|
+
function c(e) {
|
|
8
|
+
return e.scope === "CHANNEL" ? `CHANNEL:${e.channel || ""}` : e.scope === "TYPE" ? `TYPE:${e.type || ""}` : e.scope === "TOPIC" ? `TOPIC:${e.topicId || ""}` : "GLOBAL";
|
|
9
|
+
}
|
|
10
|
+
function l() {
|
|
11
|
+
let l = n(), { preferencesByKey: u, isLoading: d, setPreference: f, deletePreference: p } = e(), { trackPreferenceUpdated: m } = t(), [h, g] = s(null), [_, v] = s(null), y = o(null);
|
|
12
|
+
a(() => () => {
|
|
13
|
+
y.current && clearTimeout(y.current);
|
|
14
|
+
}, []);
|
|
15
|
+
let b = (e) => {
|
|
16
|
+
y.current && clearTimeout(y.current), v(e), y.current = setTimeout(() => {
|
|
17
|
+
v((t) => t?.key === e.key ? null : t), y.current = null;
|
|
18
|
+
}, 2500);
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
preferencesByKey: u,
|
|
22
|
+
preferencesLoading: d,
|
|
23
|
+
savingKey: h,
|
|
24
|
+
saveFeedback: _,
|
|
25
|
+
togglePreference: async (e) => {
|
|
26
|
+
let t = c(e), n = u.get(t), a = !(n?.enabled ?? !0);
|
|
27
|
+
g(t), r("medium");
|
|
28
|
+
try {
|
|
29
|
+
await f({
|
|
30
|
+
...e,
|
|
31
|
+
enabled: a,
|
|
32
|
+
frequency: n?.frequency || "IMMEDIATE"
|
|
33
|
+
}), m({
|
|
34
|
+
action: "set",
|
|
35
|
+
scope: e.scope,
|
|
36
|
+
channel: e.channel,
|
|
37
|
+
type: e.type,
|
|
38
|
+
enabled: a
|
|
39
|
+
}), b({
|
|
40
|
+
key: t,
|
|
41
|
+
type: "success",
|
|
42
|
+
message: l("notifications.preferenceSaved", "Preference saved.")
|
|
43
|
+
}), i("success");
|
|
44
|
+
} catch {
|
|
45
|
+
b({
|
|
46
|
+
key: t,
|
|
47
|
+
type: "error",
|
|
48
|
+
message: l("notifications.preferenceSaveFailed", "Could not save preference.")
|
|
49
|
+
}), i("error");
|
|
50
|
+
} finally {
|
|
51
|
+
g(null);
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
resetPreference: async (e) => {
|
|
55
|
+
let t = u.get(e);
|
|
56
|
+
if (t) {
|
|
57
|
+
g(e);
|
|
58
|
+
try {
|
|
59
|
+
await p(t.id), m({
|
|
60
|
+
action: "reset",
|
|
61
|
+
scope: t.scope,
|
|
62
|
+
channel: t.channel,
|
|
63
|
+
type: t.type
|
|
64
|
+
}), b({
|
|
65
|
+
key: e,
|
|
66
|
+
type: "success",
|
|
67
|
+
message: l("notifications.preferenceReset", "Preference reset.")
|
|
68
|
+
});
|
|
69
|
+
} catch {
|
|
70
|
+
b({
|
|
71
|
+
key: e,
|
|
72
|
+
type: "error",
|
|
73
|
+
message: l("notifications.preferenceResetFailed", "Could not reset preference.")
|
|
74
|
+
});
|
|
75
|
+
} finally {
|
|
76
|
+
g(null);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export { c as preferenceKey, l as usePreferenceToggles };
|
|
83
|
+
|
|
84
|
+
//# sourceMappingURL=usePreferenceToggles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usePreferenceToggles.js","names":["preferenceKey","input","usePreferenceToggles","tr","useTr","preferencesLoading","useNotificationPreferences","useNotificationAnalytics","savingKey","setSavingKey","useState","saveFeedback","setSaveFeedback","feedbackTimerRef","useRef","showSaveFeedback","feedback","current","key","existing","preferencesByKey","nextEnabled","nativeImpact","setPreference","trackPreferenceUpdated","nativeNotify","deletePreference"],"sources":["../../src/hooks/usePreferenceToggles.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport { useNotificationPreferences } from './useNotificationPreferences';\nimport { useNotificationAnalytics } from './useNotificationAnalytics';\nimport { useTr } from '../shared/hooks/useTr';\nimport type { NotificationChannel, NotificationPreferenceScope, NotificationType } from '../types';\nimport { nativeImpact, nativeNotify } from '../utils/nativeBridge';\n\nexport interface PreferenceTarget {\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n}\n\nexport interface PreferenceFeedback {\n key: string;\n type: 'success' | 'error';\n message: string;\n}\n\n/** The key a preference is stored under: the same as the backend's `preferenceKey`. */\nexport function preferenceKey(input: PreferenceTarget): string {\n if (input.scope === 'CHANNEL') return `CHANNEL:${input.channel || ''}`;\n if (input.scope === 'TYPE') return `TYPE:${input.type || ''}`;\n if (input.scope === 'TOPIC') return `TOPIC:${input.topicId || ''}`;\n return 'GLOBAL';\n}\n\n/**\n * Toggling and resetting one notification preference, with the saved/failed\n * status line. Shared by the classic Preferences page and FluidGrids'\n * Notification settings (BOFF-11872) so both make exactly the same calls.\n */\nexport function usePreferenceToggles() {\n const tr = useTr();\n const {\n preferencesByKey,\n isLoading: preferencesLoading,\n setPreference,\n deletePreference,\n } = useNotificationPreferences();\n const { trackPreferenceUpdated } = useNotificationAnalytics();\n const [savingKey, setSavingKey] = useState<string | null>(null);\n const [saveFeedback, setSaveFeedback] = useState<PreferenceFeedback | null>(null);\n const feedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (feedbackTimerRef.current) {\n clearTimeout(feedbackTimerRef.current);\n }\n };\n }, []);\n\n const showSaveFeedback = (feedback: PreferenceFeedback) => {\n if (feedbackTimerRef.current) {\n clearTimeout(feedbackTimerRef.current);\n }\n\n setSaveFeedback(feedback);\n feedbackTimerRef.current = setTimeout(() => {\n setSaveFeedback((current) => (current?.key === feedback.key ? null : current));\n feedbackTimerRef.current = null;\n }, 2500);\n };\n\n const togglePreference = async (input: PreferenceTarget) => {\n const key = preferenceKey(input);\n const existing = preferencesByKey.get(key);\n const nextEnabled = !(existing?.enabled ?? true);\n setSavingKey(key);\n nativeImpact('medium');\n try {\n await setPreference({\n ...input,\n enabled: nextEnabled,\n frequency: existing?.frequency || 'IMMEDIATE',\n });\n trackPreferenceUpdated({\n action: 'set',\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n enabled: nextEnabled,\n });\n showSaveFeedback({\n key,\n type: 'success',\n message: tr('notifications.preferenceSaved', 'Preference saved.'),\n });\n void nativeNotify('success');\n } catch {\n showSaveFeedback({\n key,\n type: 'error',\n message: tr('notifications.preferenceSaveFailed', 'Could not save preference.'),\n });\n void nativeNotify('error');\n } finally {\n setSavingKey(null);\n }\n };\n\n const resetPreference = async (key: string) => {\n const existing = preferencesByKey.get(key);\n if (!existing) return;\n setSavingKey(key);\n try {\n await deletePreference(existing.id);\n trackPreferenceUpdated({\n action: 'reset',\n scope: existing.scope,\n channel: existing.channel,\n type: existing.type,\n });\n showSaveFeedback({\n key,\n type: 'success',\n message: tr('notifications.preferenceReset', 'Preference reset.'),\n });\n } catch {\n showSaveFeedback({\n key,\n type: 'error',\n message: tr('notifications.preferenceResetFailed', 'Could not reset preference.'),\n });\n } finally {\n setSavingKey(null);\n }\n };\n\n return {\n preferencesByKey,\n preferencesLoading,\n savingKey,\n saveFeedback,\n togglePreference,\n resetPreference,\n };\n}\n"],"mappings":";;;;;;AAqBA,SAAgBA,EAAc,GAAiC;CAI7D,OAHIC,EAAM,UAAU,YAAkB,WAAWA,EAAM,WAAW,OAC9DA,EAAM,UAAU,SAAe,QAAQA,EAAM,QAAQ,OACrDA,EAAM,UAAU,UAAgB,SAASA,EAAM,WAAW,OACvD;AACT;AAOA,SAAgBC,IAAuB;CACrC,IAAMC,IAAKC,EAAM,GACX,EACJ,qBACA,WAAWC,GACX,kBACA,wBACEC,EAA2B,GACzB,EAAE,8BAA2BC,EAAyB,GACtD,CAACC,GAAWC,KAAgBC,EAAwB,IAAI,G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;MACR,OAAOL,EAAS;MAChB,SAASA,EAAS;MAClB,MAAMA,EAAS;KACjB,CAAC,GACDJ,EAAiB;MACf;MACA,MAAM;MACN,SAASZ,EAAG,iCAAiC,mBAAmB;KAClE,CAAC;IACH,QAAQ;KACN,EAAiB;MACf;MACA,MAAM;MACN,SAASA,EAAG,uCAAuC,6BAA6B;KAClF,CAAC;IACH,UAAU;KACR,EAAa,IAAI;IACnB;GAtBgB;EAuBlB;CASA;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
|
-
|
|
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) =>
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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,EAAS,GAAM,EAC5C,CAAC,GAAW,KAAgB,EAAS,GAAM,EAC3C,CAAC,GAAO,KAAY,EAAwB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,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,KAAA;IACtB,OAAOA,EAAI;IACX,SAASA,EAAI;GACf;GAEA,OADAP,EAAcS,CAAY,GAC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;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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|