@burdenoff/microfe-notification 2026.1029.1 → 2026.1109.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +1 -2
- 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/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 +18 -0
- package/dist/components/NotificationCard.js +10 -11
- 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/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/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 +18 -19
- package/dist/pages/CreateNotificationPage.js.map +1 -1
- package/dist/pages/NotificationCenterPage.d.ts +6 -0
- package/dist/pages/NotificationCenterPage.js +13 -14
- 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 +2 -0
- package/dist/pages/NotificationHistoryPage.js +13 -14
- 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 +1 -0
- package/dist/pages/NotificationPreferencesPage.js +14 -15
- package/dist/pages/NotificationPreferencesPage.js.map +1 -1
- package/dist/pages/NotificationTemplatesPage.d.ts +7 -0
- package/dist/pages/NotificationTemplatesPage.js +25 -23
- package/dist/pages/NotificationTemplatesPage.js.map +1 -1
- package/dist/pages/NotificationTopicsPage.d.ts +1 -0
- package/dist/pages/NotificationTopicsPage.js +6 -7
- package/dist/pages/NotificationTopicsPage.js.map +1 -1
- package/dist/pages/TemplateEditorPage.d.ts +12 -0
- package/dist/pages/TemplateEditorPage.js +294 -285
- package/dist/pages/TemplateEditorPage.js.map +1 -1
- package/dist/providers/NotificationProvider.d.ts +11 -0
- package/dist/providers/NotificationProvider.js +1 -2
- 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 +249 -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 +16 -10
- 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 +66 -48
- package/dist/node_modules/rxjs/node_modules/tslib/tslib.es6.js.map +0 -1
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ApolloClient } from '@apollo/client';
|
|
2
|
+
/**
|
|
3
|
+
* Default Global Gateway URL
|
|
4
|
+
* Notifications are a GLOBAL service and must use the global gateway
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEFAULT_GLOBAL_GATEWAY_URL = "https://gw-global.local.burdenoff.com/global/graphql";
|
|
7
|
+
/**
|
|
8
|
+
* Get or create the singleton Apollo client for global notification operations
|
|
9
|
+
*
|
|
10
|
+
* @param globalGatewayUrl - Global Gateway GraphQL URL (default: https://gw-global.local.burdenoff.com/global/graphql)
|
|
11
|
+
* @param authToken - Optional JWT auth token
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Context for a user's own notification reads and writes.
|
|
15
|
+
*
|
|
16
|
+
* Notifications are scoped to an ORGANIZATION, and product services file a
|
|
17
|
+
* user's rows under the active workspace's organization. On the global gateway
|
|
18
|
+
* a user session's organization comes from the account token, which differs
|
|
19
|
+
* whenever the active workspace belongs to another organization the user is a
|
|
20
|
+
* member of. With this context the request also carries the shell's workspace
|
|
21
|
+
* token (when it is valid for the active workspace), so the gateway scopes it
|
|
22
|
+
* to the active workspace's organization, as the shell's notification bell
|
|
23
|
+
* does. Without a valid token the account organization applies, as before.
|
|
24
|
+
*/
|
|
25
|
+
export declare const USER_NOTIFICATION_CONTEXT: {
|
|
26
|
+
readonly preferWorkspaceAuth: true;
|
|
27
|
+
};
|
|
28
|
+
export declare function getGlobalNotificationClient(globalGatewayUrl?: string, authToken?: string): InstanceType<typeof ApolloClient>;
|
|
29
|
+
/**
|
|
30
|
+
* Reset the singleton client (useful for testing or re-initialization)
|
|
31
|
+
*/
|
|
32
|
+
export declare function resetGlobalNotificationClient(): void;
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { GraphQLWsLink as e } from "../node_modules/@apollo/client/link/subscriptions/index.js";
|
|
2
|
+
import { getMainDefinition as t } from "../node_modules/@apollo/client/utilities/internal/getMainDefinition.js";
|
|
3
3
|
import { createClient as n } from "../node_modules/graphql-ws/dist/client.js";
|
|
4
4
|
import { ApolloClient as r, ApolloLink as i, HttpLink as a, InMemoryCache as o, Observable as s, from as c, split as l } from "@apollo/client";
|
|
5
5
|
import { setContext as u } from "@apollo/client/link/context";
|
|
6
6
|
import { onError as d } from "@apollo/client/link/error";
|
|
7
7
|
import { isAuthNetworkError as f, redirectToLogin as p } from "@burdenoff/fe-libs/shared/utils";
|
|
8
8
|
import { getStoredOrganizationId as m, getStoredWorkspaceId as h, getStoredWorkspaceToken as g, isWorkspaceTokenValidForContext as _ } from "@burdenoff/fe-libs/shared/graphql";
|
|
9
|
-
|
|
9
|
+
// src/graphql/global-client.ts
|
|
10
10
|
function v(e = []) {
|
|
11
11
|
return e.some((e) => {
|
|
12
12
|
let t = typeof e.extensions?.code == "string" ? e.extensions.code : "", n = typeof e.extensions?.errorCode == "string" ? e.extensions.errorCode : "", r = (e.message ?? "").toLowerCase();
|
|
13
13
|
return t === "UNAUTHENTICATED" || n === "TOKEN_EXPIRED" || r.includes("token_expired") || r.includes("token expired") || r.includes("session expired") || r.includes("unauthorized") || r.includes("unauthenticated") || r.includes("authentication required") || r.includes("workspace context missing");
|
|
14
14
|
});
|
|
15
15
|
}
|
|
16
|
-
function y(
|
|
17
|
-
let n = e
|
|
16
|
+
function y(e) {
|
|
17
|
+
let n = t(e);
|
|
18
18
|
return n.kind === "OperationDefinition" && n.operation === "mutation";
|
|
19
19
|
}
|
|
20
20
|
function b(e) {
|
|
@@ -27,7 +27,7 @@ function x(e) {
|
|
|
27
27
|
return new s((i) => {
|
|
28
28
|
let a = n(t).subscribe({
|
|
29
29
|
next: (t) => {
|
|
30
|
-
i.next(t),
|
|
30
|
+
i.next(t), r && !b(t) && e()?.refetchQueries({ include: "active" });
|
|
31
31
|
},
|
|
32
32
|
error: (e) => {
|
|
33
33
|
i.error(e);
|
|
@@ -42,16 +42,16 @@ function x(e) {
|
|
|
42
42
|
});
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
|
-
var S = null, C = null, w = null;
|
|
46
|
-
function
|
|
45
|
+
var S = null, C = null, w = null, T = "https://gw-global.local.burdenoff.com/global/graphql";
|
|
46
|
+
function E(e) {
|
|
47
47
|
let t = e.replace(/\/$/, "");
|
|
48
48
|
return t.endsWith("/graphql") ? t : t.endsWith("/global") ? `${t}/graphql` : `${t}/global/graphql`;
|
|
49
49
|
}
|
|
50
|
-
function
|
|
50
|
+
function D(e) {
|
|
51
51
|
return e.startsWith("https://") ? e.replace("https://", "wss://") : e.startsWith("http://") ? e.replace("http://", "ws://") : e;
|
|
52
52
|
}
|
|
53
|
-
var
|
|
54
|
-
function
|
|
53
|
+
var O = { preferWorkspaceAuth: !0 };
|
|
54
|
+
function k() {
|
|
55
55
|
let e = h();
|
|
56
56
|
if (!e) return null;
|
|
57
57
|
let t = g();
|
|
@@ -60,40 +60,34 @@ function O() {
|
|
|
60
60
|
organizationId: m()
|
|
61
61
|
}) ? t : null;
|
|
62
62
|
}
|
|
63
|
-
function
|
|
64
|
-
let m =
|
|
63
|
+
function A(i, s) {
|
|
64
|
+
let m = E(i || "https://gw-global.local.burdenoff.com/global/graphql"), h = s ?? null;
|
|
65
65
|
if (S && C === m && w === h) return S;
|
|
66
66
|
C = m, w = h;
|
|
67
|
-
let g = new a({ uri: m }), _ = typeof window < "u" ? new
|
|
68
|
-
url:
|
|
67
|
+
let g = new a({ uri: m }), _ = typeof window < "u" ? new e(n({
|
|
68
|
+
url: D(m),
|
|
69
69
|
connectionParams: () => ({ authorization: s ? `Bearer ${s}` : "" }),
|
|
70
70
|
lazy: !0,
|
|
71
71
|
retryAttempts: 3
|
|
72
72
|
})) : null, y = u((e, t) => {
|
|
73
|
-
let n = t.preferWorkspaceAuth === !0 ?
|
|
73
|
+
let n = t.preferWorkspaceAuth === !0 ? k() : null;
|
|
74
74
|
return { headers: {
|
|
75
75
|
...t.headers,
|
|
76
76
|
authorization: s ? `Bearer ${s}` : "",
|
|
77
77
|
...n ? { "x-workspace-authorization": `Bearer ${n}` } : {}
|
|
78
78
|
} };
|
|
79
79
|
}), b = d(({ error: e }) => {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
e instanceof Error && f(e) && p();
|
|
86
|
-
}
|
|
87
|
-
}), D = _ ? l(({ query: t }) => {
|
|
88
|
-
let n = e(t);
|
|
80
|
+
e && (v("errors" in e && Array.isArray(e.errors) ? e.errors : []) || e instanceof Error && f(e)) && p();
|
|
81
|
+
}), T = _ ? l(({ query: e }) => {
|
|
82
|
+
let n = t(e);
|
|
89
83
|
return n.kind === "OperationDefinition" && n.operation === "subscription";
|
|
90
|
-
}, _, g) : g;
|
|
84
|
+
}, _, g) : g, O = x(() => S);
|
|
91
85
|
return S = new r({
|
|
92
86
|
link: c([
|
|
93
87
|
b,
|
|
94
|
-
|
|
88
|
+
O,
|
|
95
89
|
y,
|
|
96
|
-
|
|
90
|
+
T
|
|
97
91
|
]),
|
|
98
92
|
cache: new o({ typePolicies: {
|
|
99
93
|
Query: { fields: {
|
|
@@ -114,7 +108,6 @@ function k(i, s) {
|
|
|
114
108
|
}
|
|
115
109
|
}), S;
|
|
116
110
|
}
|
|
117
|
-
|
|
118
|
-
export { D as USER_NOTIFICATION_CONTEXT, k as getGlobalNotificationClient };
|
|
111
|
+
export { T as DEFAULT_GLOBAL_GATEWAY_URL, O as USER_NOTIFICATION_CONTEXT, A as getGlobalNotificationClient };
|
|
119
112
|
|
|
120
113
|
//# sourceMappingURL=global-client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"global-client.js","names":[],"sources":["../../src/graphql/global-client.ts"],"sourcesContent":["import {\n ApolloClient,\n ApolloLink,\n type FetchResult,\n InMemoryCache,\n HttpLink,\n Observable,\n from,\n split,\n} from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { onError } from '@apollo/client/link/error';\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { isAuthNetworkError, redirectToLogin } from '@burdenoff/fe-libs/shared/utils';\nimport {\n getStoredOrganizationId,\n getStoredWorkspaceId,\n getStoredWorkspaceToken,\n isWorkspaceTokenValidForContext,\n} from '@burdenoff/fe-libs/shared/graphql';\nimport { createClient } from 'graphql-ws';\n\nfunction hasSessionAuthErrors(\n errors: ReadonlyArray<{ message?: string; extensions?: Record<string, unknown> }> = []\n): boolean {\n return errors.some((error) => {\n const code = typeof error.extensions?.code === 'string' ? error.extensions.code : '';\n const errorCode =\n typeof error.extensions?.errorCode === 'string' ? error.extensions.errorCode : '';\n const message = (error.message ?? '').toLowerCase();\n\n return (\n code === 'UNAUTHENTICATED' ||\n errorCode === 'TOKEN_EXPIRED' ||\n message.includes('token_expired') ||\n message.includes('token expired') ||\n message.includes('session expired') ||\n message.includes('unauthorized') ||\n message.includes('unauthenticated') ||\n message.includes('authentication required') ||\n message.includes('workspace context missing')\n );\n });\n}\n\nfunction isMutationOperation(query: Parameters<typeof getMainDefinition>[0]): boolean {\n const definition = getMainDefinition(query);\n return definition.kind === 'OperationDefinition' && definition.operation === 'mutation';\n}\n\nfunction hasGraphQLResultErrors(result: FetchResult<Record<string, unknown>>): boolean {\n const errors = result.errors;\n return Array.isArray(errors) && errors.length > 0;\n}\n\nfunction createMutationAutoRefreshLink(\n getClient: () => InstanceType<typeof ApolloClient> | null\n): ApolloLink {\n return new ApolloLink((operation, forward) => {\n const shouldRefreshAfterMutation =\n isMutationOperation(operation.query) &&\n operation.getContext().autoRefreshAfterMutation !== false &&\n operation.getContext().skipMutationAutoRefresh !== true;\n\n return new Observable<FetchResult<Record<string, unknown>>>((observer) => {\n const subscription = forward(operation).subscribe({\n next: (result) => {\n observer.next(result as FetchResult<Record<string, unknown>>);\n if (!shouldRefreshAfterMutation || hasGraphQLResultErrors(result)) return;\n\n void getClient()?.refetchQueries({ include: 'active' });\n },\n error: (error: unknown) => {\n observer.error(error);\n },\n complete: () => {\n observer.complete();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n });\n });\n}\n\nlet globalClientInstance: InstanceType<typeof ApolloClient> | null = null;\nlet currentGlobalUrl: string | null = null;\nlet currentAuthToken: string | null = null;\n\n/**\n * Default Global Gateway URL\n * Notifications are a GLOBAL service and must use the global gateway\n */\nexport const DEFAULT_GLOBAL_GATEWAY_URL = 'https://gw-global.local.burdenoff.com/global/graphql';\n\nfunction toGraphqlUrl(url: string): string {\n const normalized = url.replace(/\\/$/, '');\n if (normalized.endsWith('/graphql')) return normalized;\n if (normalized.endsWith('/global')) return `${normalized}/graphql`;\n return `${normalized}/global/graphql`;\n}\n\nfunction toSubscriptionUrl(url: string): string {\n if (url.startsWith('https://')) return url.replace('https://', 'wss://');\n if (url.startsWith('http://')) return url.replace('http://', 'ws://');\n return url;\n}\n\n/**\n * Get or create the singleton Apollo client for global notification operations\n *\n * @param globalGatewayUrl - Global Gateway GraphQL URL (default: https://gw-global.local.burdenoff.com/global/graphql)\n * @param authToken - Optional JWT auth token\n */\n/**\n * Context for a user's own notification reads and writes.\n *\n * Notifications are scoped to an ORGANIZATION, and product services file a\n * user's rows under the active workspace's organization. On the global gateway\n * a user session's organization comes from the account token, which differs\n * whenever the active workspace belongs to another organization the user is a\n * member of. With this context the request also carries the shell's workspace\n * token (when it is valid for the active workspace), so the gateway scopes it\n * to the active workspace's organization, as the shell's notification bell\n * does. Without a valid token the account organization applies, as before.\n */\nexport const USER_NOTIFICATION_CONTEXT = { preferWorkspaceAuth: true } as const;\n\n/** The shell's workspace token, when it is still valid for the active workspace. */\nfunction activeWorkspaceToken(): string | null {\n const workspaceId = getStoredWorkspaceId();\n if (!workspaceId) return null;\n const token = getStoredWorkspaceToken();\n return isWorkspaceTokenValidForContext(token, {\n workspaceId,\n organizationId: getStoredOrganizationId(),\n })\n ? token\n : null;\n}\n\nexport function getGlobalNotificationClient(\n globalGatewayUrl?: string,\n authToken?: string\n): InstanceType<typeof ApolloClient> {\n const url = toGraphqlUrl(globalGatewayUrl || DEFAULT_GLOBAL_GATEWAY_URL);\n const nextAuthToken = authToken ?? null;\n\n // Return existing instance if config hasn't changed\n if (globalClientInstance && currentGlobalUrl === url && currentAuthToken === nextAuthToken) {\n return globalClientInstance;\n }\n\n // Update current config\n currentGlobalUrl = url;\n currentAuthToken = nextAuthToken;\n\n const httpLink = new HttpLink({\n uri: url,\n });\n\n const wsLink =\n typeof window !== 'undefined'\n ? new GraphQLWsLink(\n createClient({\n url: toSubscriptionUrl(url),\n connectionParams: () => ({\n authorization: authToken ? `Bearer ${authToken}` : '',\n }),\n lazy: true,\n retryAttempts: 3,\n })\n )\n : null;\n\n const authLink = setContext((_, prevContext) => {\n const workspaceToken = prevContext.preferWorkspaceAuth === true ? activeWorkspaceToken() : null;\n return {\n headers: {\n ...(prevContext.headers as Record<string, string>),\n authorization: authToken ? `Bearer ${authToken}` : '',\n ...(workspaceToken ? { 'x-workspace-authorization': `Bearer ${workspaceToken}` } : {}),\n },\n };\n });\n\n const errorLink = onError(({ error }) => {\n if (!error) return;\n\n const graphQLErrors = 'errors' in error && Array.isArray(error.errors) ? error.errors : [];\n\n if (hasSessionAuthErrors(graphQLErrors)) {\n redirectToLogin();\n return;\n }\n\n if (error instanceof Error && isAuthNetworkError(error)) {\n redirectToLogin();\n }\n });\n\n const transportLink = wsLink\n ? split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' && definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink\n )\n : httpLink;\n\n const mutationAutoRefreshLink = createMutationAutoRefreshLink(() => globalClientInstance);\n\n globalClientInstance = new ApolloClient({\n link: from([errorLink, mutationAutoRefreshLink, authLink, transportLink]),\n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n notifications: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n notificationTemplates: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n },\n },\n Notification: {\n keyFields: ['id'],\n },\n NotificationTemplate: {\n keyFields: ['id'],\n },\n },\n }),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'cache-and-network',\n },\n query: {\n fetchPolicy: 'cache-first',\n },\n mutate: {\n fetchPolicy: 'network-only',\n },\n },\n });\n\n return globalClientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing or re-initialization)\n */\nexport function resetGlobalNotificationClient(): void {\n if (globalClientInstance) {\n globalClientInstance.clearStore();\n globalClientInstance = null;\n currentGlobalUrl = null;\n currentAuthToken = null;\n }\n}\n"],"mappings":";;;;;;;;;AAuBA,SAAS,EACP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O,GAAG,EAAM,SAAS,EAAE,CAEnD,EAAE;AACvC,OAAiB;AACjB;;AAGF,GAAI,aAAiB,SAAS,EAAmB,EAAM,IACrD,GAAiB;;GAEnB,EAEI,IAAgB,IAClB,GACG,EAAE,eAAY;EACb,IAAM,IAAa,EAAkB,EAAM;AAC3C,SACE,EAAW,SAAS,yBAAyB,EAAW,cAAc;IAG1E,GACA,EACD,GACD;AA2CJ,QAvCA,IAAuB,IAAI,EAAa;EACtC,MAAM,EAAK;GAAC;GAHkB,QAAoC,EAAqB;GAGvC;GAAU;GAAc,CAAC;EACzE,OAAO,IAAI,EAAc,EACvB,cAAc;GACZ,OAAO,EACL,QAAQ;IACN,eAAe,EACb,MAAM,GAAoB,GAAmB;AAC3C,YAAO;OAEV;IACD,uBAAuB,EACrB,MAAM,GAAoB,GAAmB;AAC3C,YAAO;OAEV;IACF,EACF;GACD,cAAc,EACZ,WAAW,CAAC,KAAK,EAClB;GACD,sBAAsB,EACpB,WAAW,CAAC,KAAK,EAClB;GACF,EACF,CAAC;EACF,gBAAgB;GACd,YAAY,EACV,aAAa,qBACd;GACD,OAAO,EACL,aAAa,eACd;GACD,QAAQ,EACN,aAAa,gBACd;GACF;EACF,CAAC,EAEK"}
|
|
1
|
+
{"version":3,"file":"global-client.js","names":["hasSessionAuthErrors","errors","code","error","errorCode","message","isMutationOperation","definition","getMainDefinition","query","hasGraphQLResultErrors","result","createMutationAutoRefreshLink","ApolloLink","shouldRefreshAfterMutation","operation","Observable","subscription","forward","observer","getClient","globalClientInstance","currentGlobalUrl","currentAuthToken","DEFAULT_GLOBAL_GATEWAY_URL","toGraphqlUrl","normalized","url","toSubscriptionUrl","USER_NOTIFICATION_CONTEXT","activeWorkspaceToken","workspaceId","getStoredWorkspaceId","token","getStoredWorkspaceToken","isWorkspaceTokenValidForContext","getStoredOrganizationId","getGlobalNotificationClient","globalGatewayUrl","nextAuthToken","authToken","httpLink","HttpLink","wsLink","GraphQLWsLink","createClient","authLink","setContext","workspaceToken","prevContext","errorLink","onError","isAuthNetworkError","redirectToLogin","transportLink","split","mutationAutoRefreshLink","ApolloClient","from","InMemoryCache","incoming"],"sources":["../../src/graphql/global-client.ts"],"sourcesContent":["import {\n ApolloClient,\n ApolloLink,\n type FetchResult,\n InMemoryCache,\n HttpLink,\n Observable,\n from,\n split,\n} from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { onError } from '@apollo/client/link/error';\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { isAuthNetworkError, redirectToLogin } from '@burdenoff/fe-libs/shared/utils';\nimport {\n getStoredOrganizationId,\n getStoredWorkspaceId,\n getStoredWorkspaceToken,\n isWorkspaceTokenValidForContext,\n} from '@burdenoff/fe-libs/shared/graphql';\nimport { createClient } from 'graphql-ws';\n\nfunction hasSessionAuthErrors(\n errors: ReadonlyArray<{ message?: string; extensions?: Record<string, unknown> }> = []\n): boolean {\n return errors.some((error) => {\n const code = typeof error.extensions?.code === 'string' ? error.extensions.code : '';\n const errorCode =\n typeof error.extensions?.errorCode === 'string' ? error.extensions.errorCode : '';\n const message = (error.message ?? '').toLowerCase();\n\n return (\n code === 'UNAUTHENTICATED' ||\n errorCode === 'TOKEN_EXPIRED' ||\n message.includes('token_expired') ||\n message.includes('token expired') ||\n message.includes('session expired') ||\n message.includes('unauthorized') ||\n message.includes('unauthenticated') ||\n message.includes('authentication required') ||\n message.includes('workspace context missing')\n );\n });\n}\n\nfunction isMutationOperation(query: Parameters<typeof getMainDefinition>[0]): boolean {\n const definition = getMainDefinition(query);\n return definition.kind === 'OperationDefinition' && definition.operation === 'mutation';\n}\n\nfunction hasGraphQLResultErrors(result: FetchResult<Record<string, unknown>>): boolean {\n const errors = result.errors;\n return Array.isArray(errors) && errors.length > 0;\n}\n\nfunction createMutationAutoRefreshLink(\n getClient: () => InstanceType<typeof ApolloClient> | null\n): ApolloLink {\n return new ApolloLink((operation, forward) => {\n const shouldRefreshAfterMutation =\n isMutationOperation(operation.query) &&\n operation.getContext().autoRefreshAfterMutation !== false &&\n operation.getContext().skipMutationAutoRefresh !== true;\n\n return new Observable<FetchResult<Record<string, unknown>>>((observer) => {\n const subscription = forward(operation).subscribe({\n next: (result) => {\n observer.next(result as FetchResult<Record<string, unknown>>);\n if (!shouldRefreshAfterMutation || hasGraphQLResultErrors(result)) return;\n\n void getClient()?.refetchQueries({ include: 'active' });\n },\n error: (error: unknown) => {\n observer.error(error);\n },\n complete: () => {\n observer.complete();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n });\n });\n}\n\nlet globalClientInstance: InstanceType<typeof ApolloClient> | null = null;\nlet currentGlobalUrl: string | null = null;\nlet currentAuthToken: string | null = null;\n\n/**\n * Default Global Gateway URL\n * Notifications are a GLOBAL service and must use the global gateway\n */\nexport const DEFAULT_GLOBAL_GATEWAY_URL = 'https://gw-global.local.burdenoff.com/global/graphql';\n\nfunction toGraphqlUrl(url: string): string {\n const normalized = url.replace(/\\/$/, '');\n if (normalized.endsWith('/graphql')) return normalized;\n if (normalized.endsWith('/global')) return `${normalized}/graphql`;\n return `${normalized}/global/graphql`;\n}\n\nfunction toSubscriptionUrl(url: string): string {\n if (url.startsWith('https://')) return url.replace('https://', 'wss://');\n if (url.startsWith('http://')) return url.replace('http://', 'ws://');\n return url;\n}\n\n/**\n * Get or create the singleton Apollo client for global notification operations\n *\n * @param globalGatewayUrl - Global Gateway GraphQL URL (default: https://gw-global.local.burdenoff.com/global/graphql)\n * @param authToken - Optional JWT auth token\n */\n/**\n * Context for a user's own notification reads and writes.\n *\n * Notifications are scoped to an ORGANIZATION, and product services file a\n * user's rows under the active workspace's organization. On the global gateway\n * a user session's organization comes from the account token, which differs\n * whenever the active workspace belongs to another organization the user is a\n * member of. With this context the request also carries the shell's workspace\n * token (when it is valid for the active workspace), so the gateway scopes it\n * to the active workspace's organization, as the shell's notification bell\n * does. Without a valid token the account organization applies, as before.\n */\nexport const USER_NOTIFICATION_CONTEXT = { preferWorkspaceAuth: true } as const;\n\n/** The shell's workspace token, when it is still valid for the active workspace. */\nfunction activeWorkspaceToken(): string | null {\n const workspaceId = getStoredWorkspaceId();\n if (!workspaceId) return null;\n const token = getStoredWorkspaceToken();\n return isWorkspaceTokenValidForContext(token, {\n workspaceId,\n organizationId: getStoredOrganizationId(),\n })\n ? token\n : null;\n}\n\nexport function getGlobalNotificationClient(\n globalGatewayUrl?: string,\n authToken?: string\n): InstanceType<typeof ApolloClient> {\n const url = toGraphqlUrl(globalGatewayUrl || DEFAULT_GLOBAL_GATEWAY_URL);\n const nextAuthToken = authToken ?? null;\n\n // Return existing instance if config hasn't changed\n if (globalClientInstance && currentGlobalUrl === url && currentAuthToken === nextAuthToken) {\n return globalClientInstance;\n }\n\n // Update current config\n currentGlobalUrl = url;\n currentAuthToken = nextAuthToken;\n\n const httpLink = new HttpLink({\n uri: url,\n });\n\n const wsLink =\n typeof window !== 'undefined'\n ? new GraphQLWsLink(\n createClient({\n url: toSubscriptionUrl(url),\n connectionParams: () => ({\n authorization: authToken ? `Bearer ${authToken}` : '',\n }),\n lazy: true,\n retryAttempts: 3,\n })\n )\n : null;\n\n const authLink = setContext((_, prevContext) => {\n const workspaceToken = prevContext.preferWorkspaceAuth === true ? activeWorkspaceToken() : null;\n return {\n headers: {\n ...(prevContext.headers as Record<string, string>),\n authorization: authToken ? `Bearer ${authToken}` : '',\n ...(workspaceToken ? { 'x-workspace-authorization': `Bearer ${workspaceToken}` } : {}),\n },\n };\n });\n\n const errorLink = onError(({ error }) => {\n if (!error) return;\n\n const graphQLErrors = 'errors' in error && Array.isArray(error.errors) ? error.errors : [];\n\n if (hasSessionAuthErrors(graphQLErrors)) {\n redirectToLogin();\n return;\n }\n\n if (error instanceof Error && isAuthNetworkError(error)) {\n redirectToLogin();\n }\n });\n\n const transportLink = wsLink\n ? split(\n ({ query }) => {\n const definition = getMainDefinition(query);\n return (\n definition.kind === 'OperationDefinition' && definition.operation === 'subscription'\n );\n },\n wsLink,\n httpLink\n )\n : httpLink;\n\n const mutationAutoRefreshLink = createMutationAutoRefreshLink(() => globalClientInstance);\n\n globalClientInstance = new ApolloClient({\n link: from([errorLink, mutationAutoRefreshLink, authLink, transportLink]),\n cache: new InMemoryCache({\n typePolicies: {\n Query: {\n fields: {\n notifications: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n notificationTemplates: {\n merge(_existing: unknown, incoming: unknown) {\n return incoming;\n },\n },\n },\n },\n Notification: {\n keyFields: ['id'],\n },\n NotificationTemplate: {\n keyFields: ['id'],\n },\n },\n }),\n defaultOptions: {\n watchQuery: {\n fetchPolicy: 'cache-and-network',\n },\n query: {\n fetchPolicy: 'cache-first',\n },\n mutate: {\n fetchPolicy: 'network-only',\n },\n },\n });\n\n return globalClientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing or re-initialization)\n */\nexport function resetGlobalNotificationClient(): void {\n if (globalClientInstance) {\n globalClientInstance.clearStore();\n globalClientInstance = null;\n currentGlobalUrl = null;\n currentAuthToken = null;\n }\n}\n"],"mappings":";;;;;;;;;AAuBA,SAASA,EACP,IAAoF,CAAC,GAC5E;CACT,OAAOC,EAAO,MAAM,MAAU;EAC5B,IAAMC,IAAO,OAAOC,EAAM,YAAY,QAAS,WAAWA,EAAM,WAAW,OAAO,IAC5EC,IACJ,OAAOD,EAAM,YAAY,aAAc,WAAWA,EAAM,WAAW,YAAY,IAC3EE,KAAWF,EAAM,WAAW,GAAA,CAAI,YAAY;EAElD,OACED,MAAS,qBACTE,MAAc,mBACdC,EAAQ,SAAS,eAAe,KAChCA,EAAQ,SAAS,eAAe,KAChCA,EAAQ,SAAS,iBAAiB,KAClCA,EAAQ,SAAS,cAAc,KAC/BA,EAAQ,SAAS,iBAAiB,KAClCA,EAAQ,SAAS,yBAAyB,KAC1CA,EAAQ,SAAS,2BAA2B;CAEhD,CAAC;AACH;AAEA,SAASC,EAAoB,GAAyD;CACpF,IAAMC,IAAaC,EAAkBC,CAAK;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EAAa;EACtC,MAAMC,EAAK;GAACR;GAAWM;GAAyBV;GAAUQ;EAAa,CAAC;EACxE,OAAO,IAAIK,EAAc,EACvB,cAAc;GACZ,OAAO,EACL,QAAQ;IACN,eAAe,EACb,MAAM,GAAoB,GAAmB;KAC3C,OAAOC;IACT,EACF;IACA,uBAAuB,EACrB,MAAM,GAAoB,GAAmB;KAC3C,OAAOA;IACT,EACF;GACF,EACF;GACA,cAAc,EACZ,WAAW,CAAC,IAAI,EAClB;GACA,sBAAsB,EACpB,WAAW,CAAC,IAAI,EAClB;EACF,EACF,CAAC;EACD,gBAAgB;GACd,YAAY,EACV,aAAa,oBACf;GACA,OAAO,EACL,aAAa,cACf;GACA,QAAQ,EACN,aAAa,eACf;EACF;CACF,CAAC,GAEMvC;AACT"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { useNotifications } from './useNotifications';
|
|
2
|
+
export { useNotificationAdmin } from './useNotificationAdmin';
|
|
3
|
+
export { useNotificationPreferences } from './useNotificationPreferences';
|
|
4
|
+
export { useNotificationTopics } from './useNotificationTopics';
|
|
5
|
+
export { useNotificationAnalytics } from './useNotificationAnalytics';
|
|
6
|
+
export { useNotificationStore } from '../store/notificationStore';
|
|
7
|
+
export { useNotification } from '../providers/NotificationProvider';
|
package/dist/hooks/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import "
|
|
2
|
-
import "
|
|
3
|
-
import "./
|
|
1
|
+
import { useNotifications as e } from "./useNotifications.js";
|
|
2
|
+
import { useNotificationAdmin as t } from "./useNotificationAdmin.js";
|
|
3
|
+
import { useNotificationPreferences as n } from "./useNotificationPreferences.js";
|
|
4
|
+
import { useNotificationTopics as r } from "./useNotificationTopics.js";
|
|
4
5
|
import "./useNotificationAnalytics.js";
|
|
5
|
-
import "
|
|
6
|
-
import "
|
|
7
|
-
|
|
6
|
+
import { useNotificationStore as i } from "../store/notificationStore.js";
|
|
7
|
+
import { useNotification as a } from "../providers/NotificationProvider.js";
|
|
8
|
+
export { a as useNotification, t as useNotificationAdmin, n as useNotificationPreferences, i as useNotificationStore, r as useNotificationTopics, e as useNotifications };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Notification, NotificationAdminFilters } from '../types';
|
|
2
|
+
export declare function useNotificationAdmin(): {
|
|
3
|
+
filters: NotificationAdminFilters;
|
|
4
|
+
setFilters: import('react').Dispatch<import('react').SetStateAction<NotificationAdminFilters>>;
|
|
5
|
+
notifications: Notification[];
|
|
6
|
+
scheduledNotifications: {
|
|
7
|
+
id: string;
|
|
8
|
+
scheduledFor: string;
|
|
9
|
+
status: import('../generated/global-types').ScheduledNotificationStatus;
|
|
10
|
+
timezone: string | null;
|
|
11
|
+
retryCount: number;
|
|
12
|
+
errorMessage: string | null;
|
|
13
|
+
createdAt: string;
|
|
14
|
+
notification: {
|
|
15
|
+
id: string;
|
|
16
|
+
title: string;
|
|
17
|
+
message: string;
|
|
18
|
+
type: import('../generated/global-types').NotificationType;
|
|
19
|
+
priority: import('../generated/global-types').NotificationPriority;
|
|
20
|
+
channel: import('../generated/global-types').NotificationChannel;
|
|
21
|
+
userId: string;
|
|
22
|
+
topicId: string | null;
|
|
23
|
+
};
|
|
24
|
+
}[];
|
|
25
|
+
selectedNotification: Notification | null;
|
|
26
|
+
events: {
|
|
27
|
+
id: string;
|
|
28
|
+
notificationId: string;
|
|
29
|
+
eventType: import('../generated/global-types').NotificationEventType;
|
|
30
|
+
deliveryStatus: import('../generated/global-types').NotificationDeliveryStatus | null;
|
|
31
|
+
timestamp: string;
|
|
32
|
+
externalId: string | null;
|
|
33
|
+
channelServiceEventId: string | null;
|
|
34
|
+
details: Record<string, unknown> | null;
|
|
35
|
+
metadata: Record<string, unknown> | null;
|
|
36
|
+
}[];
|
|
37
|
+
isLoading: boolean;
|
|
38
|
+
error: string | null;
|
|
39
|
+
refetch: () => Promise<void>;
|
|
40
|
+
loadNotification: (notificationId: string) => Promise<void>;
|
|
41
|
+
archiveNotification: (notificationId: string) => Promise<void>;
|
|
42
|
+
unarchiveNotification: (notificationId: string) => Promise<void>;
|
|
43
|
+
cancelScheduledNotification: (scheduledNotificationId: string) => Promise<void>;
|
|
44
|
+
rescheduleNotification: (scheduledNotificationId: string, scheduledFor: string, timezone?: string) => Promise<void>;
|
|
45
|
+
clearSelection: () => void;
|
|
46
|
+
};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { useNotification as e } from "../providers/NotificationProvider.js";
|
|
2
2
|
import { getGlobalNotificationClient as t } from "../graphql/global-client.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { useNotificationAnalytics as n } from "./useNotificationAnalytics.js";
|
|
4
|
+
import { ArchiveNotificationDocument as r, CancelScheduledNotificationDocument as i, GetNotificationDocument as a, GetNotificationEventsDocument as o, GetNotificationsDocument as s, GetScheduledNotificationsDocument as c, RescheduleNotificationDocument as l, UnarchiveNotificationDocument as u } from "../generated/global-operations.js";
|
|
5
5
|
import { useCallback as d, useEffect as f, useState as p } from "react";
|
|
6
|
-
|
|
6
|
+
// src/hooks/useNotificationAdmin.ts
|
|
7
7
|
var m = {
|
|
8
8
|
search: "",
|
|
9
9
|
status: "all",
|
|
@@ -89,11 +89,11 @@ function _(e) {
|
|
|
89
89
|
};
|
|
90
90
|
}
|
|
91
91
|
function v() {
|
|
92
|
-
let { authToken: h, apiGatewayUrl: g } = e(), { trackScheduleUpdated: v } =
|
|
92
|
+
let { authToken: h, apiGatewayUrl: g } = e(), { trackScheduleUpdated: v } = n(), [y, b] = p(m), [x, S] = p([]), [C, w] = p([]), [T, E] = p(null), [D, O] = p([]), [k, A] = p(!1), [j, M] = p(null), N = d(() => t(g ?? void 0, h ?? void 0), [g, h]), P = d(async () => {
|
|
93
93
|
A(!0), M(null);
|
|
94
94
|
try {
|
|
95
|
-
|
|
96
|
-
query:
|
|
95
|
+
let e = await N().query({
|
|
96
|
+
query: s,
|
|
97
97
|
variables: {
|
|
98
98
|
filter: {
|
|
99
99
|
...y.search ? { search: y.search } : {},
|
|
@@ -108,7 +108,8 @@ function v() {
|
|
|
108
108
|
offset: 0
|
|
109
109
|
},
|
|
110
110
|
fetchPolicy: "network-only"
|
|
111
|
-
})
|
|
111
|
+
});
|
|
112
|
+
S((e.data?.notifications.items || []).map(_));
|
|
112
113
|
} catch (e) {
|
|
113
114
|
console.error("[useNotificationAdmin] Failed to fetch notifications:", e), M(e instanceof Error ? e.message : "Failed to fetch notifications");
|
|
114
115
|
} finally {
|
|
@@ -116,14 +117,15 @@ function v() {
|
|
|
116
117
|
}
|
|
117
118
|
}, [y, N]), F = d(async () => {
|
|
118
119
|
try {
|
|
119
|
-
|
|
120
|
-
query:
|
|
120
|
+
let e = await N().query({
|
|
121
|
+
query: c,
|
|
121
122
|
variables: {
|
|
122
123
|
limit: 100,
|
|
123
124
|
offset: 0
|
|
124
125
|
},
|
|
125
126
|
fetchPolicy: "network-only"
|
|
126
|
-
})
|
|
127
|
+
});
|
|
128
|
+
w(e.data?.scheduledNotifications.items || []);
|
|
127
129
|
} catch (e) {
|
|
128
130
|
console.error("[useNotificationAdmin] Failed to fetch scheduled notifications:", e);
|
|
129
131
|
}
|
|
@@ -131,11 +133,11 @@ function v() {
|
|
|
131
133
|
M(null);
|
|
132
134
|
try {
|
|
133
135
|
let t = N(), [n, r] = await Promise.all([t.query({
|
|
134
|
-
query:
|
|
136
|
+
query: a,
|
|
135
137
|
variables: { id: e },
|
|
136
138
|
fetchPolicy: "network-only"
|
|
137
139
|
}), t.query({
|
|
138
|
-
query:
|
|
140
|
+
query: o,
|
|
139
141
|
variables: { notificationId: e },
|
|
140
142
|
fetchPolicy: "network-only"
|
|
141
143
|
})]);
|
|
@@ -145,17 +147,17 @@ function v() {
|
|
|
145
147
|
}
|
|
146
148
|
}, [N]), L = d(async (e) => {
|
|
147
149
|
await N().mutate({
|
|
148
|
-
mutation:
|
|
150
|
+
mutation: r,
|
|
149
151
|
variables: { id: e }
|
|
150
152
|
}), await P();
|
|
151
153
|
}, [P, N]), R = d(async (e) => {
|
|
152
154
|
await N().mutate({
|
|
153
|
-
mutation:
|
|
155
|
+
mutation: u,
|
|
154
156
|
variables: { id: e }
|
|
155
157
|
}), await P();
|
|
156
158
|
}, [P, N]), z = d(async (e) => {
|
|
157
159
|
await N().mutate({
|
|
158
|
-
mutation:
|
|
160
|
+
mutation: i,
|
|
159
161
|
variables: { id: e }
|
|
160
162
|
}), v({ action: "cancel" }), await Promise.all([P(), F()]);
|
|
161
163
|
}, [
|
|
@@ -165,7 +167,7 @@ function v() {
|
|
|
165
167
|
v
|
|
166
168
|
]), B = d(async (e, t, n) => {
|
|
167
169
|
await N().mutate({
|
|
168
|
-
mutation:
|
|
170
|
+
mutation: l,
|
|
169
171
|
variables: { input: {
|
|
170
172
|
scheduledNotificationId: e,
|
|
171
173
|
scheduledFor: t,
|
|
@@ -200,7 +202,6 @@ function v() {
|
|
|
200
202
|
}
|
|
201
203
|
};
|
|
202
204
|
}
|
|
203
|
-
//#endregion
|
|
204
205
|
export { v as useNotificationAdmin };
|
|
205
206
|
|
|
206
207
|
//# sourceMappingURL=useNotificationAdmin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationAdmin.js","names":[],"sources":["../../src/hooks/useNotificationAdmin.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { Notification, NotificationAdminFilters } from '../types';\nimport { useNotificationAnalytics } from './useNotificationAnalytics';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationsQuery,\n GetNotificationQuery,\n GetNotificationEventsQuery,\n GetScheduledNotificationsQuery,\n} from '../generated/global-operations';\n\nconst defaultFilters: NotificationAdminFilters = {\n search: '',\n status: 'all',\n channel: 'all',\n deliveryStatus: 'all',\n type: 'all',\n topicId: '',\n archived: 'all',\n};\n\nfunction mapPriority(priority: string): Notification['priority'] {\n if (priority === 'MEDIUM') return 'NORMAL';\n return (priority as Notification['priority']) || 'NORMAL';\n}\n\nfunction mapStatus(status: string): Notification['status'] {\n if (status === 'CANCELLED') return 'ARCHIVED';\n if (status === 'READ') return 'DELIVERED';\n return (status as Notification['status']) || 'PENDING';\n}\n\nfunction mapNotification(\n notification:\n | GetNotificationsQuery['notifications']['items'][number]\n | NonNullable<GetNotificationQuery['notification']>\n): Notification {\n return {\n id: notification.id,\n title: notification.title,\n body: notification.message,\n type: notification.type as Notification['type'],\n priority: mapPriority(notification.priority),\n status: mapStatus(notification.status),\n channel: notification.channel as Notification['channel'],\n deliveryStatus: notification.deliveryStatus ?? undefined,\n createdAt: notification.createdAt,\n updatedAt: notification.updatedAt,\n readAt: notification.readAt ?? undefined,\n archivedAt: notification.archivedAt ?? undefined,\n clickedAt: notification.clickedAt ?? undefined,\n openedAt: notification.openedAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n sentAt: notification.sentAt ?? undefined,\n actionUrl: notification.redirectUrl ?? undefined,\n actions: (notification.actions || []).map((action) => ({\n id: action.id,\n label: action.label,\n url: action.url,\n style: action.style ?? undefined,\n actionType: action.actionType ?? undefined,\n metadata: action.metadata ?? undefined,\n })),\n media: (notification.media || []).map((item) => ({\n url: item.url,\n label: item.label ?? undefined,\n kind: item.kind ?? undefined,\n contentType: item.contentType ?? undefined,\n thumbnailUrl: item.thumbnailUrl ?? undefined,\n })),\n appName: notification.appName ?? undefined,\n htmlBody: notification.htmlMessage ?? undefined,\n metadata: notification.metadata ?? undefined,\n channels: [\n {\n id: notification.id,\n channel: notification.channel as Notification['channel'],\n status: mapStatus(notification.status),\n sentAt: notification.sentAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n failedAt: notification.failedAt ?? undefined,\n errorCode: notification.errorCode ?? undefined,\n errorMessage: notification.errorMessage ?? undefined,\n },\n ],\n recipientEmail: notification.recipientEmail ?? undefined,\n recipientPhone: notification.recipientPhone ?? undefined,\n scheduledFor: notification.scheduledFor ?? undefined,\n scheduledNotification: notification.scheduledNotification\n ? {\n id: notification.scheduledNotification.id,\n scheduledFor: notification.scheduledNotification.scheduledFor,\n status: notification.scheduledNotification.status,\n timezone: notification.scheduledNotification.timezone ?? undefined,\n retryCount: notification.scheduledNotification.retryCount ?? undefined,\n errorMessage: notification.scheduledNotification.errorMessage ?? undefined,\n }\n : undefined,\n topicId: notification.topicId ?? undefined,\n topic: notification.topic\n ? {\n id: notification.topic.id,\n name: notification.topic.name,\n slug: notification.topic.slug,\n type: notification.topic.type as Notification['type'],\n description: notification.topic.description ?? undefined,\n }\n : undefined,\n imageUrl: notification.media?.[0]?.url ?? undefined,\n };\n}\n\nexport function useNotificationAdmin() {\n const { authToken, apiGatewayUrl } = useNotification();\n const { trackScheduleUpdated } = useNotificationAnalytics();\n const [filters, setFilters] = useState<NotificationAdminFilters>(defaultFilters);\n const [notifications, setNotifications] = useState<Notification[]>([]);\n const [scheduledNotifications, setScheduledNotifications] = useState<\n GetScheduledNotificationsQuery['scheduledNotifications']['items']\n >([]);\n const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);\n const [events, setEvents] = useState<GetNotificationEventsQuery['notificationEvents']>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchNotifications = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: {\n ...(filters.search ? { search: filters.search } : {}),\n ...(filters.status !== 'all' ? { status: filters.status } : {}),\n ...(filters.channel !== 'all' ? { channel: filters.channel } : {}),\n ...(filters.deliveryStatus !== 'all' ? { deliveryStatus: filters.deliveryStatus } : {}),\n ...(filters.type !== 'all' ? { type: filters.type } : {}),\n ...(filters.topicId ? { topicId: filters.topicId } : {}),\n ...(filters.archived !== 'all' ? { archived: filters.archived === 'archived' } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n setNotifications((result.data?.notifications.items || []).map(mapNotification));\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch notifications:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch notifications');\n } finally {\n setIsLoading(false);\n }\n }, [filters, getClient]);\n\n const fetchScheduledNotifications = useCallback(async () => {\n try {\n const client = getClient();\n const result = await client.query<GetScheduledNotificationsQuery>({\n query: NotificationOps.GetScheduledNotificationsDocument,\n variables: { limit: 100, offset: 0 },\n fetchPolicy: 'network-only',\n });\n\n setScheduledNotifications(result.data?.scheduledNotifications.items || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch scheduled notifications:', err);\n }\n }, [getClient]);\n\n const loadNotification = useCallback(\n async (notificationId: string) => {\n setError(null);\n\n try {\n const client = getClient();\n const [notificationResult, eventsResult] = await Promise.all([\n client.query<GetNotificationQuery>({\n query: NotificationOps.GetNotificationDocument,\n variables: { id: notificationId },\n fetchPolicy: 'network-only',\n }),\n client.query<GetNotificationEventsQuery>({\n query: NotificationOps.GetNotificationEventsDocument,\n variables: { notificationId },\n fetchPolicy: 'network-only',\n }),\n ]);\n\n if (notificationResult.data?.notification) {\n setSelectedNotification(mapNotification(notificationResult.data.notification));\n }\n setEvents(eventsResult.data?.notificationEvents || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to load notification detail:', err);\n setError(err instanceof Error ? err.message : 'Failed to load notification detail');\n }\n },\n [getClient]\n );\n\n const archiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.ArchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const unarchiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.UnarchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const cancelScheduledNotification = useCallback(\n async (scheduledNotificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.CancelScheduledNotificationDocument,\n variables: { id: scheduledNotificationId },\n });\n trackScheduleUpdated({ action: 'cancel' });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient, trackScheduleUpdated]\n );\n\n const rescheduleNotification = useCallback(\n async (scheduledNotificationId: string, scheduledFor: string, timezone?: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.RescheduleNotificationDocument,\n variables: {\n input: {\n scheduledNotificationId,\n scheduledFor,\n timezone,\n },\n },\n });\n trackScheduleUpdated({ action: 'reschedule' });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient, trackScheduleUpdated]\n );\n\n useEffect(() => {\n fetchNotifications();\n fetchScheduledNotifications();\n }, [fetchNotifications, fetchScheduledNotifications]);\n\n return {\n filters,\n setFilters,\n notifications,\n scheduledNotifications,\n selectedNotification,\n events,\n isLoading,\n error,\n refetch: fetchNotifications,\n loadNotification,\n archiveNotification,\n unarchiveNotification,\n cancelScheduledNotification,\n rescheduleNotification,\n clearSelection: () => {\n setSelectedNotification(null);\n setEvents([]);\n },\n };\n}\n"],"mappings":";;;;;;AAaA,IAAM,IAA2C;CAC/C,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,gBAAgB;CAChB,MAAM;CACN,SAAS;CACT,UAAU;CACX;AAED,SAAS,EAAY,GAA4C;AAE/D,QADI,MAAa,WAAiB,WAC1B,KAAyC;;AAGnD,SAAS,EAAU,GAAwC;AAGzD,QAFI,MAAW,cAAoB,aAC/B,MAAW,SAAe,cACtB,KAAqC;;AAG/C,SAAS,EACP,GAGc;AACd,QAAO;EACL,IAAI,EAAa;EACjB,OAAO,EAAa;EACpB,MA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A4B,CAAC,EAE9C;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;EACT;EACA;EACA;EACA;EACA;EACA,sBAAsB;AAEpB,GADA,EAAwB,KAAK,EAC7B,EAAU,EAAE,CAAC;;EAEhB"}
|
|
1
|
+
{"version":3,"file":"useNotificationAdmin.js","names":["NotificationOps.GetNotificationsDocument","NotificationOps.GetScheduledNotificationsDocument","NotificationOps.GetNotificationDocument","NotificationOps.GetNotificationEventsDocument","NotificationOps.ArchiveNotificationDocument","NotificationOps.UnarchiveNotificationDocument","NotificationOps.CancelScheduledNotificationDocument","NotificationOps.RescheduleNotificationDocument","defaultFilters","mapPriority","priority","mapStatus","status","mapNotification","notification","action","item","useNotificationAdmin","useNotification","useNotificationAnalytics","filters","setFilters","useState","notifications","setNotifications","scheduledNotifications","setScheduledNotifications","selectedNotification","setSelectedNotification","events","setEvents","isLoading","setIsLoading","error","setError","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","fetchNotifications","result","GetNotificationsDocument","err","fetchScheduledNotifications","GetScheduledNotificationsDocument","loadNotification","client","notificationResult","eventsResult","GetNotificationDocument","notificationId","GetNotificationEventsDocument","archiveNotification","ArchiveNotificationDocument","unarchiveNotification","UnarchiveNotificationDocument","cancelScheduledNotification","CancelScheduledNotificationDocument","scheduledNotificationId","trackScheduleUpdated","rescheduleNotification","RescheduleNotificationDocument","useEffect"],"sources":["../../src/hooks/useNotificationAdmin.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { Notification, NotificationAdminFilters } from '../types';\nimport { useNotificationAnalytics } from './useNotificationAnalytics';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationsQuery,\n GetNotificationQuery,\n GetNotificationEventsQuery,\n GetScheduledNotificationsQuery,\n} from '../generated/global-operations';\n\nconst defaultFilters: NotificationAdminFilters = {\n search: '',\n status: 'all',\n channel: 'all',\n deliveryStatus: 'all',\n type: 'all',\n topicId: '',\n archived: 'all',\n};\n\nfunction mapPriority(priority: string): Notification['priority'] {\n if (priority === 'MEDIUM') return 'NORMAL';\n return (priority as Notification['priority']) || 'NORMAL';\n}\n\nfunction mapStatus(status: string): Notification['status'] {\n if (status === 'CANCELLED') return 'ARCHIVED';\n if (status === 'READ') return 'DELIVERED';\n return (status as Notification['status']) || 'PENDING';\n}\n\nfunction mapNotification(\n notification:\n | GetNotificationsQuery['notifications']['items'][number]\n | NonNullable<GetNotificationQuery['notification']>\n): Notification {\n return {\n id: notification.id,\n title: notification.title,\n body: notification.message,\n type: notification.type as Notification['type'],\n priority: mapPriority(notification.priority),\n status: mapStatus(notification.status),\n channel: notification.channel as Notification['channel'],\n deliveryStatus: notification.deliveryStatus ?? undefined,\n createdAt: notification.createdAt,\n updatedAt: notification.updatedAt,\n readAt: notification.readAt ?? undefined,\n archivedAt: notification.archivedAt ?? undefined,\n clickedAt: notification.clickedAt ?? undefined,\n openedAt: notification.openedAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n sentAt: notification.sentAt ?? undefined,\n actionUrl: notification.redirectUrl ?? undefined,\n actions: (notification.actions || []).map((action) => ({\n id: action.id,\n label: action.label,\n url: action.url,\n style: action.style ?? undefined,\n actionType: action.actionType ?? undefined,\n metadata: action.metadata ?? undefined,\n })),\n media: (notification.media || []).map((item) => ({\n url: item.url,\n label: item.label ?? undefined,\n kind: item.kind ?? undefined,\n contentType: item.contentType ?? undefined,\n thumbnailUrl: item.thumbnailUrl ?? undefined,\n })),\n appName: notification.appName ?? undefined,\n htmlBody: notification.htmlMessage ?? undefined,\n metadata: notification.metadata ?? undefined,\n channels: [\n {\n id: notification.id,\n channel: notification.channel as Notification['channel'],\n status: mapStatus(notification.status),\n sentAt: notification.sentAt ?? undefined,\n deliveredAt: notification.deliveredAt ?? undefined,\n failedAt: notification.failedAt ?? undefined,\n errorCode: notification.errorCode ?? undefined,\n errorMessage: notification.errorMessage ?? undefined,\n },\n ],\n recipientEmail: notification.recipientEmail ?? undefined,\n recipientPhone: notification.recipientPhone ?? undefined,\n scheduledFor: notification.scheduledFor ?? undefined,\n scheduledNotification: notification.scheduledNotification\n ? {\n id: notification.scheduledNotification.id,\n scheduledFor: notification.scheduledNotification.scheduledFor,\n status: notification.scheduledNotification.status,\n timezone: notification.scheduledNotification.timezone ?? undefined,\n retryCount: notification.scheduledNotification.retryCount ?? undefined,\n errorMessage: notification.scheduledNotification.errorMessage ?? undefined,\n }\n : undefined,\n topicId: notification.topicId ?? undefined,\n topic: notification.topic\n ? {\n id: notification.topic.id,\n name: notification.topic.name,\n slug: notification.topic.slug,\n type: notification.topic.type as Notification['type'],\n description: notification.topic.description ?? undefined,\n }\n : undefined,\n imageUrl: notification.media?.[0]?.url ?? undefined,\n };\n}\n\nexport function useNotificationAdmin() {\n const { authToken, apiGatewayUrl } = useNotification();\n const { trackScheduleUpdated } = useNotificationAnalytics();\n const [filters, setFilters] = useState<NotificationAdminFilters>(defaultFilters);\n const [notifications, setNotifications] = useState<Notification[]>([]);\n const [scheduledNotifications, setScheduledNotifications] = useState<\n GetScheduledNotificationsQuery['scheduledNotifications']['items']\n >([]);\n const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);\n const [events, setEvents] = useState<GetNotificationEventsQuery['notificationEvents']>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchNotifications = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationsQuery>({\n query: NotificationOps.GetNotificationsDocument,\n variables: {\n filter: {\n ...(filters.search ? { search: filters.search } : {}),\n ...(filters.status !== 'all' ? { status: filters.status } : {}),\n ...(filters.channel !== 'all' ? { channel: filters.channel } : {}),\n ...(filters.deliveryStatus !== 'all' ? { deliveryStatus: filters.deliveryStatus } : {}),\n ...(filters.type !== 'all' ? { type: filters.type } : {}),\n ...(filters.topicId ? { topicId: filters.topicId } : {}),\n ...(filters.archived !== 'all' ? { archived: filters.archived === 'archived' } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'network-only',\n });\n\n setNotifications((result.data?.notifications.items || []).map(mapNotification));\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch notifications:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch notifications');\n } finally {\n setIsLoading(false);\n }\n }, [filters, getClient]);\n\n const fetchScheduledNotifications = useCallback(async () => {\n try {\n const client = getClient();\n const result = await client.query<GetScheduledNotificationsQuery>({\n query: NotificationOps.GetScheduledNotificationsDocument,\n variables: { limit: 100, offset: 0 },\n fetchPolicy: 'network-only',\n });\n\n setScheduledNotifications(result.data?.scheduledNotifications.items || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to fetch scheduled notifications:', err);\n }\n }, [getClient]);\n\n const loadNotification = useCallback(\n async (notificationId: string) => {\n setError(null);\n\n try {\n const client = getClient();\n const [notificationResult, eventsResult] = await Promise.all([\n client.query<GetNotificationQuery>({\n query: NotificationOps.GetNotificationDocument,\n variables: { id: notificationId },\n fetchPolicy: 'network-only',\n }),\n client.query<GetNotificationEventsQuery>({\n query: NotificationOps.GetNotificationEventsDocument,\n variables: { notificationId },\n fetchPolicy: 'network-only',\n }),\n ]);\n\n if (notificationResult.data?.notification) {\n setSelectedNotification(mapNotification(notificationResult.data.notification));\n }\n setEvents(eventsResult.data?.notificationEvents || []);\n } catch (err) {\n console.error('[useNotificationAdmin] Failed to load notification detail:', err);\n setError(err instanceof Error ? err.message : 'Failed to load notification detail');\n }\n },\n [getClient]\n );\n\n const archiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.ArchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const unarchiveNotification = useCallback(\n async (notificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.UnarchiveNotificationDocument,\n variables: { id: notificationId },\n });\n await fetchNotifications();\n },\n [fetchNotifications, getClient]\n );\n\n const cancelScheduledNotification = useCallback(\n async (scheduledNotificationId: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.CancelScheduledNotificationDocument,\n variables: { id: scheduledNotificationId },\n });\n trackScheduleUpdated({ action: 'cancel' });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient, trackScheduleUpdated]\n );\n\n const rescheduleNotification = useCallback(\n async (scheduledNotificationId: string, scheduledFor: string, timezone?: string) => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.RescheduleNotificationDocument,\n variables: {\n input: {\n scheduledNotificationId,\n scheduledFor,\n timezone,\n },\n },\n });\n trackScheduleUpdated({ action: 'reschedule' });\n await Promise.all([fetchNotifications(), fetchScheduledNotifications()]);\n },\n [fetchNotifications, fetchScheduledNotifications, getClient, trackScheduleUpdated]\n );\n\n useEffect(() => {\n fetchNotifications();\n fetchScheduledNotifications();\n }, [fetchNotifications, fetchScheduledNotifications]);\n\n return {\n filters,\n setFilters,\n notifications,\n scheduledNotifications,\n selectedNotification,\n events,\n isLoading,\n error,\n refetch: fetchNotifications,\n loadNotification,\n archiveNotification,\n unarchiveNotification,\n cancelScheduledNotification,\n rescheduleNotification,\n clearSelection: () => {\n setSelectedNotification(null);\n setEvents([]);\n },\n };\n}\n"],"mappings":";;;;;;AAaA,IAAMQ,IAA2C;CAC/C,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,gBAAgB;CAChB,MAAM;CACN,SAAS;CACT,UAAU;AACZ;AAEA,SAASC,EAAY,GAA4C;CAE/D,OADIC,MAAa,WAAiB,WAC1BA,KAAyC;AACnD;AAEA,SAASC,EAAU,GAAwC;CAGzD,OAFIC,MAAW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ACzC,MAAM,QAAQ,IAAI,CAACpB,EAAmB,GAAGI,EAA4B,CAAC,CAAC;CACzE,GACA;EAACJ;EAAoBI;EAA6BT;EAAWyB;CAAoB,CACnF,GAEMC,IAAyBzB,EAC7B,OAAO,GAAiC,GAAsB,MAAsB;EAalF,AAXA,MADeD,EACT,CAAA,CAAO,OAAO;GAClB,UAAU5B;GACV,WAAW,EACT,OAAO;IACL;IACA;IACA;GACF,EACF;EACF,CAAC,GACDqD,EAAqB,EAAE,QAAQ,aAAa,CAAC,GAC7C,MAAM,QAAQ,IAAI,CAACpB,EAAmB,GAAGI,EAA4B,CAAC,CAAC;CACzE,GACA;EAACJ;EAAoBI;EAA6BT;EAAWyB;CAAoB,CACnF;CAOA,OALAG,QAAgB;EAEd,AADAvB,EAAmB,GACnBI,EAA4B;CAC9B,GAAG,CAACJ,GAAoBI,CAA2B,CAAC,GAE7C;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAASJ;EACT;EACA;EACA;EACA;EACA;EACA,sBAAsB;GAEpB,AADAZ,EAAwB,IAAI,GAC5BE,EAAU,CAAC,CAAC;EACd;CACF;AACF"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Notification, NotificationPreferenceScope } from '../types';
|
|
2
|
+
import { NotificationChannelType, NotificationPriorityEnum, NotificationTypeEnum } from './useSendNotification';
|
|
3
|
+
interface NotificationAnalyticsPayload {
|
|
4
|
+
source?: 'center' | 'panel' | 'history' | 'preferences' | 'admin_history' | 'composer' | 'template_editor';
|
|
5
|
+
action?: 'open' | 'set' | 'reset' | 'send' | 'create' | 'update' | 'cancel' | 'reschedule';
|
|
6
|
+
interaction?: 'card' | 'primary_action' | 'custom_action';
|
|
7
|
+
scope?: 'GLOBAL' | 'CHANNEL' | 'TYPE' | 'TOPIC';
|
|
8
|
+
channel?: string;
|
|
9
|
+
type?: string;
|
|
10
|
+
priority?: string;
|
|
11
|
+
mode?: 'compose' | 'template';
|
|
12
|
+
recipientSource?: 'manual' | 'directory';
|
|
13
|
+
recipientCount?: number;
|
|
14
|
+
successCount?: number;
|
|
15
|
+
failedCount?: number;
|
|
16
|
+
scheduled?: boolean;
|
|
17
|
+
includeInApp?: boolean;
|
|
18
|
+
enabled?: boolean;
|
|
19
|
+
hasActions?: boolean;
|
|
20
|
+
hasMedia?: boolean;
|
|
21
|
+
hasHtml?: boolean;
|
|
22
|
+
variableCount?: number;
|
|
23
|
+
}
|
|
24
|
+
type NotificationAnalyticsSource = NonNullable<NotificationAnalyticsPayload['source']>;
|
|
25
|
+
type NotificationAnalyticsAction = NonNullable<NotificationAnalyticsPayload['action']>;
|
|
26
|
+
type NotificationInteraction = NonNullable<NotificationAnalyticsPayload['interaction']>;
|
|
27
|
+
interface NotificationSentInput {
|
|
28
|
+
mode: 'compose' | 'template';
|
|
29
|
+
channel: NotificationChannelType;
|
|
30
|
+
type?: NotificationTypeEnum | string;
|
|
31
|
+
priority?: NotificationPriorityEnum | string;
|
|
32
|
+
recipientSource: 'manual' | 'directory';
|
|
33
|
+
recipientCount: number;
|
|
34
|
+
successCount?: number;
|
|
35
|
+
failedCount?: number;
|
|
36
|
+
scheduled: boolean;
|
|
37
|
+
includeInApp: boolean;
|
|
38
|
+
hasActions: boolean;
|
|
39
|
+
hasMedia: boolean;
|
|
40
|
+
}
|
|
41
|
+
interface TemplateSavedInput {
|
|
42
|
+
action: Extract<NotificationAnalyticsAction, 'create' | 'update'>;
|
|
43
|
+
channel?: string;
|
|
44
|
+
type?: string;
|
|
45
|
+
variableCount: number;
|
|
46
|
+
hasHtml?: boolean;
|
|
47
|
+
}
|
|
48
|
+
interface PreferenceUpdatedInput {
|
|
49
|
+
action: Extract<NotificationAnalyticsAction, 'set' | 'reset'>;
|
|
50
|
+
scope: NotificationPreferenceScope;
|
|
51
|
+
channel?: string;
|
|
52
|
+
type?: string;
|
|
53
|
+
enabled?: boolean;
|
|
54
|
+
}
|
|
55
|
+
interface ScheduleUpdatedInput {
|
|
56
|
+
action: Extract<NotificationAnalyticsAction, 'cancel' | 'reschedule'>;
|
|
57
|
+
}
|
|
58
|
+
export declare function useNotificationAnalytics(): {
|
|
59
|
+
trackNotificationOpened: (notification: Notification, source: NotificationAnalyticsSource, interaction: NotificationInteraction) => void;
|
|
60
|
+
trackPreferenceUpdated: (input: PreferenceUpdatedInput) => void;
|
|
61
|
+
trackNotificationSent: (input: NotificationSentInput) => void;
|
|
62
|
+
trackTemplateSaved: (input: TemplateSavedInput) => void;
|
|
63
|
+
trackScheduleUpdated: (input: ScheduleUpdatedInput) => void;
|
|
64
|
+
};
|
|
65
|
+
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useCallback as e } from "react";
|
|
2
2
|
import { useEventBus as t } from "@burdenoff/fe-libs/shared/events";
|
|
3
|
-
|
|
3
|
+
// src/hooks/useNotificationAnalytics.ts
|
|
4
4
|
function n(e, t, n) {
|
|
5
5
|
return {
|
|
6
6
|
source: t,
|
|
@@ -58,7 +58,6 @@ function r() {
|
|
|
58
58
|
}), [i])
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
|
-
//#endregion
|
|
62
61
|
export { r as useNotificationAnalytics };
|
|
63
62
|
|
|
64
63
|
//# sourceMappingURL=useNotificationAnalytics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationAnalytics.js","names":[],"sources":["../../src/hooks/useNotificationAnalytics.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useEventBus } from '@burdenoff/fe-libs/shared/events';\nimport type { Notification, NotificationPreferenceScope } from '../types';\nimport type {\n NotificationChannelType,\n NotificationPriorityEnum,\n NotificationTypeEnum,\n} from './useSendNotification';\n\ntype NotificationAnalyticsName =\n | 'notification.item.opened'\n | 'notification.preference.updated'\n | 'notification.admin.sent'\n | 'notification.template.saved'\n | 'notification.schedule.updated';\n\ninterface NotificationAnalyticsPayload {\n source?:\n | 'center'\n | 'panel'\n | 'history'\n | 'preferences'\n | 'admin_history'\n | 'composer'\n | 'template_editor';\n action?: 'open' | 'set' | 'reset' | 'send' | 'create' | 'update' | 'cancel' | 'reschedule';\n interaction?: 'card' | 'primary_action' | 'custom_action';\n scope?: 'GLOBAL' | 'CHANNEL' | 'TYPE' | 'TOPIC';\n channel?: string;\n type?: string;\n priority?: string;\n mode?: 'compose' | 'template';\n recipientSource?: 'manual' | 'directory';\n recipientCount?: number;\n successCount?: number;\n failedCount?: number;\n scheduled?: boolean;\n includeInApp?: boolean;\n enabled?: boolean;\n hasActions?: boolean;\n hasMedia?: boolean;\n hasHtml?: boolean;\n variableCount?: number;\n}\n\ninterface NotificationAnalyticsEventBus {\n emit: (\n name: NotificationAnalyticsName,\n payload: NotificationAnalyticsPayload,\n options?: { component?: string }\n ) => void;\n}\n\ntype NotificationAnalyticsSource = NonNullable<NotificationAnalyticsPayload['source']>;\ntype NotificationAnalyticsAction = NonNullable<NotificationAnalyticsPayload['action']>;\ntype NotificationInteraction = NonNullable<NotificationAnalyticsPayload['interaction']>;\n\ninterface NotificationSentInput {\n mode: 'compose' | 'template';\n channel: NotificationChannelType;\n type?: NotificationTypeEnum | string;\n priority?: NotificationPriorityEnum | string;\n recipientSource: 'manual' | 'directory';\n recipientCount: number;\n successCount?: number;\n failedCount?: number;\n scheduled: boolean;\n includeInApp: boolean;\n hasActions: boolean;\n hasMedia: boolean;\n}\n\ninterface TemplateSavedInput {\n action: Extract<NotificationAnalyticsAction, 'create' | 'update'>;\n channel?: string;\n type?: string;\n variableCount: number;\n hasHtml?: boolean;\n}\n\ninterface PreferenceUpdatedInput {\n action: Extract<NotificationAnalyticsAction, 'set' | 'reset'>;\n scope: NotificationPreferenceScope;\n channel?: string;\n type?: string;\n enabled?: boolean;\n}\n\ninterface ScheduleUpdatedInput {\n action: Extract<NotificationAnalyticsAction, 'cancel' | 'reschedule'>;\n}\n\nfunction toNotificationOpenPayload(\n notification: Notification,\n source: NotificationAnalyticsSource,\n interaction: NotificationInteraction\n): NotificationAnalyticsPayload {\n return {\n source,\n action: 'open',\n interaction,\n channel: notification.channel,\n type: notification.type,\n priority: notification.priority,\n hasActions: Boolean(notification.actionUrl || notification.actions.length > 0),\n hasMedia: notification.media.length > 0,\n };\n}\n\nexport function useNotificationAnalytics() {\n const eventBus = useEventBus();\n\n const emit = useCallback(\n (name: NotificationAnalyticsName, payload: NotificationAnalyticsPayload) => {\n // The runtime event bus accepts string names; this local typed facade keeps\n // notification emissions constrained to the sparse Rybbit allowlist while\n // consuming app shells roll forward to the updated fe-libs event registry.\n const notificationEventBus = eventBus as unknown as NotificationAnalyticsEventBus;\n notificationEventBus.emit(name, payload, { component: 'microfe-notification' });\n },\n [eventBus]\n );\n\n const trackNotificationOpened = useCallback(\n (\n notification: Notification,\n source: NotificationAnalyticsSource,\n interaction: NotificationInteraction\n ) =>\n emit(\n 'notification.item.opened',\n toNotificationOpenPayload(notification, source, interaction)\n ),\n [emit]\n );\n\n const trackPreferenceUpdated = useCallback(\n (input: PreferenceUpdatedInput) =>\n emit('notification.preference.updated', {\n source: 'preferences',\n action: input.action,\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n enabled: input.enabled,\n }),\n [emit]\n );\n\n const trackNotificationSent = useCallback(\n (input: NotificationSentInput) =>\n emit('notification.admin.sent', {\n source: 'composer',\n action: 'send',\n mode: input.mode,\n channel: input.channel,\n type: input.type,\n priority: input.priority,\n recipientSource: input.recipientSource,\n recipientCount: input.recipientCount,\n successCount: input.successCount,\n failedCount: input.failedCount,\n scheduled: input.scheduled,\n includeInApp: input.includeInApp,\n hasActions: input.hasActions,\n hasMedia: input.hasMedia,\n }),\n [emit]\n );\n\n const trackTemplateSaved = useCallback(\n (input: TemplateSavedInput) =>\n emit('notification.template.saved', {\n source: 'template_editor',\n action: input.action,\n channel: input.channel,\n type: input.type,\n variableCount: input.variableCount,\n hasHtml: input.hasHtml,\n }),\n [emit]\n );\n\n const trackScheduleUpdated = useCallback(\n (input: ScheduleUpdatedInput) =>\n emit('notification.schedule.updated', {\n source: 'admin_history',\n action: input.action,\n scheduled: input.action === 'reschedule',\n }),\n [emit]\n );\n\n return {\n trackNotificationOpened,\n trackPreferenceUpdated,\n trackNotificationSent,\n trackTemplateSaved,\n trackScheduleUpdated,\n };\n}\n"],"mappings":";;;AA4FA,
|
|
1
|
+
{"version":3,"file":"useNotificationAnalytics.js","names":["toNotificationOpenPayload","notification","useNotificationAnalytics","eventBus","useEventBus","emit","useCallback","name","payload","source","interaction","input"],"sources":["../../src/hooks/useNotificationAnalytics.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useEventBus } from '@burdenoff/fe-libs/shared/events';\nimport type { Notification, NotificationPreferenceScope } from '../types';\nimport type {\n NotificationChannelType,\n NotificationPriorityEnum,\n NotificationTypeEnum,\n} from './useSendNotification';\n\ntype NotificationAnalyticsName =\n | 'notification.item.opened'\n | 'notification.preference.updated'\n | 'notification.admin.sent'\n | 'notification.template.saved'\n | 'notification.schedule.updated';\n\ninterface NotificationAnalyticsPayload {\n source?:\n | 'center'\n | 'panel'\n | 'history'\n | 'preferences'\n | 'admin_history'\n | 'composer'\n | 'template_editor';\n action?: 'open' | 'set' | 'reset' | 'send' | 'create' | 'update' | 'cancel' | 'reschedule';\n interaction?: 'card' | 'primary_action' | 'custom_action';\n scope?: 'GLOBAL' | 'CHANNEL' | 'TYPE' | 'TOPIC';\n channel?: string;\n type?: string;\n priority?: string;\n mode?: 'compose' | 'template';\n recipientSource?: 'manual' | 'directory';\n recipientCount?: number;\n successCount?: number;\n failedCount?: number;\n scheduled?: boolean;\n includeInApp?: boolean;\n enabled?: boolean;\n hasActions?: boolean;\n hasMedia?: boolean;\n hasHtml?: boolean;\n variableCount?: number;\n}\n\ninterface NotificationAnalyticsEventBus {\n emit: (\n name: NotificationAnalyticsName,\n payload: NotificationAnalyticsPayload,\n options?: { component?: string }\n ) => void;\n}\n\ntype NotificationAnalyticsSource = NonNullable<NotificationAnalyticsPayload['source']>;\ntype NotificationAnalyticsAction = NonNullable<NotificationAnalyticsPayload['action']>;\ntype NotificationInteraction = NonNullable<NotificationAnalyticsPayload['interaction']>;\n\ninterface NotificationSentInput {\n mode: 'compose' | 'template';\n channel: NotificationChannelType;\n type?: NotificationTypeEnum | string;\n priority?: NotificationPriorityEnum | string;\n recipientSource: 'manual' | 'directory';\n recipientCount: number;\n successCount?: number;\n failedCount?: number;\n scheduled: boolean;\n includeInApp: boolean;\n hasActions: boolean;\n hasMedia: boolean;\n}\n\ninterface TemplateSavedInput {\n action: Extract<NotificationAnalyticsAction, 'create' | 'update'>;\n channel?: string;\n type?: string;\n variableCount: number;\n hasHtml?: boolean;\n}\n\ninterface PreferenceUpdatedInput {\n action: Extract<NotificationAnalyticsAction, 'set' | 'reset'>;\n scope: NotificationPreferenceScope;\n channel?: string;\n type?: string;\n enabled?: boolean;\n}\n\ninterface ScheduleUpdatedInput {\n action: Extract<NotificationAnalyticsAction, 'cancel' | 'reschedule'>;\n}\n\nfunction toNotificationOpenPayload(\n notification: Notification,\n source: NotificationAnalyticsSource,\n interaction: NotificationInteraction\n): NotificationAnalyticsPayload {\n return {\n source,\n action: 'open',\n interaction,\n channel: notification.channel,\n type: notification.type,\n priority: notification.priority,\n hasActions: Boolean(notification.actionUrl || notification.actions.length > 0),\n hasMedia: notification.media.length > 0,\n };\n}\n\nexport function useNotificationAnalytics() {\n const eventBus = useEventBus();\n\n const emit = useCallback(\n (name: NotificationAnalyticsName, payload: NotificationAnalyticsPayload) => {\n // The runtime event bus accepts string names; this local typed facade keeps\n // notification emissions constrained to the sparse Rybbit allowlist while\n // consuming app shells roll forward to the updated fe-libs event registry.\n const notificationEventBus = eventBus as unknown as NotificationAnalyticsEventBus;\n notificationEventBus.emit(name, payload, { component: 'microfe-notification' });\n },\n [eventBus]\n );\n\n const trackNotificationOpened = useCallback(\n (\n notification: Notification,\n source: NotificationAnalyticsSource,\n interaction: NotificationInteraction\n ) =>\n emit(\n 'notification.item.opened',\n toNotificationOpenPayload(notification, source, interaction)\n ),\n [emit]\n );\n\n const trackPreferenceUpdated = useCallback(\n (input: PreferenceUpdatedInput) =>\n emit('notification.preference.updated', {\n source: 'preferences',\n action: input.action,\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n enabled: input.enabled,\n }),\n [emit]\n );\n\n const trackNotificationSent = useCallback(\n (input: NotificationSentInput) =>\n emit('notification.admin.sent', {\n source: 'composer',\n action: 'send',\n mode: input.mode,\n channel: input.channel,\n type: input.type,\n priority: input.priority,\n recipientSource: input.recipientSource,\n recipientCount: input.recipientCount,\n successCount: input.successCount,\n failedCount: input.failedCount,\n scheduled: input.scheduled,\n includeInApp: input.includeInApp,\n hasActions: input.hasActions,\n hasMedia: input.hasMedia,\n }),\n [emit]\n );\n\n const trackTemplateSaved = useCallback(\n (input: TemplateSavedInput) =>\n emit('notification.template.saved', {\n source: 'template_editor',\n action: input.action,\n channel: input.channel,\n type: input.type,\n variableCount: input.variableCount,\n hasHtml: input.hasHtml,\n }),\n [emit]\n );\n\n const trackScheduleUpdated = useCallback(\n (input: ScheduleUpdatedInput) =>\n emit('notification.schedule.updated', {\n source: 'admin_history',\n action: input.action,\n scheduled: input.action === 'reschedule',\n }),\n [emit]\n );\n\n return {\n trackNotificationOpened,\n trackPreferenceUpdated,\n trackNotificationSent,\n trackTemplateSaved,\n trackScheduleUpdated,\n };\n}\n"],"mappings":";;;AA4FA,SAASA,EACP,GACA,GACA,GAC8B;CAC9B,OAAO;EACL;EACA,QAAQ;EACR;EACA,SAASC,EAAa;EACtB,MAAMA,EAAa;EACnB,UAAUA,EAAa;EACvB,YAAY,GAAQA,EAAa,aAAaA,EAAa,QAAQ,SAAS;EAC5E,UAAUA,EAAa,MAAM,SAAS;CACxC;AACF;AAEA,SAAgBC,IAA2B;CACzC,IAAMC,IAAWC,EAAY,GAEvBC,IAAOC,GACV,GAAiC,MAA0C;EAK1E,EAAqB,KAAKC,GAAMC,GAAS,EAAE,WAAW,uBAAuB,CAAC;CAChF,GACA,CAACL,CAAQ,CACX;CAwEA,OAAO;EACL,yBAvE8BG,GAE5B,GACA,GACA,MAEAD,EACE,4BACAL,EAA0BC,GAAcQ,GAAQC,CAAW,CAC7D,GACF,CAACL,CAAI,CA6DL;EACA,wBA3D6BC,GAC5B,MACCD,EAAK,mCAAmC;GACtC,QAAQ;GACR,QAAQM,EAAM;GACd,OAAOA,EAAM;GACb,SAASA,EAAM;GACf,MAAMA,EAAM;GACZ,SAASA,EAAM;EACjB,CAAC,GACH,CAACN,CAAI,CAiDL;EACA,uBA/C4BC,GAC3B,MACCD,EAAK,2BAA2B;GAC9B,QAAQ;GACR,QAAQ;GACR,MAAMM,EAAM;GACZ,SAASA,EAAM;GACf,MAAMA,EAAM;GACZ,UAAUA,EAAM;GAChB,iBAAiBA,EAAM;GACvB,gBAAgBA,EAAM;GACtB,cAAcA,EAAM;GACpB,aAAaA,EAAM;GACnB,WAAWA,EAAM;GACjB,cAAcA,EAAM;GACpB,YAAYA,EAAM;GAClB,UAAUA,EAAM;EAClB,CAAC,GACH,CAACN,CAAI,CA6BL;EACA,oBA3ByBC,GACxB,MACCD,EAAK,+BAA+B;GAClC,QAAQ;GACR,QAAQM,EAAM;GACd,SAASA,EAAM;GACf,MAAMA,EAAM;GACZ,eAAeA,EAAM;GACrB,SAASA,EAAM;EACjB,CAAC,GACH,CAACN,CAAI,CAiBL;EACA,sBAf2BC,GAC1B,MACCD,EAAK,iCAAiC;GACpC,QAAQ;GACR,QAAQM,EAAM;GACd,WAAWA,EAAM,WAAW;EAC9B,CAAC,GACH,CAACN,CAAI,CAQL;CACF;AACF"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { NotificationPreference, UpsertNotificationPreferenceInput } from '../types';
|
|
2
|
+
export declare function useNotificationPreferences(): {
|
|
3
|
+
preferences: NotificationPreference[];
|
|
4
|
+
preferencesByKey: Map<string, NotificationPreference>;
|
|
5
|
+
isLoading: boolean;
|
|
6
|
+
error: string | null;
|
|
7
|
+
refetch: () => Promise<void>;
|
|
8
|
+
setPreference: (input: UpsertNotificationPreferenceInput) => Promise<NotificationPreference | null>;
|
|
9
|
+
deletePreference: (id: string) => Promise<boolean>;
|
|
10
|
+
};
|