@burdenoff/microfe-notification 2026.1023.2 → 2026.1029.2
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/components/NotificationCard.js +9 -9
- package/dist/hooks/useNotificationTopics.js +40 -38
- package/dist/hooks/useNotificationTopics.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/pages/CreateNotificationPage.js +5 -5
- package/dist/pages/NotificationCenterPage.js +5 -5
- package/dist/pages/NotificationPreferencesPage.js +43 -39
- package/dist/pages/NotificationPreferencesPage.js.map +1 -1
- package/dist/pages/NotificationTopicsPage.js +35 -31
- package/dist/pages/NotificationTopicsPage.js.map +1 -1
- package/dist/pages/TemplateEditorPage.js +5 -5
- package/dist/utils/index.js +15 -8
- package/dist/utils/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { useNotificationAnalytics as e } from "../hooks/useNotificationAnalytics.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { formatRelativeTime as t, getNotificationTypeIcon as n, getPriorityColor as r, getPriorityIcon as i, truncateText as a } from "../utils/index.js";
|
|
3
|
+
import { useTr as o } from "../shared/hooks/useTr.js";
|
|
4
4
|
import { nativeImpact as s, nativeOpenUrl as c } from "../utils/nativeBridge.js";
|
|
5
5
|
import { navigateInApp as l } from "../utils/inAppNavigation.js";
|
|
6
6
|
import { ExternalLink as u, X as d } from "lucide-react";
|
|
7
7
|
import { Fragment as f, jsx as p, jsxs as m } from "react/jsx-runtime";
|
|
8
8
|
//#region src/components/NotificationCard.tsx
|
|
9
9
|
function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClick: y, showArchivedState: b = !1, compact: x = !1, analyticsSource: S = "center" }) {
|
|
10
|
-
let C =
|
|
10
|
+
let C = o(), { trackNotificationOpened: w } = e(), T = !h.readAt, E = !!h.archivedAt, D = () => {
|
|
11
11
|
w(h, S, "card"), y && y(h), T && g && g(h.id);
|
|
12
12
|
}, O = (e) => {
|
|
13
13
|
e.stopPropagation(), _ && _(h.id);
|
|
@@ -39,16 +39,16 @@ function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClic
|
|
|
39
39
|
/* @__PURE__ */ p("span", {
|
|
40
40
|
className: "text-base",
|
|
41
41
|
"aria-hidden": "true",
|
|
42
|
-
children:
|
|
42
|
+
children: n(h.type)
|
|
43
43
|
}),
|
|
44
44
|
/* @__PURE__ */ p("h3", {
|
|
45
45
|
className: `text-sm truncate ${T ? "font-bold text-primary" : "font-medium text-secondary"}`,
|
|
46
|
-
children: x ?
|
|
46
|
+
children: x ? a(h.title, 60) : h.title
|
|
47
47
|
}),
|
|
48
48
|
/* @__PURE__ */ p("span", {
|
|
49
49
|
className: "text-xs",
|
|
50
50
|
"aria-label": `Priority: ${h.priority}`,
|
|
51
|
-
children:
|
|
51
|
+
children: i(h.priority)
|
|
52
52
|
})
|
|
53
53
|
]
|
|
54
54
|
}), _ && /* @__PURE__ */ p("button", {
|
|
@@ -72,7 +72,7 @@ function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClic
|
|
|
72
72
|
}),
|
|
73
73
|
/* @__PURE__ */ p("p", {
|
|
74
74
|
className: `text-sm text-secondary ${x ? "line-clamp-2" : ""}`,
|
|
75
|
-
children: x ?
|
|
75
|
+
children: x ? a(h.body, 120) : h.body
|
|
76
76
|
}),
|
|
77
77
|
h.topic && /* @__PURE__ */ p("div", {
|
|
78
78
|
className: "mt-2 inline-flex items-center rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary",
|
|
@@ -94,14 +94,14 @@ function h({ notification: h, onMarkAsRead: g, onArchive: _, onAction: v, onClic
|
|
|
94
94
|
className: "flex items-center gap-2 text-xs text-tertiary",
|
|
95
95
|
children: [
|
|
96
96
|
/* @__PURE__ */ p("span", {
|
|
97
|
-
className:
|
|
97
|
+
className: r(h.priority),
|
|
98
98
|
children: h.priority
|
|
99
99
|
}),
|
|
100
100
|
b && E && /* @__PURE__ */ m(f, { children: [/* @__PURE__ */ p("span", { children: "•" }), /* @__PURE__ */ p("span", { children: C("notifCommon.archived", "Archived") })] }),
|
|
101
101
|
/* @__PURE__ */ p("span", { children: "•" }),
|
|
102
102
|
/* @__PURE__ */ p("time", {
|
|
103
103
|
dateTime: h.createdAt,
|
|
104
|
-
children:
|
|
104
|
+
children: t(h.createdAt, C)
|
|
105
105
|
})
|
|
106
106
|
]
|
|
107
107
|
}), h.actionUrl && /* @__PURE__ */ m("button", {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { useNotification as e } from "../providers/NotificationProvider.js";
|
|
2
2
|
import { getGlobalNotificationClient as t } from "../graphql/global-client.js";
|
|
3
3
|
import { CreateNotificationTopicDocument as n, DeleteNotificationTopicDocument as r, GetNotificationTopicsDocument as i, SetNotificationTopicSubscriptionDocument as a, UpdateNotificationTopicDocument as o } from "../generated/global-operations.js";
|
|
4
|
-
import {
|
|
4
|
+
import { isPermissionError as s } from "../utils/index.js";
|
|
5
|
+
import { useCallback as c, useEffect as l, useState as u } from "react";
|
|
5
6
|
//#region src/hooks/useNotificationTopics.ts
|
|
6
|
-
function
|
|
7
|
+
function d(e) {
|
|
7
8
|
return {
|
|
8
9
|
id: e.id,
|
|
9
10
|
slug: e.slug,
|
|
@@ -24,44 +25,45 @@ function u(e) {
|
|
|
24
25
|
updatedAt: e.updatedAt
|
|
25
26
|
};
|
|
26
27
|
}
|
|
27
|
-
function
|
|
28
|
-
let { authToken:
|
|
29
|
-
|
|
28
|
+
function f(f) {
|
|
29
|
+
let { authToken: p, apiGatewayUrl: m } = e(), [h, g] = u([]), [_, v] = u(!1), [y, b] = u(null), [x, S] = u(!1), [C, w] = u(f || {}), T = c(() => t(m ?? void 0, p ?? void 0), [m, p]), E = c(async () => {
|
|
30
|
+
v(!0), b(null), S(!1);
|
|
30
31
|
try {
|
|
31
|
-
|
|
32
|
+
g(((await T().query({
|
|
32
33
|
query: i,
|
|
33
34
|
variables: {
|
|
34
35
|
filter: {
|
|
35
|
-
...
|
|
36
|
-
...
|
|
37
|
-
...
|
|
36
|
+
...C.search ? { search: C.search } : {},
|
|
37
|
+
...C.type ? { type: C.type } : {},
|
|
38
|
+
...C.isActive === void 0 ? {} : { isActive: C.isActive }
|
|
38
39
|
},
|
|
39
40
|
limit: 100,
|
|
40
41
|
offset: 0
|
|
41
42
|
},
|
|
42
|
-
fetchPolicy: "
|
|
43
|
-
})).data?.notificationTopics.items || []).map(
|
|
43
|
+
fetchPolicy: "network-only"
|
|
44
|
+
})).data?.notificationTopics.items || []).map(d));
|
|
44
45
|
} catch (e) {
|
|
45
|
-
console.error("[useNotificationTopics] Failed to fetch topics:", e),
|
|
46
|
+
s(e) ? S(!0) : (console.error("[useNotificationTopics] Failed to fetch topics:", e), b(e instanceof Error ? e.message : "Failed to fetch topics")), g([]);
|
|
46
47
|
} finally {
|
|
47
|
-
|
|
48
|
+
v(!1);
|
|
48
49
|
}
|
|
49
|
-
}, [
|
|
50
|
-
return
|
|
51
|
-
|
|
52
|
-
}, [
|
|
53
|
-
topics:
|
|
54
|
-
isLoading:
|
|
55
|
-
error:
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
50
|
+
}, [C, T]);
|
|
51
|
+
return l(() => {
|
|
52
|
+
E();
|
|
53
|
+
}, [E]), {
|
|
54
|
+
topics: h,
|
|
55
|
+
isLoading: _,
|
|
56
|
+
error: y,
|
|
57
|
+
isForbidden: x,
|
|
58
|
+
filter: C,
|
|
59
|
+
setFilter: w,
|
|
60
|
+
refetch: E,
|
|
61
|
+
createTopic: c(async (e) => {
|
|
62
|
+
let t = await T().mutate({
|
|
61
63
|
mutation: n,
|
|
62
64
|
variables: { input: e }
|
|
63
65
|
});
|
|
64
|
-
await
|
|
66
|
+
await E();
|
|
65
67
|
let r = t.data?.createNotificationTopic;
|
|
66
68
|
return r ? {
|
|
67
69
|
id: r.id,
|
|
@@ -74,16 +76,16 @@ function d(d) {
|
|
|
74
76
|
createdAt: r.createdAt,
|
|
75
77
|
updatedAt: r.updatedAt
|
|
76
78
|
} : null;
|
|
77
|
-
}, [
|
|
78
|
-
updateTopic:
|
|
79
|
-
let n = await
|
|
79
|
+
}, [E, T]),
|
|
80
|
+
updateTopic: c(async (e, t) => {
|
|
81
|
+
let n = await T().mutate({
|
|
80
82
|
mutation: o,
|
|
81
83
|
variables: {
|
|
82
84
|
id: e,
|
|
83
85
|
input: t
|
|
84
86
|
}
|
|
85
87
|
});
|
|
86
|
-
await
|
|
88
|
+
await E();
|
|
87
89
|
let r = n.data?.updateNotificationTopic;
|
|
88
90
|
return r ? {
|
|
89
91
|
id: r.id,
|
|
@@ -96,20 +98,20 @@ function d(d) {
|
|
|
96
98
|
createdAt: r.createdAt,
|
|
97
99
|
updatedAt: r.updatedAt
|
|
98
100
|
} : null;
|
|
99
|
-
}, [
|
|
100
|
-
deleteTopic:
|
|
101
|
+
}, [E, T]),
|
|
102
|
+
deleteTopic: c(async (e) => (await T().mutate({
|
|
101
103
|
mutation: r,
|
|
102
104
|
variables: { id: e }
|
|
103
|
-
}), await
|
|
104
|
-
setTopicSubscription:
|
|
105
|
-
let n = await
|
|
105
|
+
}), await E(), !0), [E, T]),
|
|
106
|
+
setTopicSubscription: c(async (e, t) => {
|
|
107
|
+
let n = await T().mutate({
|
|
106
108
|
mutation: a,
|
|
107
109
|
variables: { input: {
|
|
108
110
|
topicId: e,
|
|
109
111
|
subscribed: t
|
|
110
112
|
} }
|
|
111
113
|
});
|
|
112
|
-
await
|
|
114
|
+
await E();
|
|
113
115
|
let r = n.data?.setNotificationTopicSubscription;
|
|
114
116
|
return r ? {
|
|
115
117
|
id: r.id,
|
|
@@ -118,10 +120,10 @@ function d(d) {
|
|
|
118
120
|
topicId: r.topicId,
|
|
119
121
|
userId: r.userId
|
|
120
122
|
} : null;
|
|
121
|
-
}, [
|
|
123
|
+
}, [E, T])
|
|
122
124
|
};
|
|
123
125
|
}
|
|
124
126
|
//#endregion
|
|
125
|
-
export {
|
|
127
|
+
export { f as useNotificationTopics };
|
|
126
128
|
|
|
127
129
|
//# sourceMappingURL=useNotificationTopics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationTopics.js","names":[],"sources":["../../src/hooks/useNotificationTopics.ts"],"sourcesContent":["import { useState, useEffect, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationTopic, NotificationTopicSubscription } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTopicsQuery,\n CreateNotificationTopicMutation,\n UpdateNotificationTopicMutation,\n SetNotificationTopicSubscriptionMutation,\n} from '../generated/global-operations';\n\nexport interface NotificationTopicFilter {\n search?: string;\n type?: string;\n isActive?: boolean;\n}\n\nexport interface CreateNotificationTopicInput {\n name: string;\n slug: string;\n description?: string;\n type: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateNotificationTopicInput {\n name?: string;\n slug?: string;\n description?: string;\n type?: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nfunction mapTopic(\n topic: GetNotificationTopicsQuery['notificationTopics']['items'][number]\n): NotificationTopic {\n return {\n id: topic.id,\n slug: topic.slug,\n name: topic.name,\n description: topic.description ?? undefined,\n type: topic.type as NotificationTopic['type'],\n isActive: topic.isActive,\n metadata: topic.metadata ?? undefined,\n subscriberCount: topic.subscriberCount ?? 0,\n mySubscription: topic.mySubscription\n ? {\n id: topic.mySubscription.id,\n subscribed: topic.mySubscription.subscribed,\n unsubscribedAt: topic.mySubscription.unsubscribedAt ?? undefined,\n topicId: topic.mySubscription.topicId,\n userId: topic.mySubscription.userId,\n }\n : undefined,\n createdAt: topic.createdAt,\n updatedAt: topic.updatedAt,\n };\n}\n\nexport function useNotificationTopics(initialFilter?: NotificationTopicFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [topics, setTopics] = useState<NotificationTopic[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [filter, setFilter] = useState<NotificationTopicFilter>(initialFilter || {});\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchTopics = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTopicsQuery>({\n query: NotificationOps.GetNotificationTopicsDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search } : {}),\n ...(filter.type ? { type: filter.type } : {}),\n ...(filter.isActive !== undefined ? { isActive: filter.isActive } : {}),\n },\n limit: 100,\n offset: 0,\n },\n fetchPolicy: 'cache-first',\n });\n\n setTopics((result.data?.notificationTopics.items || []).map(mapTopic));\n } catch (err) {\n console.error('[useNotificationTopics] Failed to fetch topics:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch topics');\n setTopics([]);\n } finally {\n setIsLoading(false);\n }\n }, [filter, getClient]);\n\n useEffect(() => {\n fetchTopics();\n }, [fetchTopics]);\n\n const createTopic = useCallback(\n async (input: CreateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTopicMutation>({\n mutation: NotificationOps.CreateNotificationTopicDocument,\n variables: { input },\n });\n await fetchTopics();\n const created = result.data?.createNotificationTopic;\n return created\n ? {\n id: created.id,\n slug: created.slug,\n name: created.name,\n description: created.description ?? undefined,\n type: created.type as NotificationTopic['type'],\n isActive: created.isActive,\n subscriberCount: 0,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const updateTopic = useCallback(\n async (id: string, input: UpdateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTopicMutation>({\n mutation: NotificationOps.UpdateNotificationTopicDocument,\n variables: { id, input },\n });\n await fetchTopics();\n const updated = result.data?.updateNotificationTopic;\n return updated\n ? {\n id: updated.id,\n slug: updated.slug,\n name: updated.name,\n description: updated.description ?? undefined,\n type: updated.type as NotificationTopic['type'],\n isActive: updated.isActive,\n subscriberCount: 0,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const deleteTopic = useCallback(\n async (id: string): Promise<boolean> => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTopicDocument,\n variables: { id },\n });\n await fetchTopics();\n return true;\n },\n [fetchTopics, getClient]\n );\n\n const setTopicSubscription = useCallback(\n async (topicId: string, subscribed: boolean): Promise<NotificationTopicSubscription | null> => {\n const client = getClient();\n const result = await client.mutate<SetNotificationTopicSubscriptionMutation>({\n mutation: NotificationOps.SetNotificationTopicSubscriptionDocument,\n variables: {\n input: {\n topicId,\n subscribed,\n },\n },\n });\n await fetchTopics();\n\n const subscription = result.data?.setNotificationTopicSubscription;\n return subscription\n ? {\n id: subscription.id,\n subscribed: subscription.subscribed,\n unsubscribedAt: subscription.unsubscribedAt ?? undefined,\n topicId: subscription.topicId,\n userId: subscription.userId,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n return {\n topics,\n isLoading,\n error,\n filter,\n setFilter,\n refetch: fetchTopics,\n createTopic,\n updateTopic,\n deleteTopic,\n setTopicSubscription,\n };\n}\n"],"mappings":";;;;;AAoCA,SAAS,EACP,GACmB;AACnB,QAAO;EACL,IAAI,EAAM;EACV,MAAM,EAAM;EACZ,MAAM,EAAM;EACZ,aAAa,EAAM,eAAe,KAAA;EAClC,MAAM,EAAM;EACZ,UAAU,EAAM;EAChB,UAAU,EAAM,YAAY,KAAA;EAC5B,iBAAiB,EAAM,mBAAmB;EAC1C,gBAAgB,EAAM,iBAClB;GACE,IAAI,EAAM,eAAe;GACzB,YAAY,EAAM,eAAe;GACjC,gBAAgB,EAAM,eAAe,kBAAkB,K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Aa;IACtB,QAAQ,EAAa;IACtB,GACD;KAEN,CAAC,GAAa,EAAU,CACzB;EAaA"}
|
|
1
|
+
{"version":3,"file":"useNotificationTopics.js","names":[],"sources":["../../src/hooks/useNotificationTopics.ts"],"sourcesContent":["import { useState, useEffect, useCallback } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationTopic, NotificationTopicSubscription } from '../types';\nimport { isPermissionError } from '../utils';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTopicsQuery,\n CreateNotificationTopicMutation,\n UpdateNotificationTopicMutation,\n SetNotificationTopicSubscriptionMutation,\n} from '../generated/global-operations';\n\nexport interface NotificationTopicFilter {\n search?: string;\n type?: string;\n isActive?: boolean;\n}\n\nexport interface CreateNotificationTopicInput {\n name: string;\n slug: string;\n description?: string;\n type: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateNotificationTopicInput {\n name?: string;\n slug?: string;\n description?: string;\n type?: string;\n isActive?: boolean;\n metadata?: Record<string, unknown>;\n}\n\nfunction mapTopic(\n topic: GetNotificationTopicsQuery['notificationTopics']['items'][number]\n): NotificationTopic {\n return {\n id: topic.id,\n slug: topic.slug,\n name: topic.name,\n description: topic.description ?? undefined,\n type: topic.type as NotificationTopic['type'],\n isActive: topic.isActive,\n metadata: topic.metadata ?? undefined,\n subscriberCount: topic.subscriberCount ?? 0,\n mySubscription: topic.mySubscription\n ? {\n id: topic.mySubscription.id,\n subscribed: topic.mySubscription.subscribed,\n unsubscribedAt: topic.mySubscription.unsubscribedAt ?? undefined,\n topicId: topic.mySubscription.topicId,\n userId: topic.mySubscription.userId,\n }\n : undefined,\n createdAt: topic.createdAt,\n updatedAt: topic.updatedAt,\n };\n}\n\nexport function useNotificationTopics(initialFilter?: NotificationTopicFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [topics, setTopics] = useState<NotificationTopic[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n // True when the gateway denied `notificationTopics` (no notification-topic\n // read). Pages show a no-access state instead of \"no topics\" (BOFF-10104).\n const [isForbidden, setIsForbidden] = useState(false);\n const [filter, setFilter] = useState<NotificationTopicFilter>(initialFilter || {});\n\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n const fetchTopics = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n setIsForbidden(false);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTopicsQuery>({\n query: NotificationOps.GetNotificationTopicsDocument,\n variables: {\n filter: {\n ...(filter.search ? { search: filter.search } : {}),\n ...(filter.type ? { type: filter.type } : {}),\n ...(filter.isActive !== undefined ? { isActive: filter.isActive } : {}),\n },\n limit: 100,\n offset: 0,\n },\n // Always revalidate: access to topics can be revoked while the app is\n // open, and a cached list would hide the FORBIDDEN (BOFF-10104).\n fetchPolicy: 'network-only',\n });\n\n setTopics((result.data?.notificationTopics.items || []).map(mapTopic));\n } catch (err) {\n // A denial is a handled state (isForbidden), not a load error.\n if (isPermissionError(err)) {\n setIsForbidden(true);\n } else {\n console.error('[useNotificationTopics] Failed to fetch topics:', err);\n setError(err instanceof Error ? err.message : 'Failed to fetch topics');\n }\n setTopics([]);\n } finally {\n setIsLoading(false);\n }\n }, [filter, getClient]);\n\n useEffect(() => {\n fetchTopics();\n }, [fetchTopics]);\n\n const createTopic = useCallback(\n async (input: CreateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTopicMutation>({\n mutation: NotificationOps.CreateNotificationTopicDocument,\n variables: { input },\n });\n await fetchTopics();\n const created = result.data?.createNotificationTopic;\n return created\n ? {\n id: created.id,\n slug: created.slug,\n name: created.name,\n description: created.description ?? undefined,\n type: created.type as NotificationTopic['type'],\n isActive: created.isActive,\n subscriberCount: 0,\n createdAt: created.createdAt,\n updatedAt: created.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const updateTopic = useCallback(\n async (id: string, input: UpdateNotificationTopicInput): Promise<NotificationTopic | null> => {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTopicMutation>({\n mutation: NotificationOps.UpdateNotificationTopicDocument,\n variables: { id, input },\n });\n await fetchTopics();\n const updated = result.data?.updateNotificationTopic;\n return updated\n ? {\n id: updated.id,\n slug: updated.slug,\n name: updated.name,\n description: updated.description ?? undefined,\n type: updated.type as NotificationTopic['type'],\n isActive: updated.isActive,\n subscriberCount: 0,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n const deleteTopic = useCallback(\n async (id: string): Promise<boolean> => {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTopicDocument,\n variables: { id },\n });\n await fetchTopics();\n return true;\n },\n [fetchTopics, getClient]\n );\n\n const setTopicSubscription = useCallback(\n async (topicId: string, subscribed: boolean): Promise<NotificationTopicSubscription | null> => {\n const client = getClient();\n const result = await client.mutate<SetNotificationTopicSubscriptionMutation>({\n mutation: NotificationOps.SetNotificationTopicSubscriptionDocument,\n variables: {\n input: {\n topicId,\n subscribed,\n },\n },\n });\n await fetchTopics();\n\n const subscription = result.data?.setNotificationTopicSubscription;\n return subscription\n ? {\n id: subscription.id,\n subscribed: subscription.subscribed,\n unsubscribedAt: subscription.unsubscribedAt ?? undefined,\n topicId: subscription.topicId,\n userId: subscription.userId,\n }\n : null;\n },\n [fetchTopics, getClient]\n );\n\n return {\n topics,\n isLoading,\n error,\n isForbidden,\n filter,\n setFilter,\n refetch: fetchTopics,\n createTopic,\n updateTopic,\n deleteTopic,\n setTopicSubscription,\n };\n}\n"],"mappings":";;;;;;AAqCA,SAAS,EACP,GACmB;AACnB,QAAO;EACL,IAAI,EAAM;EACV,MAAM,EAAM;EACZ,MAAM,EAAM;EACZ,aAAa,EAAM,eAAe,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AAa,EAAU,CACzB;EAyCC,sBAvC2B,EAC3B,OAAO,GAAiB,MAAuE;GAE7F,IAAM,IAAS,MADA,GAAW,CACE,OAAiD;IAC3E,UAAU;IACV,WAAW,EACT,OAAO;KACL;KACA;KACD,EACF;IACF,CAAC;AACF,SAAM,GAAa;GAEnB,IAAM,IAAe,EAAO,MAAM;AAClC,UAAO,IACH;IACE,IAAI,EAAa;IACjB,YAAY,EAAa;IACzB,gBAAgB,EAAa,kBAAkB,KAAA;IAC/C,SAAS,EAAa;IACtB,QAAQ,EAAa;IACtB,GACD;KAEN,CAAC,GAAa,EAAU,CACzB;EAcA"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { useNotification as e } from "./providers/NotificationProvider.js";
|
|
2
2
|
import { useNotificationStore as t } from "./store/notificationStore.js";
|
|
3
3
|
import { useNotifications as n } from "./hooks/useNotifications.js";
|
|
4
|
-
import "./hooks/index.js";
|
|
5
4
|
import { filterNotifications as r, formatRelativeTime as i, getNotificationTypeIcon as a, getNotificationTypeLabel as o, getPriorityColor as s, getPriorityIcon as c, groupNotificationsByDate as l, sortNotificationsByDate as u, substituteTemplateVariables as d, truncateText as f, validateTemplateVariables as p } from "./utils/index.js";
|
|
5
|
+
import "./hooks/index.js";
|
|
6
6
|
import { NotificationCard as m } from "./components/NotificationCard.js";
|
|
7
7
|
import { NotificationRoot as h } from "./NotificationRoot.js";
|
|
8
8
|
import { UserNotificationRoot as g } from "./UserNotificationRoot.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useNotificationAnalytics as e } from "../hooks/useNotificationAnalytics.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { isPermissionError as t } from "../utils/index.js";
|
|
3
|
+
import { useNotificationTopics as n } from "../hooks/useNotificationTopics.js";
|
|
4
|
+
import { useTr as r } from "../shared/hooks/useTr.js";
|
|
5
5
|
import { nativeImpact as ee, nativeNotify as i } from "../utils/nativeBridge.js";
|
|
6
6
|
import { NOTIFICATION_PERMISSIONS as te } from "../constants/permissions.js";
|
|
7
7
|
import { useSendNotification as ne } from "../hooks/useSendNotification.js";
|
|
@@ -176,7 +176,7 @@ var Oe = [
|
|
|
176
176
|
}
|
|
177
177
|
];
|
|
178
178
|
function Ne() {
|
|
179
|
-
let ge = xe(), l =
|
|
179
|
+
let ge = xe(), l = r(), { hasPermission: ve, isLoading: Ne, refreshPermissions: Pe } = se(), { showToast: Fe } = oe(), { sendNotification: Ie, sendBatch: Le, sendWithTemplate: Re, isSending: p, error: ze, lastResult: Be, clearError: Ve, clearResult: He } = ne(), { templates: m, isLoading: Ue } = re(), { trackNotificationSent: We } = e(), { searchUsers: h, fetchAllUsers: Ge, results: g, isLoading: Ke, error: _ } = ie(), { topics: qe } = n({ isActive: !0 }), [v, Je] = o("compose"), [y, Ye] = o("EMAIL"), [b, Xe] = o("MARKETING"), [x, Ze] = o("MEDIUM"), [S, Qe] = o([]), [C, w] = o("manual"), [T, E] = o([]), [D, O] = o(!1), [k, $e] = o(""), [A, et] = o(""), [j, tt] = o(""), [M, nt] = o(""), [N, rt] = o(""), [it, at] = o(!1), [P, ot] = o(""), [st, F] = o([{
|
|
180
180
|
url: "",
|
|
181
181
|
label: "",
|
|
182
182
|
kind: "image"
|
|
@@ -354,7 +354,7 @@ function Ne() {
|
|
|
354
354
|
}))?.status && (n(1, 0), Y(!0), i("success"));
|
|
355
355
|
}
|
|
356
356
|
} catch (e) {
|
|
357
|
-
if (i("error"),
|
|
357
|
+
if (i("error"), t(e)) {
|
|
358
358
|
Ve(), Fe(l("notifications.permissionDeniedOnSend", "You don't have permission to send that notification. Refreshing access…"), "warning"), Pe().catch((e) => console.warn("[permissions] refresh failed after send denial:", e));
|
|
359
359
|
return;
|
|
360
360
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { useNotification as e } from "../providers/NotificationProvider.js";
|
|
2
2
|
import { useNotifications as t } from "../hooks/useNotifications.js";
|
|
3
|
-
import {
|
|
3
|
+
import { filterNotifications as n, groupNotificationsByDate as r } from "../utils/index.js";
|
|
4
|
+
import { useNotificationTopics as i } from "../hooks/useNotificationTopics.js";
|
|
4
5
|
import "../hooks/index.js";
|
|
5
|
-
import { useTr as
|
|
6
|
-
import { filterNotifications as i, groupNotificationsByDate as a } from "../utils/index.js";
|
|
6
|
+
import { useTr as a } from "../shared/hooks/useTr.js";
|
|
7
7
|
import { NotificationCard as o } from "../components/NotificationCard.js";
|
|
8
8
|
import { NOTIFICATION_PERMISSIONS as s } from "../constants/permissions.js";
|
|
9
9
|
import { useMemo as c } from "react";
|
|
@@ -60,10 +60,10 @@ var w = {
|
|
|
60
60
|
}
|
|
61
61
|
];
|
|
62
62
|
function O() {
|
|
63
|
-
let O =
|
|
63
|
+
let O = a(), { hasPermission: k, isLoading: A } = l(), { currentUser: j } = e(), { notifications: M, unreadCount: N, notificationFilter: P, markAsRead: F, markAllAsRead: I, archiveNotification: L, recordAction: R, updateFilter: z, resetFilter: B } = t({
|
|
64
64
|
baseFilter: w,
|
|
65
65
|
unreadFilter: T
|
|
66
|
-
}), { topics: V } =
|
|
66
|
+
}), { topics: V } = i({ isActive: !0 }), H = c(() => n(M, P), [M, P]), U = c(() => r(H, O), [H, O]);
|
|
67
67
|
return A ? /* @__PURE__ */ m("div", {
|
|
68
68
|
className: "flex h-64 items-center justify-center",
|
|
69
69
|
children: /* @__PURE__ */ m("div", { className: "h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" })
|
|
@@ -69,76 +69,76 @@ function T(e) {
|
|
|
69
69
|
return e.scope === "CHANNEL" ? `CHANNEL:${e.channel || ""}` : e.scope === "TYPE" ? `TYPE:${e.type || ""}` : e.scope === "TOPIC" ? `TOPIC:${e.topicId || ""}` : "GLOBAL";
|
|
70
70
|
}
|
|
71
71
|
function E() {
|
|
72
|
-
let E = i(), { hasPermission: D, isLoading: O } = f(), { currentUser: k } = e(), { topics: A, isLoading: j } = r({
|
|
72
|
+
let E = i(), { hasPermission: D, isLoading: O } = f(), { currentUser: k } = e(), { topics: A, isLoading: j, isForbidden: M } = r({
|
|
73
73
|
type: "MARKETING",
|
|
74
74
|
isActive: !0
|
|
75
|
-
}), { preferencesByKey:
|
|
75
|
+
}), { preferencesByKey: N, isLoading: P, setPreference: F, deletePreference: I } = n(), { trackPreferenceUpdated: L } = t(), [R, z] = d(""), [B, V] = d(null), [H, U] = d(null), W = u(null), G = j || P;
|
|
76
76
|
c(() => () => {
|
|
77
|
-
|
|
77
|
+
W.current && clearTimeout(W.current);
|
|
78
78
|
}, []);
|
|
79
|
-
let
|
|
80
|
-
|
|
81
|
-
|
|
79
|
+
let K = (e) => {
|
|
80
|
+
W.current && clearTimeout(W.current), U(e), W.current = setTimeout(() => {
|
|
81
|
+
U((t) => t?.key === e.key ? null : t), W.current = null;
|
|
82
82
|
}, 2500);
|
|
83
|
-
},
|
|
84
|
-
if (!
|
|
85
|
-
let e =
|
|
83
|
+
}, q = l(() => {
|
|
84
|
+
if (!R.trim()) return A;
|
|
85
|
+
let e = R.toLowerCase();
|
|
86
86
|
return A.filter((t) => t.name.toLowerCase().includes(e) || t.slug.toLowerCase().includes(e) || t.description?.toLowerCase().includes(e));
|
|
87
|
-
}, [
|
|
88
|
-
let t = T(e), n =
|
|
89
|
-
|
|
87
|
+
}, [R, A]), J = async (e) => {
|
|
88
|
+
let t = T(e), n = N.get(t), r = !(n?.enabled ?? !0);
|
|
89
|
+
V(t), a("medium");
|
|
90
90
|
try {
|
|
91
|
-
await
|
|
91
|
+
await F({
|
|
92
92
|
...e,
|
|
93
93
|
enabled: r,
|
|
94
94
|
frequency: n?.frequency || "IMMEDIATE"
|
|
95
|
-
}),
|
|
95
|
+
}), L({
|
|
96
96
|
action: "set",
|
|
97
97
|
scope: e.scope,
|
|
98
98
|
channel: e.channel,
|
|
99
99
|
type: e.type,
|
|
100
100
|
enabled: r
|
|
101
|
-
}),
|
|
101
|
+
}), K({
|
|
102
102
|
key: t,
|
|
103
103
|
type: "success",
|
|
104
104
|
message: E("notifications.preferenceSaved", "Preference saved.")
|
|
105
105
|
}), o("success");
|
|
106
106
|
} catch {
|
|
107
|
-
|
|
107
|
+
K({
|
|
108
108
|
key: t,
|
|
109
109
|
type: "error",
|
|
110
110
|
message: E("notifications.preferenceSaveFailed", "Could not save preference.")
|
|
111
111
|
}), o("error");
|
|
112
112
|
} finally {
|
|
113
|
-
|
|
113
|
+
V(null);
|
|
114
114
|
}
|
|
115
|
-
},
|
|
116
|
-
let t =
|
|
115
|
+
}, Y = async (e) => {
|
|
116
|
+
let t = N.get(e);
|
|
117
117
|
if (t) {
|
|
118
|
-
|
|
118
|
+
V(e);
|
|
119
119
|
try {
|
|
120
|
-
await
|
|
120
|
+
await I(t.id), L({
|
|
121
121
|
action: "reset",
|
|
122
122
|
scope: t.scope,
|
|
123
123
|
channel: t.channel,
|
|
124
124
|
type: t.type
|
|
125
|
-
}),
|
|
125
|
+
}), K({
|
|
126
126
|
key: e,
|
|
127
127
|
type: "success",
|
|
128
128
|
message: E("notifications.preferenceReset", "Preference reset.")
|
|
129
129
|
});
|
|
130
130
|
} catch {
|
|
131
|
-
|
|
131
|
+
K({
|
|
132
132
|
key: e,
|
|
133
133
|
type: "error",
|
|
134
134
|
message: E("notifications.preferenceResetFailed", "Could not reset preference.")
|
|
135
135
|
});
|
|
136
136
|
} finally {
|
|
137
|
-
|
|
137
|
+
V(null);
|
|
138
138
|
}
|
|
139
139
|
}
|
|
140
|
-
},
|
|
141
|
-
let t =
|
|
140
|
+
}, X = (e) => {
|
|
141
|
+
let t = N.get(e.key), n = t?.enabled ?? !0, r = B === e.key, i = H?.key === e.key ? H : null;
|
|
142
142
|
return /* @__PURE__ */ v("div", {
|
|
143
143
|
className: "rounded-lg border border-border-seam bg-gloss-card p-4 transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop)]",
|
|
144
144
|
children: [/* @__PURE__ */ v("div", {
|
|
@@ -170,14 +170,14 @@ function E() {
|
|
|
170
170
|
children: [t && /* @__PURE__ */ _("button", {
|
|
171
171
|
type: "button",
|
|
172
172
|
disabled: r,
|
|
173
|
-
onClick: () =>
|
|
173
|
+
onClick: () => Y(e.key),
|
|
174
174
|
className: "rounded-md border border-default px-3 py-2 text-sm text-secondary hover:bg-bg-sunken disabled:cursor-not-allowed disabled:opacity-50",
|
|
175
175
|
children: E("notifications.reset", "Reset")
|
|
176
176
|
}), /* @__PURE__ */ v("button", {
|
|
177
177
|
type: "button",
|
|
178
178
|
"aria-pressed": n,
|
|
179
179
|
disabled: r,
|
|
180
|
-
onClick: () =>
|
|
180
|
+
onClick: () => J({
|
|
181
181
|
scope: e.scope,
|
|
182
182
|
channel: e.channel,
|
|
183
183
|
type: e.type,
|
|
@@ -224,7 +224,7 @@ function E() {
|
|
|
224
224
|
children: [/* @__PURE__ */ _("h2", {
|
|
225
225
|
className: "text-sm font-semibold uppercase tracking-wide text-tertiary",
|
|
226
226
|
children: E("notifications.globalPreferences", "Global")
|
|
227
|
-
}),
|
|
227
|
+
}), X({
|
|
228
228
|
key: "GLOBAL",
|
|
229
229
|
scope: "GLOBAL",
|
|
230
230
|
title: E("notifications.allNotifications", "All notifications"),
|
|
@@ -242,7 +242,7 @@ function E() {
|
|
|
242
242
|
children: E("notifications.channelPreferences", "Channels")
|
|
243
243
|
}), /* @__PURE__ */ _("div", {
|
|
244
244
|
className: "grid gap-3 lg:grid-cols-2",
|
|
245
|
-
children: C.map((e) =>
|
|
245
|
+
children: C.map((e) => X({
|
|
246
246
|
key: `CHANNEL:${e.value}`,
|
|
247
247
|
scope: "CHANNEL",
|
|
248
248
|
channel: e.value,
|
|
@@ -258,7 +258,7 @@ function E() {
|
|
|
258
258
|
children: E("notifications.typePreferences", "Notification Types")
|
|
259
259
|
}), /* @__PURE__ */ _("div", {
|
|
260
260
|
className: "grid gap-3 lg:grid-cols-2",
|
|
261
|
-
children: w.map((e) =>
|
|
261
|
+
children: w.map((e) => X({
|
|
262
262
|
key: `TYPE:${e.value}`,
|
|
263
263
|
scope: "TYPE",
|
|
264
264
|
type: e.value,
|
|
@@ -275,8 +275,8 @@ function E() {
|
|
|
275
275
|
className: "absolute left-3 top-1/2 -translate-y-1/2 text-tertiary"
|
|
276
276
|
}), /* @__PURE__ */ _("input", {
|
|
277
277
|
type: "text",
|
|
278
|
-
value:
|
|
279
|
-
onChange: (e) =>
|
|
278
|
+
value: R,
|
|
279
|
+
onChange: (e) => z(e.target.value),
|
|
280
280
|
"aria-label": E("notifications.searchTopics", "Search topics..."),
|
|
281
281
|
placeholder: E("notifications.searchTopics", "Search topics..."),
|
|
282
282
|
className: "w-full rounded-lg border border-default bg-surface py-2 pl-9 pr-4 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-accent"
|
|
@@ -288,14 +288,18 @@ function E() {
|
|
|
288
288
|
children: [/* @__PURE__ */ _("h2", {
|
|
289
289
|
className: "text-sm font-semibold uppercase tracking-wide text-tertiary",
|
|
290
290
|
children: E("notifications.topicPreferences", "Topics")
|
|
291
|
-
}),
|
|
291
|
+
}), G ? /* @__PURE__ */ _("div", {
|
|
292
292
|
className: "rounded-lg border border-default bg-surface p-6 text-sm text-secondary",
|
|
293
293
|
children: E("notifications.loadingPreferences", "Loading preferences...")
|
|
294
|
-
}) :
|
|
295
|
-
illustration:
|
|
296
|
-
title:
|
|
297
|
-
description:
|
|
298
|
-
}) :
|
|
294
|
+
}) : M ? /* @__PURE__ */ _(b, {
|
|
295
|
+
illustration: "empty-generic",
|
|
296
|
+
title: E("notifications.topicsNoAccessTitle", "You don't have access to notification topics"),
|
|
297
|
+
description: E("notifications.topicsNoAccessDescription", "Your role doesn't include permission to read notification topics. Ask a workspace admin if you need access.")
|
|
298
|
+
}) : q.length === 0 ? /* @__PURE__ */ _(b, {
|
|
299
|
+
illustration: R.trim() ? "empty-search" : "empty-data",
|
|
300
|
+
title: R.trim() ? E("notifications.noTopicsFound", "No topics match your search") : E("notifications.noTopicsAvailableTitle", "No subscribable topics yet"),
|
|
301
|
+
description: R.trim() ? E("notifications.adjustSearchOrDateRange", "Try adjusting your filters") : E("notifications.noTopicsAvailableDescription", "When marketing topics are published you can subscribe or unsubscribe from each one here.")
|
|
302
|
+
}) : q.map((e) => X({
|
|
299
303
|
key: `TOPIC:${e.id}`,
|
|
300
304
|
scope: "TOPIC",
|
|
301
305
|
topicId: e.id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationPreferencesPage.js","names":[],"sources":["../../src/pages/NotificationPreferencesPage.tsx"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\nimport { BellRing, Search, ToggleLeft, ToggleRight } from 'lucide-react';\nimport { usePermissions } from '@burdenoff/fe-libs/shared/providers/shell';\nimport {\n EmphasisPanel,\n IllustratedEmptyState,\n OptionalFields,\n PagePurpose,\n} from '@burdenoff/fe-libs/ui';\nimport { useNotificationPreferences, useNotificationTopics } from '../hooks';\nimport { useNotificationAnalytics } from '../hooks/useNotificationAnalytics';\nimport { NOTIFICATION_PERMISSIONS } from '../constants/permissions';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { useTr } from '../shared/hooks/useTr';\nimport type { NotificationChannel, NotificationPreferenceScope, NotificationType } from '../types';\nimport { nativeImpact, nativeNotify } from '../utils/nativeBridge';\n\nconst CHANNEL_OPTIONS: Array<{ value: NotificationChannel; labelKey: string; label: string }> = [\n { value: 'IN_APP', labelKey: 'notifications.channelInApp', label: 'In-app' },\n { value: 'EMAIL', labelKey: 'notifications.channelEmail', label: 'Email' },\n { value: 'PUSH', labelKey: 'notifications.channelPush', label: 'Push' },\n { value: 'SMS', labelKey: 'notifications.channelSms', label: 'SMS' },\n { value: 'WHATSAPP', labelKey: 'notifications.channelWhatsapp', label: 'WhatsApp' },\n { value: 'SLACK', labelKey: 'notifications.channelSlack', label: 'Slack' },\n];\n\nconst TYPE_OPTIONS: Array<{ value: NotificationType; labelKey: string; label: string }> = [\n { value: 'TRANSACTIONAL', labelKey: 'notifications.typeTransactional', label: 'Transactional' },\n { value: 'SYSTEM', labelKey: 'notifications.typeSystem', label: 'System' },\n { value: 'ALERT', labelKey: 'notifications.typeAlert', label: 'Alerts' },\n { value: 'MARKETING', labelKey: 'notifications.typeMarketing', label: 'Marketing' },\n];\n\nfunction preferenceKey(input: {\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n}) {\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\nexport function NotificationPreferencesPage() {\n const tr = useTr();\n const { hasPermission, isLoading: permissionsLoading } = usePermissions();\n const { currentUser } = useNotification();\n const { topics, isLoading: topicsLoading } = useNotificationTopics({\n type: 'MARKETING',\n isActive: true,\n });\n const {\n preferencesByKey,\n isLoading: preferencesLoading,\n setPreference,\n deletePreference,\n } = useNotificationPreferences();\n const { trackPreferenceUpdated } = useNotificationAnalytics();\n const [search, setSearch] = useState('');\n const [savingKey, setSavingKey] = useState<string | null>(null);\n const [saveFeedback, setSaveFeedback] = useState<{\n key: string;\n type: 'success' | 'error';\n message: string;\n } | null>(null);\n const feedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const isLoading = topicsLoading || preferencesLoading;\n\n useEffect(() => {\n return () => {\n if (feedbackTimerRef.current) {\n clearTimeout(feedbackTimerRef.current);\n }\n };\n }, []);\n\n const showSaveFeedback = (feedback: {\n key: string;\n type: 'success' | 'error';\n message: string;\n }) => {\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 filteredTopics = useMemo(() => {\n if (!search.trim()) {\n return topics;\n }\n\n const query = search.toLowerCase();\n return topics.filter(\n (topic) =>\n topic.name.toLowerCase().includes(query) ||\n topic.slug.toLowerCase().includes(query) ||\n topic.description?.toLowerCase().includes(query)\n );\n }, [search, topics]);\n\n const togglePreference = async (input: {\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n }) => {\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 const renderPreferenceRow = (input: {\n key: string;\n title: string;\n description: string;\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n }) => {\n const existing = preferencesByKey.get(input.key);\n const isEnabled = existing?.enabled ?? true;\n const isSaving = savingKey === input.key;\n const feedback = saveFeedback?.key === input.key ? saveFeedback : null;\n\n return (\n <div\n key={input.key}\n className=\"rounded-lg border border-border-seam bg-gloss-card p-4 transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop)]\"\n >\n <div className=\"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between\">\n <div className=\"space-y-1\">\n <div className=\"flex items-center gap-2\">\n <BellRing size={16} className=\"text-accent-primary\" />\n <h2 className=\"text-sm font-semibold text-primary\">{input.title}</h2>\n {existing && (\n <span className=\"rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary\">\n {existing.frequency.replace('_', ' ').toLowerCase()}\n </span>\n )}\n </div>\n <p className=\"text-sm text-secondary\">{input.description}</p>\n </div>\n\n <div className=\"flex items-center gap-2\">\n {existing && (\n <button\n type=\"button\"\n disabled={isSaving}\n onClick={() => resetPreference(input.key)}\n className=\"rounded-md border border-default px-3 py-2 text-sm text-secondary hover:bg-bg-sunken disabled:cursor-not-allowed disabled:opacity-50\"\n >\n {tr('notifications.reset', 'Reset')}\n </button>\n )}\n <button\n type=\"button\"\n aria-pressed={isEnabled}\n disabled={isSaving}\n onClick={() =>\n togglePreference({\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n topicId: input.topicId,\n })\n }\n className={`inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium transition-colors ${\n isEnabled\n ? 'border-accent-primary bg-action-primary-bg text-text-inverse hover:opacity-90'\n : 'border-default bg-bg-sunken text-secondary hover:bg-bg-sunken/80'\n } disabled:cursor-not-allowed disabled:opacity-50`}\n >\n {isEnabled ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}\n {isSaving\n ? tr('notifications.saving', 'Saving...')\n : isEnabled\n ? tr('notifications.enabled', 'Enabled')\n : tr('notifications.disabled', 'Disabled')}\n </button>\n </div>\n </div>\n <div className=\"mt-3 min-h-5\" aria-live=\"polite\">\n {feedback && (\n <p className={`text-xs ${feedback.type === 'success' ? 'text-success' : 'text-error'}`}>\n {feedback.message}\n </p>\n )}\n </div>\n </div>\n );\n };\n\n if (permissionsLoading) {\n return (\n <div className=\"flex h-64 items-center justify-center\">\n <div className=\"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent\" />\n </div>\n );\n }\n\n if (!hasPermission(NOTIFICATION_PERMISSIONS.NOTIFICATION_LIST) && !currentUser?.id) {\n return (\n <div className=\"p-8 text-center text-text-secondary\">\n {tr(\n 'notifications.noPermissionPreferences',\n \"You don't have permission to manage notification preferences.\"\n )}\n </div>\n );\n }\n\n return (\n <div data-tour=\"notification-preferences-page\" className=\"space-y-6 p-4 sm:p-6\">\n <div>\n <h1 className=\"text-2xl font-bold text-primary\">\n {tr('notifications.preferencesTitle', 'Notification Preferences')}\n </h1>\n <p className=\"mt-1 text-sm text-secondary\">\n {tr(\n 'notifications.preferencesSubtitle',\n 'Control global, channel, type, and topic-level notification delivery.'\n )}\n </p>\n </div>\n\n <PagePurpose icon={<BellRing size={16} />}>\n {tr(\n 'notifications.preferencesPurpose',\n 'Decide how and when we reach you. The Global switch is your master on/off, then you can fine-tune individual channels (email, push, SMS…), notification types and the marketing topics you have subscribed to. Settings cascade — turning a channel off silences it everywhere.'\n )}\n </PagePurpose>\n\n <EmphasisPanel data-tour=\"notification-preferences-global\" className=\"space-y-3 p-5 sm:p-6\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.globalPreferences', 'Global')}\n </h2>\n {renderPreferenceRow({\n key: 'GLOBAL',\n scope: 'GLOBAL',\n title: tr('notifications.allNotifications', 'All notifications'),\n description: tr(\n 'notifications.allNotificationsDescription',\n 'Master preference for notification delivery across all channels and types.'\n ),\n })}\n </EmphasisPanel>\n\n {/* Advanced: per-channel filter rules / quiet hours / custom templates — collapse the long-tail knobs */}\n <OptionalFields\n title={tr('notifications.advancedPreferences', 'Advanced settings')}\n description={tr(\n 'notifications.advancedPreferencesDescription',\n 'Per-channel filter rules, notification-type filters, and quiet-hour overrides.'\n )}\n >\n <section data-tour=\"notification-preferences-channels\" className=\"space-y-3\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.channelPreferences', 'Channels')}\n </h2>\n <div className=\"grid gap-3 lg:grid-cols-2\">\n {CHANNEL_OPTIONS.map((channel) =>\n renderPreferenceRow({\n key: `CHANNEL:${channel.value}`,\n scope: 'CHANNEL',\n channel: channel.value,\n title: tr(channel.labelKey, channel.label),\n description: tr(\n 'notifications.channelPreferenceDescription',\n 'Control delivery for this channel.'\n ),\n })\n )}\n </div>\n </section>\n\n <section data-tour=\"notification-preferences-types\" className=\"mt-6 space-y-3\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.typePreferences', 'Notification Types')}\n </h2>\n <div className=\"grid gap-3 lg:grid-cols-2\">\n {TYPE_OPTIONS.map((type) =>\n renderPreferenceRow({\n key: `TYPE:${type.value}`,\n scope: 'TYPE',\n type: type.value,\n title: tr(type.labelKey, type.label),\n description: tr(\n 'notifications.typePreferenceDescription',\n 'Control delivery for this notification type.'\n ),\n })\n )}\n </div>\n </section>\n </OptionalFields>\n\n <div className=\"relative max-w-xl\">\n <Search size={16} className=\"absolute left-3 top-1/2 -translate-y-1/2 text-tertiary\" />\n <input\n type=\"text\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n aria-label={tr('notifications.searchTopics', 'Search topics...')}\n placeholder={tr('notifications.searchTopics', 'Search topics...')}\n className=\"w-full rounded-lg border border-default bg-surface py-2 pl-9 pr-4 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </div>\n\n <section data-tour=\"notification-preferences-topics\" className=\"space-y-3\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.topicPreferences', 'Topics')}\n </h2>\n {isLoading ? (\n <div className=\"rounded-lg border border-default bg-surface p-6 text-sm text-secondary\">\n {tr('notifications.loadingPreferences', 'Loading preferences...')}\n </div>\n ) : filteredTopics.length === 0 ? (\n <IllustratedEmptyState\n illustration={search.trim() ? 'empty-search' : 'empty-data'}\n title={\n search.trim()\n ? tr('notifications.noTopicsFound', 'No topics match your search')\n : tr('notifications.noTopicsAvailableTitle', 'No subscribable topics yet')\n }\n description={\n search.trim()\n ? tr('notifications.adjustSearchOrDateRange', 'Try adjusting your filters')\n : tr(\n 'notifications.noTopicsAvailableDescription',\n 'When marketing topics are published you can subscribe or unsubscribe from each one here.'\n )\n }\n />\n ) : (\n filteredTopics.map((topic) =>\n renderPreferenceRow({\n key: `TOPIC:${topic.id}`,\n scope: 'TOPIC',\n topicId: topic.id,\n title: topic.name,\n description: topic.description || topic.slug,\n })\n )\n )}\n </section>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,IAAM,IAA0F;CAC9F;EAAE,OAAO;EAAU,UAAU;EAA8B,OAAO;EAAU;CAC5E;EAAE,OAAO;EAAS,UAAU;EAA8B,OAAO;EAAS;CAC1E;EAAE,OAAO;EAAQ,UAAU;EAA6B,OAAO;EAAQ;CACvE;EAAE,OAAO;EAAO,UAAU;EAA4B,OAAO;EAAO;CACpE;EAAE,OAAO;EAAY,UAAU;EAAiC,OAAO;EAAY;CACnF;EAAE,OAAO;EAAS,UAAU;EAA8B,OAAO;EAAS;CAC3E,EAEK,IAAoF;CACxF;EAAE,OAAO;EAAiB,UAAU;EAAmC,OAAO;EAAiB;CAC/F;EAAE,OAAO;EAAU,UAAU;EAA4B,OAAO;EAAU;CAC1E;EAAE,OAAO;EAAS,UAAU;EAA2B,OAAO;EAAU;CACxE;EAAE,OAAO;EAAa,UAAU;EAA+B,OAAO;EAAa;CACpF;AAED,SAAS,EAAc,GAKpB;AAID,QAHI,EAAM,UAAU,YAAkB,WAAW,EAAM,WAAW,OAC9D,EAAM,UAAU,SAAe,QAAQ,EAAM,QAAQ,OACrD,EAAM,UAAU,UAAgB,SAAS,EAAM,WAAW,OACvD;;AAGT,SAAgB,IAA8B;CAC5C,IAAM,IAAK,GAAO,EACZ,EAAE,kBAAe,WAAW,MAAuB,GAAgB,EACnE,EAAE,m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8BAA8B,mBAAmB;KAChE,aAAa,EAAG,8BAA8B,mBAAmB;KACjE,WAAU;KACV,CAAA,CACE;;GAEN,kBAAC,WAAD;IAAS,aAAU;IAAkC,WAAU;cAA/D,CACE,kBAAC,MAAD;KAAI,WAAU;eACX,EAAG,kCAAkC,SAAS;KAC5C,CAAA,EACJ,IACC,kBAAC,OAAD;KAAK,WAAU;eACZ,EAAG,oCAAoC,yBAAyB;KAC7D,CAAA,GACJ,EAAe,WAAW,IAC5B,kBAAC,GAAD;KACE,cAAc,EAAO,MAAM,GAAG,iBAAiB;KAC/C,OACE,EAAO,MAAM,GACT,EAAG,+BAA+B,8BAA8B,GAChE,EAAG,wCAAwC,6BAA6B;KAE9E,aACE,EAAO,MAAM,GACT,EAAG,yCAAyC,6BAA6B,GACzE,EACE,8CACA,2FACD;KAEP,CAAA,GAEF,EAAe,KAAK,MAClB,EAAoB;KAClB,KAAK,SAAS,EAAM;KACpB,OAAO;KACP,SAAS,EAAM;KACf,OAAO,EAAM;KACb,aAAa,EAAM,eAAe,EAAM;KACzC,CAAC,CACH,CAEK;;GACN"}
|
|
1
|
+
{"version":3,"file":"NotificationPreferencesPage.js","names":[],"sources":["../../src/pages/NotificationPreferencesPage.tsx"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from 'react';\nimport { BellRing, Search, ToggleLeft, ToggleRight } from 'lucide-react';\nimport { usePermissions } from '@burdenoff/fe-libs/shared/providers/shell';\nimport {\n EmphasisPanel,\n IllustratedEmptyState,\n OptionalFields,\n PagePurpose,\n} from '@burdenoff/fe-libs/ui';\nimport { useNotificationPreferences, useNotificationTopics } from '../hooks';\nimport { useNotificationAnalytics } from '../hooks/useNotificationAnalytics';\nimport { NOTIFICATION_PERMISSIONS } from '../constants/permissions';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { useTr } from '../shared/hooks/useTr';\nimport type { NotificationChannel, NotificationPreferenceScope, NotificationType } from '../types';\nimport { nativeImpact, nativeNotify } from '../utils/nativeBridge';\n\nconst CHANNEL_OPTIONS: Array<{ value: NotificationChannel; labelKey: string; label: string }> = [\n { value: 'IN_APP', labelKey: 'notifications.channelInApp', label: 'In-app' },\n { value: 'EMAIL', labelKey: 'notifications.channelEmail', label: 'Email' },\n { value: 'PUSH', labelKey: 'notifications.channelPush', label: 'Push' },\n { value: 'SMS', labelKey: 'notifications.channelSms', label: 'SMS' },\n { value: 'WHATSAPP', labelKey: 'notifications.channelWhatsapp', label: 'WhatsApp' },\n { value: 'SLACK', labelKey: 'notifications.channelSlack', label: 'Slack' },\n];\n\nconst TYPE_OPTIONS: Array<{ value: NotificationType; labelKey: string; label: string }> = [\n { value: 'TRANSACTIONAL', labelKey: 'notifications.typeTransactional', label: 'Transactional' },\n { value: 'SYSTEM', labelKey: 'notifications.typeSystem', label: 'System' },\n { value: 'ALERT', labelKey: 'notifications.typeAlert', label: 'Alerts' },\n { value: 'MARKETING', labelKey: 'notifications.typeMarketing', label: 'Marketing' },\n];\n\nfunction preferenceKey(input: {\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n}) {\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\nexport function NotificationPreferencesPage() {\n const tr = useTr();\n const { hasPermission, isLoading: permissionsLoading } = usePermissions();\n const { currentUser } = useNotification();\n const {\n topics,\n isLoading: topicsLoading,\n isForbidden: topicsForbidden,\n } = useNotificationTopics({\n type: 'MARKETING',\n isActive: true,\n });\n const {\n preferencesByKey,\n isLoading: preferencesLoading,\n setPreference,\n deletePreference,\n } = useNotificationPreferences();\n const { trackPreferenceUpdated } = useNotificationAnalytics();\n const [search, setSearch] = useState('');\n const [savingKey, setSavingKey] = useState<string | null>(null);\n const [saveFeedback, setSaveFeedback] = useState<{\n key: string;\n type: 'success' | 'error';\n message: string;\n } | null>(null);\n const feedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const isLoading = topicsLoading || preferencesLoading;\n\n useEffect(() => {\n return () => {\n if (feedbackTimerRef.current) {\n clearTimeout(feedbackTimerRef.current);\n }\n };\n }, []);\n\n const showSaveFeedback = (feedback: {\n key: string;\n type: 'success' | 'error';\n message: string;\n }) => {\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 filteredTopics = useMemo(() => {\n if (!search.trim()) {\n return topics;\n }\n\n const query = search.toLowerCase();\n return topics.filter(\n (topic) =>\n topic.name.toLowerCase().includes(query) ||\n topic.slug.toLowerCase().includes(query) ||\n topic.description?.toLowerCase().includes(query)\n );\n }, [search, topics]);\n\n const togglePreference = async (input: {\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n }) => {\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 const renderPreferenceRow = (input: {\n key: string;\n title: string;\n description: string;\n scope: NotificationPreferenceScope;\n channel?: NotificationChannel;\n type?: NotificationType;\n topicId?: string;\n }) => {\n const existing = preferencesByKey.get(input.key);\n const isEnabled = existing?.enabled ?? true;\n const isSaving = savingKey === input.key;\n const feedback = saveFeedback?.key === input.key ? saveFeedback : null;\n\n return (\n <div\n key={input.key}\n className=\"rounded-lg border border-border-seam bg-gloss-card p-4 transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop)]\"\n >\n <div className=\"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between\">\n <div className=\"space-y-1\">\n <div className=\"flex items-center gap-2\">\n <BellRing size={16} className=\"text-accent-primary\" />\n <h2 className=\"text-sm font-semibold text-primary\">{input.title}</h2>\n {existing && (\n <span className=\"rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary\">\n {existing.frequency.replace('_', ' ').toLowerCase()}\n </span>\n )}\n </div>\n <p className=\"text-sm text-secondary\">{input.description}</p>\n </div>\n\n <div className=\"flex items-center gap-2\">\n {existing && (\n <button\n type=\"button\"\n disabled={isSaving}\n onClick={() => resetPreference(input.key)}\n className=\"rounded-md border border-default px-3 py-2 text-sm text-secondary hover:bg-bg-sunken disabled:cursor-not-allowed disabled:opacity-50\"\n >\n {tr('notifications.reset', 'Reset')}\n </button>\n )}\n <button\n type=\"button\"\n aria-pressed={isEnabled}\n disabled={isSaving}\n onClick={() =>\n togglePreference({\n scope: input.scope,\n channel: input.channel,\n type: input.type,\n topicId: input.topicId,\n })\n }\n className={`inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium transition-colors ${\n isEnabled\n ? 'border-accent-primary bg-action-primary-bg text-text-inverse hover:opacity-90'\n : 'border-default bg-bg-sunken text-secondary hover:bg-bg-sunken/80'\n } disabled:cursor-not-allowed disabled:opacity-50`}\n >\n {isEnabled ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}\n {isSaving\n ? tr('notifications.saving', 'Saving...')\n : isEnabled\n ? tr('notifications.enabled', 'Enabled')\n : tr('notifications.disabled', 'Disabled')}\n </button>\n </div>\n </div>\n <div className=\"mt-3 min-h-5\" aria-live=\"polite\">\n {feedback && (\n <p className={`text-xs ${feedback.type === 'success' ? 'text-success' : 'text-error'}`}>\n {feedback.message}\n </p>\n )}\n </div>\n </div>\n );\n };\n\n if (permissionsLoading) {\n return (\n <div className=\"flex h-64 items-center justify-center\">\n <div className=\"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent\" />\n </div>\n );\n }\n\n if (!hasPermission(NOTIFICATION_PERMISSIONS.NOTIFICATION_LIST) && !currentUser?.id) {\n return (\n <div className=\"p-8 text-center text-text-secondary\">\n {tr(\n 'notifications.noPermissionPreferences',\n \"You don't have permission to manage notification preferences.\"\n )}\n </div>\n );\n }\n\n return (\n <div data-tour=\"notification-preferences-page\" className=\"space-y-6 p-4 sm:p-6\">\n <div>\n <h1 className=\"text-2xl font-bold text-primary\">\n {tr('notifications.preferencesTitle', 'Notification Preferences')}\n </h1>\n <p className=\"mt-1 text-sm text-secondary\">\n {tr(\n 'notifications.preferencesSubtitle',\n 'Control global, channel, type, and topic-level notification delivery.'\n )}\n </p>\n </div>\n\n <PagePurpose icon={<BellRing size={16} />}>\n {tr(\n 'notifications.preferencesPurpose',\n 'Decide how and when we reach you. The Global switch is your master on/off, then you can fine-tune individual channels (email, push, SMS…), notification types and the marketing topics you have subscribed to. Settings cascade — turning a channel off silences it everywhere.'\n )}\n </PagePurpose>\n\n <EmphasisPanel data-tour=\"notification-preferences-global\" className=\"space-y-3 p-5 sm:p-6\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.globalPreferences', 'Global')}\n </h2>\n {renderPreferenceRow({\n key: 'GLOBAL',\n scope: 'GLOBAL',\n title: tr('notifications.allNotifications', 'All notifications'),\n description: tr(\n 'notifications.allNotificationsDescription',\n 'Master preference for notification delivery across all channels and types.'\n ),\n })}\n </EmphasisPanel>\n\n {/* Advanced: per-channel filter rules / quiet hours / custom templates — collapse the long-tail knobs */}\n <OptionalFields\n title={tr('notifications.advancedPreferences', 'Advanced settings')}\n description={tr(\n 'notifications.advancedPreferencesDescription',\n 'Per-channel filter rules, notification-type filters, and quiet-hour overrides.'\n )}\n >\n <section data-tour=\"notification-preferences-channels\" className=\"space-y-3\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.channelPreferences', 'Channels')}\n </h2>\n <div className=\"grid gap-3 lg:grid-cols-2\">\n {CHANNEL_OPTIONS.map((channel) =>\n renderPreferenceRow({\n key: `CHANNEL:${channel.value}`,\n scope: 'CHANNEL',\n channel: channel.value,\n title: tr(channel.labelKey, channel.label),\n description: tr(\n 'notifications.channelPreferenceDescription',\n 'Control delivery for this channel.'\n ),\n })\n )}\n </div>\n </section>\n\n <section data-tour=\"notification-preferences-types\" className=\"mt-6 space-y-3\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.typePreferences', 'Notification Types')}\n </h2>\n <div className=\"grid gap-3 lg:grid-cols-2\">\n {TYPE_OPTIONS.map((type) =>\n renderPreferenceRow({\n key: `TYPE:${type.value}`,\n scope: 'TYPE',\n type: type.value,\n title: tr(type.labelKey, type.label),\n description: tr(\n 'notifications.typePreferenceDescription',\n 'Control delivery for this notification type.'\n ),\n })\n )}\n </div>\n </section>\n </OptionalFields>\n\n <div className=\"relative max-w-xl\">\n <Search size={16} className=\"absolute left-3 top-1/2 -translate-y-1/2 text-tertiary\" />\n <input\n type=\"text\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n aria-label={tr('notifications.searchTopics', 'Search topics...')}\n placeholder={tr('notifications.searchTopics', 'Search topics...')}\n className=\"w-full rounded-lg border border-default bg-surface py-2 pl-9 pr-4 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </div>\n\n <section data-tour=\"notification-preferences-topics\" className=\"space-y-3\">\n <h2 className=\"text-sm font-semibold uppercase tracking-wide text-tertiary\">\n {tr('notifications.topicPreferences', 'Topics')}\n </h2>\n {isLoading ? (\n <div className=\"rounded-lg border border-default bg-surface p-6 text-sm text-secondary\">\n {tr('notifications.loadingPreferences', 'Loading preferences...')}\n </div>\n ) : topicsForbidden ? (\n <IllustratedEmptyState\n illustration=\"empty-generic\"\n title={tr(\n 'notifications.topicsNoAccessTitle',\n \"You don't have access to notification topics\"\n )}\n description={tr(\n 'notifications.topicsNoAccessDescription',\n \"Your role doesn't include permission to read notification topics. Ask a workspace admin if you need access.\"\n )}\n />\n ) : filteredTopics.length === 0 ? (\n <IllustratedEmptyState\n illustration={search.trim() ? 'empty-search' : 'empty-data'}\n title={\n search.trim()\n ? tr('notifications.noTopicsFound', 'No topics match your search')\n : tr('notifications.noTopicsAvailableTitle', 'No subscribable topics yet')\n }\n description={\n search.trim()\n ? tr('notifications.adjustSearchOrDateRange', 'Try adjusting your filters')\n : tr(\n 'notifications.noTopicsAvailableDescription',\n 'When marketing topics are published you can subscribe or unsubscribe from each one here.'\n )\n }\n />\n ) : (\n filteredTopics.map((topic) =>\n renderPreferenceRow({\n key: `TOPIC:${topic.id}`,\n scope: 'TOPIC',\n topicId: topic.id,\n title: topic.name,\n description: topic.description || topic.slug,\n })\n )\n )}\n </section>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,IAAM,IAA0F;CAC9F;EAAE,OAAO;EAAU,UAAU;EAA8B,OAAO;EAAU;CAC5E;EAAE,OAAO;EAAS,UAAU;EAA8B,OAAO;EAAS;CAC1E;EAAE,OAAO;EAAQ,UAAU;EAA6B,OAAO;EAAQ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BAA6B,GACzE,EACE,8CACA,2FACD;KAEP,CAAA,GAEF,EAAe,KAAK,MAClB,EAAoB;KAClB,KAAK,SAAS,EAAM;KACpB,OAAO;KACP,SAAS,EAAM;KACf,OAAO,EAAM;KACb,aAAa,EAAM,eAAe,EAAM;KACzC,CAAC,CACH,CAEK;;GACN"}
|
|
@@ -34,21 +34,21 @@ function v(e) {
|
|
|
34
34
|
return e.toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-");
|
|
35
35
|
}
|
|
36
36
|
function y() {
|
|
37
|
-
let y = t(), { hasPermission: b, isLoading: x } = a(), { topics: S, isLoading: C,
|
|
37
|
+
let y = t(), { hasPermission: b, isLoading: x } = a(), { topics: S, isLoading: C, isForbidden: w, createTopic: T, updateTopic: E, deleteTopic: D } = e(), [O, k] = i(""), [A, j] = i(null), [M, N] = i({
|
|
38
38
|
name: "",
|
|
39
39
|
slug: "",
|
|
40
40
|
description: "",
|
|
41
41
|
type: "MARKETING",
|
|
42
42
|
isActive: !0
|
|
43
|
-
}),
|
|
44
|
-
if (!
|
|
45
|
-
let e =
|
|
43
|
+
}), P = b(n.NOTIFICATION_CREATE), F = r(() => {
|
|
44
|
+
if (!O.trim()) return S;
|
|
45
|
+
let e = O.toLowerCase();
|
|
46
46
|
return S.filter((t) => t.name.toLowerCase().includes(e) || t.slug.toLowerCase().includes(e) || t.description?.toLowerCase().includes(e));
|
|
47
|
-
}, [
|
|
47
|
+
}, [O, S]);
|
|
48
48
|
return x ? /* @__PURE__ */ u("div", {
|
|
49
49
|
className: "flex h-64 items-center justify-center",
|
|
50
50
|
children: /* @__PURE__ */ u("div", { className: "h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" })
|
|
51
|
-
}) :
|
|
51
|
+
}) : P ? /* @__PURE__ */ d("div", {
|
|
52
52
|
className: "space-y-6 p-4 sm:p-6",
|
|
53
53
|
children: [
|
|
54
54
|
/* @__PURE__ */ d("div", { children: [/* @__PURE__ */ u("h1", {
|
|
@@ -70,7 +70,7 @@ function y() {
|
|
|
70
70
|
label: y("notifications.topicsNextNameLabel", "Name your first topic"),
|
|
71
71
|
description: y("notifications.topicsNextNameDesc", "Use the form to add a clear topic like \"Product updates\" — the slug is generated for you."),
|
|
72
72
|
onClick: () => {
|
|
73
|
-
|
|
73
|
+
j(null), N((e) => ({
|
|
74
74
|
...e,
|
|
75
75
|
name: "",
|
|
76
76
|
slug: "",
|
|
@@ -105,7 +105,7 @@ function y() {
|
|
|
105
105
|
children: /* @__PURE__ */ d("form", {
|
|
106
106
|
className: "space-y-4",
|
|
107
107
|
onSubmit: async (e) => {
|
|
108
|
-
e.preventDefault(), !(!
|
|
108
|
+
e.preventDefault(), !(!M.name.trim() || !M.slug.trim()) && (A ? await E(A, M) : await T(M), j(null), N({
|
|
109
109
|
name: "",
|
|
110
110
|
slug: "",
|
|
111
111
|
description: "",
|
|
@@ -121,7 +121,7 @@ function y() {
|
|
|
121
121
|
className: "text-accent-primary"
|
|
122
122
|
}), /* @__PURE__ */ u("h2", {
|
|
123
123
|
className: "text-base font-semibold text-primary",
|
|
124
|
-
children:
|
|
124
|
+
children: A ? y("notifications.editTopic", "Edit Topic") : y("notifications.createTopic", "Create Topic")
|
|
125
125
|
})]
|
|
126
126
|
}),
|
|
127
127
|
/* @__PURE__ */ d("label", {
|
|
@@ -129,11 +129,11 @@ function y() {
|
|
|
129
129
|
children: [/* @__PURE__ */ u("span", { children: y("notifications.topicName", "Name") }), /* @__PURE__ */ u("input", {
|
|
130
130
|
id: "notification-topic-name",
|
|
131
131
|
type: "text",
|
|
132
|
-
value:
|
|
133
|
-
onChange: (e) =>
|
|
132
|
+
value: M.name,
|
|
133
|
+
onChange: (e) => N((t) => ({
|
|
134
134
|
...t,
|
|
135
135
|
name: e.target.value,
|
|
136
|
-
slug:
|
|
136
|
+
slug: A ? t.slug : v(e.target.value)
|
|
137
137
|
})),
|
|
138
138
|
className: "w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent"
|
|
139
139
|
})]
|
|
@@ -142,8 +142,8 @@ function y() {
|
|
|
142
142
|
className: "block space-y-1 text-sm text-secondary",
|
|
143
143
|
children: [/* @__PURE__ */ u("span", { children: y("notifications.topicSlug", "Slug") }), /* @__PURE__ */ u("input", {
|
|
144
144
|
type: "text",
|
|
145
|
-
value:
|
|
146
|
-
onChange: (e) =>
|
|
145
|
+
value: M.slug,
|
|
146
|
+
onChange: (e) => N((t) => ({
|
|
147
147
|
...t,
|
|
148
148
|
slug: v(e.target.value)
|
|
149
149
|
})),
|
|
@@ -154,8 +154,8 @@ function y() {
|
|
|
154
154
|
className: "block space-y-1 text-sm text-secondary",
|
|
155
155
|
children: [/* @__PURE__ */ u("span", { children: y("notifications.topicType", "Type") }), /* @__PURE__ */ u("select", {
|
|
156
156
|
id: "notification-topic-type",
|
|
157
|
-
value:
|
|
158
|
-
onChange: (e) =>
|
|
157
|
+
value: M.type,
|
|
158
|
+
onChange: (e) => N((t) => ({
|
|
159
159
|
...t,
|
|
160
160
|
type: e.target.value
|
|
161
161
|
})),
|
|
@@ -169,8 +169,8 @@ function y() {
|
|
|
169
169
|
/* @__PURE__ */ d("label", {
|
|
170
170
|
className: "block space-y-1 text-sm text-secondary",
|
|
171
171
|
children: [/* @__PURE__ */ u("span", { children: y("notifications.topicDescription", "Description") }), /* @__PURE__ */ u("textarea", {
|
|
172
|
-
value:
|
|
173
|
-
onChange: (e) =>
|
|
172
|
+
value: M.description,
|
|
173
|
+
onChange: (e) => N((t) => ({
|
|
174
174
|
...t,
|
|
175
175
|
description: e.target.value
|
|
176
176
|
})),
|
|
@@ -182,8 +182,8 @@ function y() {
|
|
|
182
182
|
className: "flex items-center gap-2 text-sm text-secondary",
|
|
183
183
|
children: [/* @__PURE__ */ u("input", {
|
|
184
184
|
type: "checkbox",
|
|
185
|
-
checked:
|
|
186
|
-
onChange: (e) =>
|
|
185
|
+
checked: M.isActive,
|
|
186
|
+
onChange: (e) => N((t) => ({
|
|
187
187
|
...t,
|
|
188
188
|
isActive: e.target.checked
|
|
189
189
|
}))
|
|
@@ -194,11 +194,11 @@ function y() {
|
|
|
194
194
|
children: [/* @__PURE__ */ d("button", {
|
|
195
195
|
type: "submit",
|
|
196
196
|
className: "inline-flex items-center gap-2 rounded-md bg-accent-primary px-4 py-2 text-sm font-medium text-white hover:opacity-90",
|
|
197
|
-
children: [/* @__PURE__ */ u(s, { size: 16 }),
|
|
198
|
-
}),
|
|
197
|
+
children: [/* @__PURE__ */ u(s, { size: 16 }), A ? y("notifications.saveTopic", "Save Topic") : y("notifications.createTopicButton", "Create Topic")]
|
|
198
|
+
}), A && /* @__PURE__ */ u("button", {
|
|
199
199
|
type: "button",
|
|
200
200
|
onClick: () => {
|
|
201
|
-
|
|
201
|
+
j(null), N({
|
|
202
202
|
name: "",
|
|
203
203
|
slug: "",
|
|
204
204
|
description: "",
|
|
@@ -222,8 +222,8 @@ function y() {
|
|
|
222
222
|
className: "absolute left-3 top-1/2 -translate-y-1/2 text-tertiary"
|
|
223
223
|
}), /* @__PURE__ */ u("input", {
|
|
224
224
|
type: "text",
|
|
225
|
-
value:
|
|
226
|
-
onChange: (e) =>
|
|
225
|
+
value: O,
|
|
226
|
+
onChange: (e) => k(e.target.value),
|
|
227
227
|
placeholder: y("notifications.searchTopics", "Search topics..."),
|
|
228
228
|
className: "w-full rounded-md border border-default bg-bg-canvas py-2 pl-9 pr-4 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-accent"
|
|
229
229
|
})]
|
|
@@ -232,11 +232,15 @@ function y() {
|
|
|
232
232
|
children: C ? /* @__PURE__ */ u("div", {
|
|
233
233
|
className: "text-sm text-secondary",
|
|
234
234
|
children: y("notifications.loadingTopics", "Loading topics...")
|
|
235
|
-
}) :
|
|
236
|
-
illustration:
|
|
235
|
+
}) : w ? /* @__PURE__ */ u(m, {
|
|
236
|
+
illustration: "empty-generic",
|
|
237
|
+
title: y("notifications.topicsNoAccessTitle", "You don't have access to notification topics"),
|
|
238
|
+
description: y("notifications.topicsNoAccessDescription", "Your role doesn't include permission to read notification topics. Ask a workspace admin if you need access.")
|
|
239
|
+
}) : F.length === 0 ? /* @__PURE__ */ u(m, {
|
|
240
|
+
illustration: O.trim() ? "empty-search" : "empty-data",
|
|
237
241
|
title: y("notifications.noTopicsFound", "No topics found."),
|
|
238
|
-
description:
|
|
239
|
-
}) :
|
|
242
|
+
description: O.trim() ? y("notifications.adjustSearchOrDateRange", "Try adjusting your filters") : y("notifications.noTopicsYet", "No notification topics have been created yet.")
|
|
243
|
+
}) : F.map((e) => /* @__PURE__ */ d("div", {
|
|
240
244
|
className: "flex flex-col gap-3 rounded-lg border border-border-seam bg-surface p-4 transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop)] sm:flex-row sm:items-start sm:justify-between",
|
|
241
245
|
children: [/* @__PURE__ */ d("div", {
|
|
242
246
|
className: "space-y-1",
|
|
@@ -276,7 +280,7 @@ function y() {
|
|
|
276
280
|
children: [/* @__PURE__ */ u("button", {
|
|
277
281
|
type: "button",
|
|
278
282
|
onClick: () => {
|
|
279
|
-
|
|
283
|
+
j(e.id), N({
|
|
280
284
|
name: e.name,
|
|
281
285
|
slug: e.slug,
|
|
282
286
|
description: e.description || "",
|
|
@@ -288,7 +292,7 @@ function y() {
|
|
|
288
292
|
children: y("notifications.edit", "Edit")
|
|
289
293
|
}), /* @__PURE__ */ d("button", {
|
|
290
294
|
type: "button",
|
|
291
|
-
onClick: () =>
|
|
295
|
+
onClick: () => D(e.id),
|
|
292
296
|
className: "inline-flex items-center gap-2 rounded-md border border-status-error-border px-3 py-2 text-sm text-status-error-text hover:bg-status-error-bg-subtle",
|
|
293
297
|
children: [/* @__PURE__ */ u(l, { size: 14 }), y("notifications.delete", "Delete")]
|
|
294
298
|
})]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationTopicsPage.js","names":[],"sources":["../../src/pages/NotificationTopicsPage.tsx"],"sourcesContent":["import { useMemo, useState } from 'react';\nimport { Plus, Save, Search, Trash2 } from 'lucide-react';\nimport { usePermissions } from '@burdenoff/fe-libs/shared/providers/shell';\nimport {\n EmphasisPanel,\n GlassCard,\n IllustratedEmptyState,\n NextSteps,\n PagePurpose,\n} from '@burdenoff/fe-libs/ui';\nimport { useNotificationTopics } from '../hooks';\nimport { NOTIFICATION_PERMISSIONS } from '../constants/permissions';\nimport { useTr } from '../shared/hooks/useTr';\n\nconst topicTypeOptions = [\n { value: 'MARKETING', labelKey: 'notifications.topicType.marketing', label: 'Marketing' },\n {\n value: 'TRANSACTIONAL',\n labelKey: 'notifications.topicType.transactional',\n label: 'Transactional',\n },\n { value: 'SYSTEM', labelKey: 'notifications.topicType.system', label: 'System' },\n { value: 'ALERT', labelKey: 'notifications.topicType.alert', label: 'Alert' },\n];\n\nfunction slugify(value: string) {\n return value\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9\\s-]/g, '')\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function NotificationTopicsPage() {\n const tr = useTr();\n const { hasPermission, isLoading: permissionsLoading } = usePermissions();\n const { topics, isLoading, createTopic, updateTopic, deleteTopic } = useNotificationTopics();\n const [search, setSearch] = useState('');\n const [editingId, setEditingId] = useState<string | null>(null);\n const [form, setForm] = useState({\n name: '',\n slug: '',\n description: '',\n type: 'MARKETING',\n isActive: true,\n });\n\n // Topics live under the `notification` resource type in the backend (see\n // `global-notification-svc/src/modules/notification/schema/mutations.gql`),\n // and create/update/delete all require `notification:create` per the\n // @rbac directive. SUPER_ADMIN bypass is inherited from PermissionProvider.\n const canManage = hasPermission(NOTIFICATION_PERMISSIONS.NOTIFICATION_CREATE);\n\n const filteredTopics = useMemo(() => {\n if (!search.trim()) {\n return topics;\n }\n\n const query = search.toLowerCase();\n return topics.filter(\n (topic) =>\n topic.name.toLowerCase().includes(query) ||\n topic.slug.toLowerCase().includes(query) ||\n topic.description?.toLowerCase().includes(query)\n );\n }, [search, topics]);\n\n if (permissionsLoading) {\n return (\n <div className=\"flex h-64 items-center justify-center\">\n <div className=\"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent\" />\n </div>\n );\n }\n\n if (!canManage) {\n return (\n <div className=\"p-8 text-center text-text-secondary\">\n {tr(\n 'notifications.noPermissionTopics',\n \"You don't have permission to manage notification topics.\"\n )}\n </div>\n );\n }\n\n return (\n <div className=\"space-y-6 p-4 sm:p-6\">\n <div>\n <h1 className=\"text-2xl font-bold text-primary\">\n {tr('notifications.topicsTitle', 'Notification Topics')}\n </h1>\n <p className=\"mt-1 text-sm text-secondary\">\n {tr(\n 'notifications.topicsSubtitle',\n 'Create topics for campaigns so users can subscribe or unsubscribe with precision.'\n )}\n </p>\n </div>\n\n <PagePurpose icon={<Plus size={16} />}>\n {tr(\n 'notifications.topicsPurpose',\n 'Topics group related notifications (e.g. \"Product updates\", \"Billing reminders\", \"Weekly digest\") so people can opt in or out of exactly what they care about. Create a topic here, then target it when sending a campaign and let users manage their own subscriptions in Preferences.'\n )}\n </PagePurpose>\n\n <NextSteps\n storageKey=\"notification-topics\"\n steps={[\n {\n id: 'name-topic',\n label: tr('notifications.topicsNextNameLabel', 'Name your first topic'),\n description: tr(\n 'notifications.topicsNextNameDesc',\n 'Use the form to add a clear topic like \"Product updates\" — the slug is generated for you.'\n ),\n onClick: () => {\n setEditingId(null);\n setForm((prev) => ({ ...prev, name: '', slug: '', type: 'MARKETING' }));\n document\n .getElementById('notification-topic-name')\n ?.scrollIntoView({ behavior: 'smooth', block: 'center' });\n document.getElementById('notification-topic-name')?.focus();\n },\n },\n {\n id: 'set-type',\n label: tr('notifications.topicsNextTypeLabel', 'Pick the right type'),\n description: tr(\n 'notifications.topicsNextTypeDesc',\n 'Marketing topics are opt-in for users; Transactional, System and Alert reach everyone.'\n ),\n onClick: () =>\n document\n .getElementById('notification-topic-type')\n ?.scrollIntoView({ behavior: 'smooth', block: 'center' }),\n },\n {\n id: 'let-subscribe',\n label: tr('notifications.topicsNextSubscribeLabel', 'Let people subscribe'),\n description: tr(\n 'notifications.topicsNextSubscribeDesc',\n 'Once a topic is active, users manage their own opt-ins from the Preferences page.'\n ),\n href: '../preferences',\n },\n ]}\n />\n\n <div className=\"grid gap-6 xl:grid-cols-[380px,1fr]\">\n {/* Single emphasis zone — the create/edit form is the primary action on this page. */}\n <EmphasisPanel className=\"p-4\">\n <form\n className=\"space-y-4\"\n onSubmit={async (event) => {\n event.preventDefault();\n\n if (!form.name.trim() || !form.slug.trim()) {\n return;\n }\n\n if (editingId) {\n await updateTopic(editingId, form);\n } else {\n await createTopic(form);\n }\n\n setEditingId(null);\n setForm({\n name: '',\n slug: '',\n description: '',\n type: 'MARKETING',\n isActive: true,\n });\n }}\n >\n <div className=\"flex items-center gap-2\">\n <Plus size={18} className=\"text-accent-primary\" />\n <h2 className=\"text-base font-semibold text-primary\">\n {editingId\n ? tr('notifications.editTopic', 'Edit Topic')\n : tr('notifications.createTopic', 'Create Topic')}\n </h2>\n </div>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicName', 'Name')}</span>\n <input\n id=\"notification-topic-name\"\n type=\"text\"\n value={form.name}\n onChange={(event) =>\n setForm((prev) => ({\n ...prev,\n name: event.target.value,\n slug: editingId ? prev.slug : slugify(event.target.value),\n }))\n }\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </label>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicSlug', 'Slug')}</span>\n <input\n type=\"text\"\n value={form.slug}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, slug: slugify(event.target.value) }))\n }\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </label>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicType', 'Type')}</span>\n <select\n id=\"notification-topic-type\"\n value={form.type}\n onChange={(event) => setForm((prev) => ({ ...prev, type: event.target.value }))}\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent scheme-normal dark:scheme-dark [&_option]:bg-bg-surface [&_option]:text-text-primary\"\n >\n {topicTypeOptions.map((option) => (\n <option key={option.value} value={option.value}>\n {tr(option.labelKey, option.label)}\n </option>\n ))}\n </select>\n </label>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicDescription', 'Description')}</span>\n <textarea\n value={form.description}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, description: event.target.value }))\n }\n rows={4}\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </label>\n\n <label className=\"flex items-center gap-2 text-sm text-secondary\">\n <input\n type=\"checkbox\"\n checked={form.isActive}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, isActive: event.target.checked }))\n }\n />\n <span>{tr('notifications.topicIsActive', 'Active topic')}</span>\n </label>\n\n <div className=\"flex items-center gap-3\">\n <button\n type=\"submit\"\n className=\"inline-flex items-center gap-2 rounded-md bg-accent-primary px-4 py-2 text-sm font-medium text-white hover:opacity-90\"\n >\n <Save size={16} />\n {editingId\n ? tr('notifications.saveTopic', 'Save Topic')\n : tr('notifications.createTopicButton', 'Create Topic')}\n </button>\n\n {editingId && (\n <button\n type=\"button\"\n onClick={() => {\n setEditingId(null);\n setForm({\n name: '',\n slug: '',\n description: '',\n type: 'MARKETING',\n isActive: true,\n });\n }}\n className=\"rounded-md border border-default px-4 py-2 text-sm text-secondary hover:bg-bg-sunken\"\n >\n {tr('notifications.cancelTopicEdit', 'Cancel')}\n </button>\n )}\n </div>\n </form>\n </EmphasisPanel>\n\n <GlassCard treatment=\"plain\" className=\"space-y-4 border-border-seam p-4\">\n <div className=\"relative max-w-md\">\n <Search size={16} className=\"absolute left-3 top-1/2 -translate-y-1/2 text-tertiary\" />\n <input\n type=\"text\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n placeholder={tr('notifications.searchTopics', 'Search topics...')}\n className=\"w-full rounded-md border border-default bg-bg-canvas py-2 pl-9 pr-4 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </div>\n\n <div className=\"space-y-3\">\n {isLoading ? (\n <div className=\"text-sm text-secondary\">\n {tr('notifications.loadingTopics', 'Loading topics...')}\n </div>\n ) : filteredTopics.length === 0 ? (\n <IllustratedEmptyState\n illustration={search.trim() ? 'empty-search' : 'empty-data'}\n title={tr('notifications.noTopicsFound', 'No topics found.')}\n description={\n search.trim()\n ? tr('notifications.adjustSearchOrDateRange', 'Try adjusting your filters')\n : tr(\n 'notifications.noTopicsYet',\n 'No notification topics have been created yet.'\n )\n }\n />\n ) : (\n filteredTopics.map((topic) => (\n <div\n key={topic.id}\n className=\"flex flex-col gap-3 rounded-lg border border-border-seam bg-surface p-4 transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop)] sm:flex-row sm:items-start sm:justify-between\"\n >\n <div className=\"space-y-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h3 className=\"text-sm font-semibold text-primary\">{topic.name}</h3>\n <span className=\"rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary\">\n {topic.slug}\n </span>\n <span className=\"rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary\">\n {topic.type}\n </span>\n </div>\n {topic.description && (\n <p className=\"text-sm text-secondary\">{topic.description}</p>\n )}\n <p className=\"text-xs text-tertiary\">\n {tr('notifications.topicSubscribers', 'Subscribers')}: {topic.subscriberCount}\n </p>\n </div>\n\n <div className=\"flex items-center gap-2\">\n <button\n type=\"button\"\n onClick={() => {\n setEditingId(topic.id);\n setForm({\n name: topic.name,\n slug: topic.slug,\n description: topic.description || '',\n type: topic.type,\n isActive: topic.isActive,\n });\n }}\n className=\"rounded-md border border-default px-3 py-2 text-sm text-secondary hover:bg-bg-sunken\"\n >\n {tr('notifications.edit', 'Edit')}\n </button>\n <button\n type=\"button\"\n onClick={() => deleteTopic(topic.id)}\n className=\"inline-flex items-center gap-2 rounded-md border border-status-error-border px-3 py-2 text-sm text-status-error-text hover:bg-status-error-bg-subtle\"\n >\n <Trash2 size={14} />\n {tr('notifications.delete', 'Delete')}\n </button>\n </div>\n </div>\n ))\n )}\n </div>\n </GlassCard>\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAM,IAAmB;CACvB;EAAE,OAAO;EAAa,UAAU;EAAqC,OAAO;EAAa;CACzF;EACE,OAAO;EACP,UAAU;EACV,OAAO;EACR;CACD;EAAE,OAAO;EAAU,UAAU;EAAkC,OAAO;EAAU;CAChF;EAAE,OAAO;EAAS,UAAU;EAAiC,OAAO;EAAS;CAC9E;AAED,SAAS,EAAQ,GAAe;AAC9B,QAAO,EACJ,aAAa,CACb,MAAM,CACN,QAAQ,iBAAiB,GAAG,CAC5B,QAAQ,QAAQ,IAAI,CACpB,QAAQ,OAAO,IAAI;;AAGxB,SAAgB,IAAyB;CACvC,IAAM,IAAK,GAAO,EACZ,EAAE,kBAAe,WAAW,MAAuB,GAAgB,EACnE,EAAE,WAAQ,cAAW,gBAAa,gBAAa,mBAAgB,GAAuB,EACtF,CAAC,GAAQ,KAAa,EAAS,GAAG,EAClC,CAAC,GAAW,KAAgB,EAAwB,KAAK,EACzD,CAAC,GAAM,KAAW,EAAS;EAC/B,MAAM;EACN,MAAM;EACN,aAAa;EACb,MAAM;EACN,UAAU;EACX,CAAC,EAMI,IAAY,EAAc,EAAyB,oBAAoB,EAEvE,IAAiB,QAAc;AACnC,MAAI,CAAC,EAAO,MAAM,CAChB,QAAO;EAGT,IAAM,IAAQ,EAAO,aAAa;AAClC,SAAO,EAAO,QACX,MACC,EAAM,KAAK,aAAa,CAAC,SAAS,EAAM,IACxC,EAAM,KAAK,aAAa,CAAC,SAAS,EAAM,IACxC,EAAM,aA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CAAA,EACT,kBAAC,UAAD;SACE,MAAK;SACL,eAAe,EAAY,EAAM,GAAG;SACpC,WAAU;mBAHZ,CAKE,kBAAC,GAAD,EAAQ,MAAM,IAAM,CAAA,EACnB,EAAG,wBAAwB,SAAS,CAC9B;WACL;UACF;SA/CC,EAAM,GA+CP,CACN;MAEA,CAAA,CACI;OACR;;GACF;MAzSJ,kBAAC,OAAD;EAAK,WAAU;YACZ,EACC,oCACA,2DACD;EACG,CAAA"}
|
|
1
|
+
{"version":3,"file":"NotificationTopicsPage.js","names":[],"sources":["../../src/pages/NotificationTopicsPage.tsx"],"sourcesContent":["import { useMemo, useState } from 'react';\nimport { Plus, Save, Search, Trash2 } from 'lucide-react';\nimport { usePermissions } from '@burdenoff/fe-libs/shared/providers/shell';\nimport {\n EmphasisPanel,\n GlassCard,\n IllustratedEmptyState,\n NextSteps,\n PagePurpose,\n} from '@burdenoff/fe-libs/ui';\nimport { useNotificationTopics } from '../hooks';\nimport { NOTIFICATION_PERMISSIONS } from '../constants/permissions';\nimport { useTr } from '../shared/hooks/useTr';\n\nconst topicTypeOptions = [\n { value: 'MARKETING', labelKey: 'notifications.topicType.marketing', label: 'Marketing' },\n {\n value: 'TRANSACTIONAL',\n labelKey: 'notifications.topicType.transactional',\n label: 'Transactional',\n },\n { value: 'SYSTEM', labelKey: 'notifications.topicType.system', label: 'System' },\n { value: 'ALERT', labelKey: 'notifications.topicType.alert', label: 'Alert' },\n];\n\nfunction slugify(value: string) {\n return value\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9\\s-]/g, '')\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function NotificationTopicsPage() {\n const tr = useTr();\n const { hasPermission, isLoading: permissionsLoading } = usePermissions();\n const { topics, isLoading, isForbidden, createTopic, updateTopic, deleteTopic } =\n useNotificationTopics();\n const [search, setSearch] = useState('');\n const [editingId, setEditingId] = useState<string | null>(null);\n const [form, setForm] = useState({\n name: '',\n slug: '',\n description: '',\n type: 'MARKETING',\n isActive: true,\n });\n\n // Topics live under the `notification` resource type in the backend (see\n // `global-notification-svc/src/modules/notification/schema/mutations.gql`),\n // and create/update/delete all require `notification:create` per the\n // @rbac directive. SUPER_ADMIN bypass is inherited from PermissionProvider.\n const canManage = hasPermission(NOTIFICATION_PERMISSIONS.NOTIFICATION_CREATE);\n\n const filteredTopics = useMemo(() => {\n if (!search.trim()) {\n return topics;\n }\n\n const query = search.toLowerCase();\n return topics.filter(\n (topic) =>\n topic.name.toLowerCase().includes(query) ||\n topic.slug.toLowerCase().includes(query) ||\n topic.description?.toLowerCase().includes(query)\n );\n }, [search, topics]);\n\n if (permissionsLoading) {\n return (\n <div className=\"flex h-64 items-center justify-center\">\n <div className=\"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent\" />\n </div>\n );\n }\n\n if (!canManage) {\n return (\n <div className=\"p-8 text-center text-text-secondary\">\n {tr(\n 'notifications.noPermissionTopics',\n \"You don't have permission to manage notification topics.\"\n )}\n </div>\n );\n }\n\n return (\n <div className=\"space-y-6 p-4 sm:p-6\">\n <div>\n <h1 className=\"text-2xl font-bold text-primary\">\n {tr('notifications.topicsTitle', 'Notification Topics')}\n </h1>\n <p className=\"mt-1 text-sm text-secondary\">\n {tr(\n 'notifications.topicsSubtitle',\n 'Create topics for campaigns so users can subscribe or unsubscribe with precision.'\n )}\n </p>\n </div>\n\n <PagePurpose icon={<Plus size={16} />}>\n {tr(\n 'notifications.topicsPurpose',\n 'Topics group related notifications (e.g. \"Product updates\", \"Billing reminders\", \"Weekly digest\") so people can opt in or out of exactly what they care about. Create a topic here, then target it when sending a campaign and let users manage their own subscriptions in Preferences.'\n )}\n </PagePurpose>\n\n <NextSteps\n storageKey=\"notification-topics\"\n steps={[\n {\n id: 'name-topic',\n label: tr('notifications.topicsNextNameLabel', 'Name your first topic'),\n description: tr(\n 'notifications.topicsNextNameDesc',\n 'Use the form to add a clear topic like \"Product updates\" — the slug is generated for you.'\n ),\n onClick: () => {\n setEditingId(null);\n setForm((prev) => ({ ...prev, name: '', slug: '', type: 'MARKETING' }));\n document\n .getElementById('notification-topic-name')\n ?.scrollIntoView({ behavior: 'smooth', block: 'center' });\n document.getElementById('notification-topic-name')?.focus();\n },\n },\n {\n id: 'set-type',\n label: tr('notifications.topicsNextTypeLabel', 'Pick the right type'),\n description: tr(\n 'notifications.topicsNextTypeDesc',\n 'Marketing topics are opt-in for users; Transactional, System and Alert reach everyone.'\n ),\n onClick: () =>\n document\n .getElementById('notification-topic-type')\n ?.scrollIntoView({ behavior: 'smooth', block: 'center' }),\n },\n {\n id: 'let-subscribe',\n label: tr('notifications.topicsNextSubscribeLabel', 'Let people subscribe'),\n description: tr(\n 'notifications.topicsNextSubscribeDesc',\n 'Once a topic is active, users manage their own opt-ins from the Preferences page.'\n ),\n href: '../preferences',\n },\n ]}\n />\n\n <div className=\"grid gap-6 xl:grid-cols-[380px,1fr]\">\n {/* Single emphasis zone — the create/edit form is the primary action on this page. */}\n <EmphasisPanel className=\"p-4\">\n <form\n className=\"space-y-4\"\n onSubmit={async (event) => {\n event.preventDefault();\n\n if (!form.name.trim() || !form.slug.trim()) {\n return;\n }\n\n if (editingId) {\n await updateTopic(editingId, form);\n } else {\n await createTopic(form);\n }\n\n setEditingId(null);\n setForm({\n name: '',\n slug: '',\n description: '',\n type: 'MARKETING',\n isActive: true,\n });\n }}\n >\n <div className=\"flex items-center gap-2\">\n <Plus size={18} className=\"text-accent-primary\" />\n <h2 className=\"text-base font-semibold text-primary\">\n {editingId\n ? tr('notifications.editTopic', 'Edit Topic')\n : tr('notifications.createTopic', 'Create Topic')}\n </h2>\n </div>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicName', 'Name')}</span>\n <input\n id=\"notification-topic-name\"\n type=\"text\"\n value={form.name}\n onChange={(event) =>\n setForm((prev) => ({\n ...prev,\n name: event.target.value,\n slug: editingId ? prev.slug : slugify(event.target.value),\n }))\n }\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </label>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicSlug', 'Slug')}</span>\n <input\n type=\"text\"\n value={form.slug}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, slug: slugify(event.target.value) }))\n }\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </label>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicType', 'Type')}</span>\n <select\n id=\"notification-topic-type\"\n value={form.type}\n onChange={(event) => setForm((prev) => ({ ...prev, type: event.target.value }))}\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent scheme-normal dark:scheme-dark [&_option]:bg-bg-surface [&_option]:text-text-primary\"\n >\n {topicTypeOptions.map((option) => (\n <option key={option.value} value={option.value}>\n {tr(option.labelKey, option.label)}\n </option>\n ))}\n </select>\n </label>\n\n <label className=\"block space-y-1 text-sm text-secondary\">\n <span>{tr('notifications.topicDescription', 'Description')}</span>\n <textarea\n value={form.description}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, description: event.target.value }))\n }\n rows={4}\n className=\"w-full rounded-md border border-default bg-bg-canvas px-3 py-2 text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </label>\n\n <label className=\"flex items-center gap-2 text-sm text-secondary\">\n <input\n type=\"checkbox\"\n checked={form.isActive}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, isActive: event.target.checked }))\n }\n />\n <span>{tr('notifications.topicIsActive', 'Active topic')}</span>\n </label>\n\n <div className=\"flex items-center gap-3\">\n <button\n type=\"submit\"\n className=\"inline-flex items-center gap-2 rounded-md bg-accent-primary px-4 py-2 text-sm font-medium text-white hover:opacity-90\"\n >\n <Save size={16} />\n {editingId\n ? tr('notifications.saveTopic', 'Save Topic')\n : tr('notifications.createTopicButton', 'Create Topic')}\n </button>\n\n {editingId && (\n <button\n type=\"button\"\n onClick={() => {\n setEditingId(null);\n setForm({\n name: '',\n slug: '',\n description: '',\n type: 'MARKETING',\n isActive: true,\n });\n }}\n className=\"rounded-md border border-default px-4 py-2 text-sm text-secondary hover:bg-bg-sunken\"\n >\n {tr('notifications.cancelTopicEdit', 'Cancel')}\n </button>\n )}\n </div>\n </form>\n </EmphasisPanel>\n\n <GlassCard treatment=\"plain\" className=\"space-y-4 border-border-seam p-4\">\n <div className=\"relative max-w-md\">\n <Search size={16} className=\"absolute left-3 top-1/2 -translate-y-1/2 text-tertiary\" />\n <input\n type=\"text\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n placeholder={tr('notifications.searchTopics', 'Search topics...')}\n className=\"w-full rounded-md border border-default bg-bg-canvas py-2 pl-9 pr-4 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-accent\"\n />\n </div>\n\n <div className=\"space-y-3\">\n {isLoading ? (\n <div className=\"text-sm text-secondary\">\n {tr('notifications.loadingTopics', 'Loading topics...')}\n </div>\n ) : isForbidden ? (\n <IllustratedEmptyState\n illustration=\"empty-generic\"\n title={tr(\n 'notifications.topicsNoAccessTitle',\n \"You don't have access to notification topics\"\n )}\n description={tr(\n 'notifications.topicsNoAccessDescription',\n \"Your role doesn't include permission to read notification topics. Ask a workspace admin if you need access.\"\n )}\n />\n ) : filteredTopics.length === 0 ? (\n <IllustratedEmptyState\n illustration={search.trim() ? 'empty-search' : 'empty-data'}\n title={tr('notifications.noTopicsFound', 'No topics found.')}\n description={\n search.trim()\n ? tr('notifications.adjustSearchOrDateRange', 'Try adjusting your filters')\n : tr(\n 'notifications.noTopicsYet',\n 'No notification topics have been created yet.'\n )\n }\n />\n ) : (\n filteredTopics.map((topic) => (\n <div\n key={topic.id}\n className=\"flex flex-col gap-3 rounded-lg border border-border-seam bg-surface p-4 transition-[box-shadow,border-color] duration-200 hover:shadow-[var(--shadow-pop)] sm:flex-row sm:items-start sm:justify-between\"\n >\n <div className=\"space-y-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h3 className=\"text-sm font-semibold text-primary\">{topic.name}</h3>\n <span className=\"rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary\">\n {topic.slug}\n </span>\n <span className=\"rounded-full bg-bg-sunken px-2 py-0.5 text-xs text-secondary\">\n {topic.type}\n </span>\n </div>\n {topic.description && (\n <p className=\"text-sm text-secondary\">{topic.description}</p>\n )}\n <p className=\"text-xs text-tertiary\">\n {tr('notifications.topicSubscribers', 'Subscribers')}: {topic.subscriberCount}\n </p>\n </div>\n\n <div className=\"flex items-center gap-2\">\n <button\n type=\"button\"\n onClick={() => {\n setEditingId(topic.id);\n setForm({\n name: topic.name,\n slug: topic.slug,\n description: topic.description || '',\n type: topic.type,\n isActive: topic.isActive,\n });\n }}\n className=\"rounded-md border border-default px-3 py-2 text-sm text-secondary hover:bg-bg-sunken\"\n >\n {tr('notifications.edit', 'Edit')}\n </button>\n <button\n type=\"button\"\n onClick={() => deleteTopic(topic.id)}\n className=\"inline-flex items-center gap-2 rounded-md border border-status-error-border px-3 py-2 text-sm text-status-error-text hover:bg-status-error-bg-subtle\"\n >\n <Trash2 size={14} />\n {tr('notifications.delete', 'Delete')}\n </button>\n </div>\n </div>\n ))\n )}\n </div>\n </GlassCard>\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAM,IAAmB;CACvB;EAAE,OAAO;EAAa,UAAU;EAAqC,OAAO;EAAa;CACzF;EACE,OAAO;EACP,UAAU;EACV,OAAO;EACR;CACD;EAAE,OAAO;EAAU,UAAU;EAAkC,OAAO;EAAU;CAChF;EAAE,OAAO;EAAS,UAAU;EAAiC,OAAO;EAAS;CAC9E;AAED,SAAS,EAAQ,GAAe;AAC9B,QAAO,EACJ,aAAa,CACb,MAAM,CACN,QAAQ,iBAAiB,GAAG,CAC5B,QAAQ,QAAQ,IAAI,CACpB,QAAQ,OAAO,IAAI;;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;QAAK,WAAU;kBAAf;SACE,kBAAC,OAAD;UAAK,WAAU;oBAAf;WACE,kBAAC,MAAD;YAAI,WAAU;sBAAsC,EAAM;YAAU,CAAA;WACpE,kBAAC,QAAD;YAAM,WAAU;sBACb,EAAM;YACF,CAAA;WACP,kBAAC,QAAD;YAAM,WAAU;sBACb,EAAM;YACF,CAAA;WACH;;SACL,EAAM,eACL,kBAAC,KAAD;UAAG,WAAU;oBAA0B,EAAM;UAAgB,CAAA;SAE/D,kBAAC,KAAD;UAAG,WAAU;oBAAb;WACG,EAAG,kCAAkC,cAAc;WAAC;WAAG,EAAM;WAC5D;;SACA;WAEN,kBAAC,OAAD;QAAK,WAAU;kBAAf,CACE,kBAAC,UAAD;SACE,MAAK;SACL,eAAe;AAEb,UADA,EAAa,EAAM,GAAG,EACtB,EAAQ;WACN,MAAM,EAAM;WACZ,MAAM,EAAM;WACZ,aAAa,EAAM,eAAe;WAClC,MAAM,EAAM;WACZ,UAAU,EAAM;WACjB,CAAC;;SAEJ,WAAU;mBAET,EAAG,sBAAsB,OAAO;SAC1B,CAAA,EACT,kBAAC,UAAD;SACE,MAAK;SACL,eAAe,EAAY,EAAM,GAAG;SACpC,WAAU;mBAHZ,CAKE,kBAAC,GAAD,EAAQ,MAAM,IAAM,CAAA,EACnB,EAAG,wBAAwB,SAAS,CAC9B;WACL;UACF;SA/CC,EAAM,GA+CP,CACN;MAEA,CAAA,CACI;OACR;;GACF;MArTJ,kBAAC,OAAD;EAAK,WAAU;YACZ,EACC,oCACA,2DACD;EACG,CAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useNotificationAnalytics as e } from "../hooks/useNotificationAnalytics.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { isPermissionError as t } from "../utils/index.js";
|
|
3
|
+
import { useTr as n } from "../shared/hooks/useTr.js";
|
|
4
4
|
import { NOTIFICATION_PERMISSIONS as r } from "../constants/permissions.js";
|
|
5
5
|
import { useNotificationTemplate as i, useNotificationTemplates as ee } from "../hooks/useNotificationTemplates.js";
|
|
6
6
|
import { TemplatePreview as te } from "../components/TemplatePreview.js";
|
|
@@ -128,7 +128,7 @@ function xe(e) {
|
|
|
128
128
|
})) : [] : [];
|
|
129
129
|
}
|
|
130
130
|
function v() {
|
|
131
|
-
let v = de(), y =
|
|
131
|
+
let v = de(), y = n(), { locale: b } = ge(), { templateId: x } = fe(), S = !!x, { hasPermission: Se, isLoading: Ce, refreshPermissions: we } = ie(), { showToast: Te } = re(), { createTemplate: Ee, updateTemplate: De, isCreating: Oe, isUpdating: ke } = ee(), { trackTemplateSaved: C } = e(), { template: w, isLoading: Ae, error: T } = i(S ? x : void 0), [E, D] = c(""), [O, k] = c(""), [je, Me] = c(!1), [A, j] = c(""), [M, N] = c("TRANSACTIONAL"), [P, Ne] = c(""), [F, I] = c("en"), [L, R] = c(""), [z, B] = c(""), [V, H] = c(""), [U, W] = c([]), [G, K] = c("text"), Pe = ne(null), Fe = ne(null), [Ie, q] = c(null), [Le, J] = c(null), [Y, X] = c(!0), [Re, ze] = c("email");
|
|
132
132
|
o(() => {
|
|
133
133
|
w && (D(w.name), k(w.slug), Me(!0), j(w.description || ""), N(w.type), I(w.locale || "en"), R(w.subject || ""), B(w.bodyTemplate || ""), H(w.htmlTemplate || ""), W(xe(w.variables)), w.htmlTemplate && K("html"));
|
|
134
134
|
}, [w]), o(() => {
|
|
@@ -186,7 +186,7 @@ function v() {
|
|
|
186
186
|
q(y("notifTemplates.variablesNeedName", "All variables must have a name"));
|
|
187
187
|
return;
|
|
188
188
|
}
|
|
189
|
-
let
|
|
189
|
+
let n = U.map((e) => e.name.trim()), r = n.filter((e, t) => n.indexOf(e) !== t);
|
|
190
190
|
if (r.length > 0) {
|
|
191
191
|
q(`${y("notifTemplates.duplicateVariableName", "Duplicate variable name")}: ${r[0]}`);
|
|
192
192
|
return;
|
|
@@ -227,7 +227,7 @@ function v() {
|
|
|
227
227
|
hasHtml: !!V.trim()
|
|
228
228
|
}), J(y("notifTemplates.createSuccess", "Template created successfully")), setTimeout(() => v("..", { relative: "path" }), 1200);
|
|
229
229
|
} catch (e) {
|
|
230
|
-
if (
|
|
230
|
+
if (t(e)) {
|
|
231
231
|
Te(y("notifTemplates.permissionDeniedOnSave", "You don't have permission to save this template. Refreshing access…"), "warning"), we().catch((e) => console.warn("[permissions] refresh failed after template save denial:", e));
|
|
232
232
|
return;
|
|
233
233
|
}
|
package/dist/utils/index.js
CHANGED
|
@@ -106,15 +106,22 @@ function d(e) {
|
|
|
106
106
|
if (e === "FORBIDDEN" || n === "FORBIDDEN") return !0;
|
|
107
107
|
}
|
|
108
108
|
return !1;
|
|
109
|
-
}
|
|
110
|
-
if (
|
|
111
|
-
let
|
|
109
|
+
};
|
|
110
|
+
if (e.statusCode === 403) return !0;
|
|
111
|
+
let n = e.bodyText;
|
|
112
|
+
if (typeof n == "string" && n.length > 0) try {
|
|
113
|
+
let e = JSON.parse(n)?.errors;
|
|
114
|
+
if (Array.isArray(e) && t(e)) return !0;
|
|
115
|
+
} catch {}
|
|
116
|
+
let r = e.graphQLErrors;
|
|
112
117
|
if (Array.isArray(r) && t(r)) return !0;
|
|
113
|
-
let i = e.
|
|
114
|
-
if (
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
+
let i = e.errors;
|
|
119
|
+
if (Array.isArray(i) && t(i)) return !0;
|
|
120
|
+
let a = e.extensions, o = typeof a?.code == "string" ? a.code : "", s = typeof a?.errorCode == "string" ? a.errorCode : "";
|
|
121
|
+
if (o === "FORBIDDEN" || s === "FORBIDDEN") return !0;
|
|
122
|
+
if (a || Array.isArray(r) || Array.isArray(i)) return !1;
|
|
123
|
+
let c = e.message, l = typeof c == "string" ? c.toLowerCase() : "";
|
|
124
|
+
return l.includes("forbidden") || l.includes("permission denied");
|
|
118
125
|
}
|
|
119
126
|
//#endregion
|
|
120
127
|
export { a as filterNotifications, e as formatRelativeTime, i as getNotificationTypeIcon, r as getNotificationTypeLabel, t as getPriorityColor, n as getPriorityIcon, s as groupNotificationsByDate, d as isPermissionError, o as sortNotificationsByDate, u as substituteTemplateVariables, c as truncateText, l as validateTemplateVariables };
|
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["import type {\n Notification,\n NotificationFilter,\n NotificationPriority,\n NotificationType,\n} from '../types';\n\n/**\n * Format a relative time string (e.g., \"2 minutes ago\", \"1 hour ago\").\n * Pass an optional `tr` translator to localize the units.\n */\nexport function formatRelativeTime(\n date: string | Date,\n tr?: (key: string, fallback: string, params?: Record<string, string | number>) => string\n): string {\n const now = new Date();\n const past = new Date(date);\n const diffInMs = now.getTime() - past.getTime();\n const diffInSeconds = Math.floor(diffInMs / 1000);\n const diffInMinutes = Math.floor(diffInSeconds / 60);\n const diffInHours = Math.floor(diffInMinutes / 60);\n const diffInDays = Math.floor(diffInHours / 24);\n\n if (diffInSeconds < 60) {\n return tr ? tr('notifCommon.time.justNow', 'just now') : 'just now';\n } else if (diffInMinutes < 60) {\n if (diffInMinutes === 1) {\n return tr ? tr('notifCommon.time.minuteAgo', 'a minute ago') : 'a minute ago';\n }\n return tr\n ? tr('notifCommon.time.minutesAgo', '{{count}} minutes ago', { count: diffInMinutes })\n : `${diffInMinutes} minutes ago`;\n } else if (diffInHours < 24) {\n if (diffInHours === 1) {\n return tr ? tr('notifCommon.time.hourAgo', 'an hour ago') : 'an hour ago';\n }\n return tr\n ? tr('notifCommon.time.hoursAgo', '{{count}} hours ago', { count: diffInHours })\n : `${diffInHours} hours ago`;\n } else if (diffInDays < 7) {\n if (diffInDays === 1) {\n return tr ? tr('notifCommon.time.dayAgo', 'a day ago') : 'a day ago';\n }\n return tr\n ? tr('notifCommon.time.daysAgo', '{{count}} days ago', { count: diffInDays })\n : `${diffInDays} days ago`;\n } else {\n return past.toLocaleDateString();\n }\n}\n\n/**\n * Get priority color class name (for use with semantic tokens)\n */\nexport function getPriorityColor(priority: NotificationPriority): string {\n switch (priority) {\n case 'URGENT':\n return 'text-error-500';\n case 'HIGH':\n return 'text-warning-500';\n case 'NORMAL':\n return 'text-info-500';\n case 'LOW':\n return 'text-text-secondary';\n default:\n return 'text-text-secondary';\n }\n}\n\n/**\n * Get priority icon/indicator\n */\nexport function getPriorityIcon(priority: NotificationPriority): string {\n switch (priority) {\n case 'URGENT':\n return '🔴';\n case 'HIGH':\n return '🟠';\n case 'NORMAL':\n return '🟢';\n case 'LOW':\n return '⚪';\n default:\n return '⚪';\n }\n}\n\n/**\n * Get notification type label\n */\nexport function getNotificationTypeLabel(type: NotificationType): string {\n switch (type) {\n case 'TRANSACTIONAL':\n return 'Transactional';\n case 'MARKETING':\n return 'Marketing';\n case 'SYSTEM':\n return 'System';\n case 'ALERT':\n return 'Alert';\n default:\n return 'Unknown';\n }\n}\n\n/**\n * Get notification type icon\n */\nexport function getNotificationTypeIcon(type: NotificationType): string {\n switch (type) {\n case 'TRANSACTIONAL':\n return '📧';\n case 'MARKETING':\n return '📢';\n case 'SYSTEM':\n return '⚙️';\n case 'ALERT':\n return '🚨';\n default:\n return '🔔';\n }\n}\n\n/**\n * Filter notifications based on criteria\n */\nexport function filterNotifications(\n notifications: Notification[],\n filter: NotificationFilter\n): Notification[] {\n return notifications.filter((notification) => {\n // Search filter\n if (filter.search) {\n const searchLower = filter.search.toLowerCase();\n const titleMatch = notification.title.toLowerCase().includes(searchLower);\n const bodyMatch = notification.body.toLowerCase().includes(searchLower);\n if (!titleMatch && !bodyMatch) return false;\n }\n\n // Type filter\n if (filter.type !== 'ALL' && notification.type !== filter.type) {\n return false;\n }\n\n // Status filter\n if (filter.status !== 'ALL' && notification.status !== filter.status) {\n return false;\n }\n\n // Priority filter\n if (filter.priority !== 'ALL' && notification.priority !== filter.priority) {\n return false;\n }\n\n // Read/Unread filter\n if (filter.isRead !== null) {\n const isRead = !!notification.readAt;\n if (filter.isRead !== isRead) return false;\n }\n\n // Date range filter\n if (filter.dateRange.start || filter.dateRange.end) {\n const notificationDate = new Date(notification.createdAt);\n if (filter.dateRange.start && notificationDate < filter.dateRange.start) {\n return false;\n }\n if (filter.dateRange.end && notificationDate > filter.dateRange.end) {\n return false;\n }\n }\n\n return true;\n });\n}\n\n/**\n * Sort notifications by created date (newest first)\n */\nexport function sortNotificationsByDate(notifications: Notification[]): Notification[] {\n return [...notifications].sort((a, b) => {\n return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();\n });\n}\n\n/**\n * Group notifications by date (Today, Yesterday, This Week, etc.).\n * Pass an optional `tr` translator to localize the group labels.\n */\nexport function groupNotificationsByDate(\n notifications: Notification[],\n tr?: (key: string, fallback: string) => string\n): Record<string, Notification[]> {\n const now = new Date();\n const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n const yesterday = new Date(today);\n yesterday.setDate(yesterday.getDate() - 1);\n const thisWeekStart = new Date(today);\n thisWeekStart.setDate(thisWeekStart.getDate() - thisWeekStart.getDay());\n\n const labelToday = tr ? tr('notifCommon.dateGroup.today', 'Today') : 'Today';\n const labelYesterday = tr ? tr('notifCommon.dateGroup.yesterday', 'Yesterday') : 'Yesterday';\n const labelThisWeek = tr ? tr('notifCommon.dateGroup.thisWeek', 'This Week') : 'This Week';\n const labelEarlier = tr ? tr('notifCommon.dateGroup.earlier', 'Earlier') : 'Earlier';\n\n const groups: Record<string, Notification[]> = {\n [labelToday]: [],\n [labelYesterday]: [],\n [labelThisWeek]: [],\n [labelEarlier]: [],\n };\n\n notifications.forEach((notification) => {\n const notificationDate = new Date(notification.createdAt);\n const notificationDay = new Date(\n notificationDate.getFullYear(),\n notificationDate.getMonth(),\n notificationDate.getDate()\n );\n\n if (notificationDay.getTime() === today.getTime()) {\n groups[labelToday].push(notification);\n } else if (notificationDay.getTime() === yesterday.getTime()) {\n groups[labelYesterday].push(notification);\n } else if (notificationDay >= thisWeekStart) {\n groups[labelThisWeek].push(notification);\n } else {\n groups[labelEarlier].push(notification);\n }\n });\n\n // Remove empty groups\n Object.keys(groups).forEach((key) => {\n if (groups[key].length === 0) {\n delete groups[key];\n }\n });\n\n return groups;\n}\n\n/**\n * Truncate text to a maximum length\n */\nexport function truncateText(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text;\n return text.slice(0, maxLength) + '...';\n}\n\n/**\n * Validate template variable substitution\n */\nexport function validateTemplateVariables(\n template: string,\n variables: Record<string, unknown>\n): { isValid: boolean; missingVariables: string[] } {\n const variableRegex = /\\{\\{([^}]+)\\}\\}/g;\n const matches = template.matchAll(variableRegex);\n const missingVariables: string[] = [];\n\n for (const match of matches) {\n const variableName = match[1].trim();\n if (!(variableName in variables)) {\n missingVariables.push(variableName);\n }\n }\n\n return {\n isValid: missingVariables.length === 0,\n missingVariables,\n };\n}\n\n/**\n * Substitute template variables\n */\nexport function substituteTemplateVariables(\n template: string,\n variables: Record<string, unknown>\n): string {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, variableName) => {\n const trimmedName = variableName.trim();\n const value = variables[trimmedName];\n return value !== undefined ? String(value) : match;\n });\n}\n\n/**\n * Get delivery status color\n */\nexport function getDeliveryStatusColor(\n status: 'PENDING' | 'SENT' | 'DELIVERED' | 'FAILED' | 'ARCHIVED'\n): string {\n switch (status) {\n case 'DELIVERED':\n return 'text-success-500';\n case 'SENT':\n return 'text-info-500';\n case 'PENDING':\n return 'text-warning-500';\n case 'FAILED':\n return 'text-error-500';\n case 'ARCHIVED':\n return 'text-text-secondary';\n default:\n return 'text-text-secondary';\n }\n}\n\n/**\n * Calculate delivery rate percentage\n */\nexport function calculateDeliveryRate(delivered: number, total: number): number {\n if (total === 0) return 0;\n return Math.round((delivered / total) * 100);\n}\n\n/**\n * Check whether a mutation error represents a gateway-level authorization\n * failure (the RBAC gateway rejected the request because the actor lacks\n * the required permission). Callers surface these with a friendly toast and\n * refresh the permission cache to recover from stale client state.\n *\n * 401/UNAUTHENTICATED is handled separately by the shell's auth flow — this\n * helper intentionally ignores it.\n */\nexport function isPermissionError(err: unknown): boolean {\n if (!err) return false;\n\n type GqlErrorLike = { extensions?: Record<string, unknown> };\n\n const hasForbiddenCode = (errors: readonly GqlErrorLike[]): boolean => {\n for (const gqlErr of errors) {\n const code = typeof gqlErr.extensions?.code === 'string' ? gqlErr.extensions.code : '';\n const errorCode =\n typeof gqlErr.extensions?.errorCode === 'string' ? gqlErr.extensions.errorCode : '';\n if (code === 'FORBIDDEN' || errorCode === 'FORBIDDEN') return true;\n }\n return false;\n };\n\n // Apollo v3 shape: `err.graphQLErrors[]`. Apollo v4 (what `global-client.ts` targets): `err.errors[]`.\n // Check both so the structured signal works regardless of which Apollo major we're on.\n const v3 = (err as { graphQLErrors?: GqlErrorLike[] }).graphQLErrors;\n if (Array.isArray(v3) && hasForbiddenCode(v3)) return true;\n const v4 = (err as { errors?: GqlErrorLike[] }).errors;\n if (Array.isArray(v4) && hasForbiddenCode(v4)) return true;\n\n // Non-Apollo shapes (fetch-wrapped errors, custom throws) may hang extensions off the error itself.\n const extensionsLike = (err as { extensions?: Record<string, unknown> }).extensions;\n const codeFromExtensions = typeof extensionsLike?.code === 'string' ? extensionsLike.code : '';\n const errorCodeFromExtensions =\n typeof extensionsLike?.errorCode === 'string' ? extensionsLike.errorCode : '';\n if (codeFromExtensions === 'FORBIDDEN' || errorCodeFromExtensions === 'FORBIDDEN') return true;\n\n // Last-resort message substring match. Gated on the absence of any structured error payload so\n // a notification title / template body containing \"forbidden\" doesn't trigger a false positive.\n if (extensionsLike || Array.isArray(v3) || Array.isArray(v4)) return false;\n const messageFromError = (err as { message?: unknown }).message;\n const message = typeof messageFromError === 'string' ? messageFromError.toLowerCase() : '';\n return message.includes('forbidden') || message.includes('permission denied');\n}\n"],"mappings":";AAWA,SAAgB,EACd,GACA,GACQ;CACR,IAAM,oBAAM,IAAI,MAAM,EAChB,IAAO,IAAI,KAAK,EAAK,EACrB,IAAW,EAAI,SAAS,GAAG,EAAK,SAAS,EACzC,IAAgB,KAAK,MAAM,I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Aa,MAAM;AAEvC,SAAO,MAAU,KAAA,IAA4B,IAAhB,OAAO,EAAM;GAC1C;;AA0CJ,SAAgB,EAAkB,GAAuB;AACvD,KAAI,CAAC,EAAK,QAAO;CAIjB,IAAM,KAAoB,MAA6C;AACrE,OAAK,IAAM,KAAU,GAAQ;GAC3B,IAAM,IAAO,OAAO,EAAO,YAAY,QAAS,WAAW,EAAO,WAAW,OAAO,IAC9E,IACJ,OAAO,EAAO,YAAY,aAAc,WAAW,EAAO,WAAW,YAAY;AACnF,OAAI,MAAS,eAAe,MAAc,YAAa,QAAO;;AAEhE,SAAO;IAKH,IAAM,EAA2C;AACvD,KAAI,MAAM,QAAQ,EAAG,IAAI,EAAiB,EAAG,CAAE,QAAO;CACtD,IAAM,IAAM,EAAoC;AAChD,KAAI,MAAM,QAAQ,EAAG,IAAI,EAAiB,EAAG,CAAE,QAAO;CAGtD,IAAM,IAAkB,EAAiD,YACnE,IAAqB,OAAO,GAAgB,QAAS,WAAW,EAAe,OAAO,IACtF,IACJ,OAAO,GAAgB,aAAc,WAAW,EAAe,YAAY;AAC7E,KAAI,MAAuB,eAAe,MAA4B,YAAa,QAAO;AAI1F,KAAI,KAAkB,MAAM,QAAQ,EAAG,IAAI,MAAM,QAAQ,EAAG,CAAE,QAAO;CACrE,IAAM,IAAoB,EAA8B,SAClD,IAAU,OAAO,KAAqB,WAAW,EAAiB,aAAa,GAAG;AACxF,QAAO,EAAQ,SAAS,YAAY,IAAI,EAAQ,SAAS,oBAAoB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["import type {\n Notification,\n NotificationFilter,\n NotificationPriority,\n NotificationType,\n} from '../types';\n\n/**\n * Format a relative time string (e.g., \"2 minutes ago\", \"1 hour ago\").\n * Pass an optional `tr` translator to localize the units.\n */\nexport function formatRelativeTime(\n date: string | Date,\n tr?: (key: string, fallback: string, params?: Record<string, string | number>) => string\n): string {\n const now = new Date();\n const past = new Date(date);\n const diffInMs = now.getTime() - past.getTime();\n const diffInSeconds = Math.floor(diffInMs / 1000);\n const diffInMinutes = Math.floor(diffInSeconds / 60);\n const diffInHours = Math.floor(diffInMinutes / 60);\n const diffInDays = Math.floor(diffInHours / 24);\n\n if (diffInSeconds < 60) {\n return tr ? tr('notifCommon.time.justNow', 'just now') : 'just now';\n } else if (diffInMinutes < 60) {\n if (diffInMinutes === 1) {\n return tr ? tr('notifCommon.time.minuteAgo', 'a minute ago') : 'a minute ago';\n }\n return tr\n ? tr('notifCommon.time.minutesAgo', '{{count}} minutes ago', { count: diffInMinutes })\n : `${diffInMinutes} minutes ago`;\n } else if (diffInHours < 24) {\n if (diffInHours === 1) {\n return tr ? tr('notifCommon.time.hourAgo', 'an hour ago') : 'an hour ago';\n }\n return tr\n ? tr('notifCommon.time.hoursAgo', '{{count}} hours ago', { count: diffInHours })\n : `${diffInHours} hours ago`;\n } else if (diffInDays < 7) {\n if (diffInDays === 1) {\n return tr ? tr('notifCommon.time.dayAgo', 'a day ago') : 'a day ago';\n }\n return tr\n ? tr('notifCommon.time.daysAgo', '{{count}} days ago', { count: diffInDays })\n : `${diffInDays} days ago`;\n } else {\n return past.toLocaleDateString();\n }\n}\n\n/**\n * Get priority color class name (for use with semantic tokens)\n */\nexport function getPriorityColor(priority: NotificationPriority): string {\n switch (priority) {\n case 'URGENT':\n return 'text-error-500';\n case 'HIGH':\n return 'text-warning-500';\n case 'NORMAL':\n return 'text-info-500';\n case 'LOW':\n return 'text-text-secondary';\n default:\n return 'text-text-secondary';\n }\n}\n\n/**\n * Get priority icon/indicator\n */\nexport function getPriorityIcon(priority: NotificationPriority): string {\n switch (priority) {\n case 'URGENT':\n return '🔴';\n case 'HIGH':\n return '🟠';\n case 'NORMAL':\n return '🟢';\n case 'LOW':\n return '⚪';\n default:\n return '⚪';\n }\n}\n\n/**\n * Get notification type label\n */\nexport function getNotificationTypeLabel(type: NotificationType): string {\n switch (type) {\n case 'TRANSACTIONAL':\n return 'Transactional';\n case 'MARKETING':\n return 'Marketing';\n case 'SYSTEM':\n return 'System';\n case 'ALERT':\n return 'Alert';\n default:\n return 'Unknown';\n }\n}\n\n/**\n * Get notification type icon\n */\nexport function getNotificationTypeIcon(type: NotificationType): string {\n switch (type) {\n case 'TRANSACTIONAL':\n return '📧';\n case 'MARKETING':\n return '📢';\n case 'SYSTEM':\n return '⚙️';\n case 'ALERT':\n return '🚨';\n default:\n return '🔔';\n }\n}\n\n/**\n * Filter notifications based on criteria\n */\nexport function filterNotifications(\n notifications: Notification[],\n filter: NotificationFilter\n): Notification[] {\n return notifications.filter((notification) => {\n // Search filter\n if (filter.search) {\n const searchLower = filter.search.toLowerCase();\n const titleMatch = notification.title.toLowerCase().includes(searchLower);\n const bodyMatch = notification.body.toLowerCase().includes(searchLower);\n if (!titleMatch && !bodyMatch) return false;\n }\n\n // Type filter\n if (filter.type !== 'ALL' && notification.type !== filter.type) {\n return false;\n }\n\n // Status filter\n if (filter.status !== 'ALL' && notification.status !== filter.status) {\n return false;\n }\n\n // Priority filter\n if (filter.priority !== 'ALL' && notification.priority !== filter.priority) {\n return false;\n }\n\n // Read/Unread filter\n if (filter.isRead !== null) {\n const isRead = !!notification.readAt;\n if (filter.isRead !== isRead) return false;\n }\n\n // Date range filter\n if (filter.dateRange.start || filter.dateRange.end) {\n const notificationDate = new Date(notification.createdAt);\n if (filter.dateRange.start && notificationDate < filter.dateRange.start) {\n return false;\n }\n if (filter.dateRange.end && notificationDate > filter.dateRange.end) {\n return false;\n }\n }\n\n return true;\n });\n}\n\n/**\n * Sort notifications by created date (newest first)\n */\nexport function sortNotificationsByDate(notifications: Notification[]): Notification[] {\n return [...notifications].sort((a, b) => {\n return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();\n });\n}\n\n/**\n * Group notifications by date (Today, Yesterday, This Week, etc.).\n * Pass an optional `tr` translator to localize the group labels.\n */\nexport function groupNotificationsByDate(\n notifications: Notification[],\n tr?: (key: string, fallback: string) => string\n): Record<string, Notification[]> {\n const now = new Date();\n const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n const yesterday = new Date(today);\n yesterday.setDate(yesterday.getDate() - 1);\n const thisWeekStart = new Date(today);\n thisWeekStart.setDate(thisWeekStart.getDate() - thisWeekStart.getDay());\n\n const labelToday = tr ? tr('notifCommon.dateGroup.today', 'Today') : 'Today';\n const labelYesterday = tr ? tr('notifCommon.dateGroup.yesterday', 'Yesterday') : 'Yesterday';\n const labelThisWeek = tr ? tr('notifCommon.dateGroup.thisWeek', 'This Week') : 'This Week';\n const labelEarlier = tr ? tr('notifCommon.dateGroup.earlier', 'Earlier') : 'Earlier';\n\n const groups: Record<string, Notification[]> = {\n [labelToday]: [],\n [labelYesterday]: [],\n [labelThisWeek]: [],\n [labelEarlier]: [],\n };\n\n notifications.forEach((notification) => {\n const notificationDate = new Date(notification.createdAt);\n const notificationDay = new Date(\n notificationDate.getFullYear(),\n notificationDate.getMonth(),\n notificationDate.getDate()\n );\n\n if (notificationDay.getTime() === today.getTime()) {\n groups[labelToday].push(notification);\n } else if (notificationDay.getTime() === yesterday.getTime()) {\n groups[labelYesterday].push(notification);\n } else if (notificationDay >= thisWeekStart) {\n groups[labelThisWeek].push(notification);\n } else {\n groups[labelEarlier].push(notification);\n }\n });\n\n // Remove empty groups\n Object.keys(groups).forEach((key) => {\n if (groups[key].length === 0) {\n delete groups[key];\n }\n });\n\n return groups;\n}\n\n/**\n * Truncate text to a maximum length\n */\nexport function truncateText(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text;\n return text.slice(0, maxLength) + '...';\n}\n\n/**\n * Validate template variable substitution\n */\nexport function validateTemplateVariables(\n template: string,\n variables: Record<string, unknown>\n): { isValid: boolean; missingVariables: string[] } {\n const variableRegex = /\\{\\{([^}]+)\\}\\}/g;\n const matches = template.matchAll(variableRegex);\n const missingVariables: string[] = [];\n\n for (const match of matches) {\n const variableName = match[1].trim();\n if (!(variableName in variables)) {\n missingVariables.push(variableName);\n }\n }\n\n return {\n isValid: missingVariables.length === 0,\n missingVariables,\n };\n}\n\n/**\n * Substitute template variables\n */\nexport function substituteTemplateVariables(\n template: string,\n variables: Record<string, unknown>\n): string {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, variableName) => {\n const trimmedName = variableName.trim();\n const value = variables[trimmedName];\n return value !== undefined ? String(value) : match;\n });\n}\n\n/**\n * Get delivery status color\n */\nexport function getDeliveryStatusColor(\n status: 'PENDING' | 'SENT' | 'DELIVERED' | 'FAILED' | 'ARCHIVED'\n): string {\n switch (status) {\n case 'DELIVERED':\n return 'text-success-500';\n case 'SENT':\n return 'text-info-500';\n case 'PENDING':\n return 'text-warning-500';\n case 'FAILED':\n return 'text-error-500';\n case 'ARCHIVED':\n return 'text-text-secondary';\n default:\n return 'text-text-secondary';\n }\n}\n\n/**\n * Calculate delivery rate percentage\n */\nexport function calculateDeliveryRate(delivered: number, total: number): number {\n if (total === 0) return 0;\n return Math.round((delivered / total) * 100);\n}\n\n/**\n * Check whether a mutation error represents a gateway-level authorization\n * failure (the RBAC gateway rejected the request because the actor lacks\n * the required permission). Callers surface these with a friendly toast and\n * refresh the permission cache to recover from stale client state.\n *\n * 401/UNAUTHENTICATED is handled separately by the shell's auth flow — this\n * helper intentionally ignores it.\n */\nexport function isPermissionError(err: unknown): boolean {\n if (!err) return false;\n\n type GqlErrorLike = { extensions?: Record<string, unknown> };\n\n const hasForbiddenCode = (errors: readonly GqlErrorLike[]): boolean => {\n for (const gqlErr of errors) {\n const code = typeof gqlErr.extensions?.code === 'string' ? gqlErr.extensions.code : '';\n const errorCode =\n typeof gqlErr.extensions?.errorCode === 'string' ? gqlErr.extensions.errorCode : '';\n if (code === 'FORBIDDEN' || errorCode === 'FORBIDDEN') return true;\n }\n return false;\n };\n\n // The gateway answers an @rbac denial with HTTP 403, which Apollo v4 raises\n // as a ServerError: a `statusCode` plus the GraphQL body in `bodyText`.\n const statusCode = (err as { statusCode?: unknown }).statusCode;\n if (statusCode === 403) return true;\n const bodyText = (err as { bodyText?: unknown }).bodyText;\n if (typeof bodyText === 'string' && bodyText.length > 0) {\n try {\n const parsed: unknown = JSON.parse(bodyText);\n const bodyErrors = (parsed as { errors?: unknown } | null)?.errors;\n if (Array.isArray(bodyErrors) && hasForbiddenCode(bodyErrors as GqlErrorLike[])) return true;\n } catch {\n // Not JSON; fall through to the other shapes.\n }\n }\n\n // Apollo v3 shape: `err.graphQLErrors[]`. Apollo v4 (what `global-client.ts` targets): `err.errors[]`.\n // Check both so the structured signal works regardless of which Apollo major we're on.\n const v3 = (err as { graphQLErrors?: GqlErrorLike[] }).graphQLErrors;\n if (Array.isArray(v3) && hasForbiddenCode(v3)) return true;\n const v4 = (err as { errors?: GqlErrorLike[] }).errors;\n if (Array.isArray(v4) && hasForbiddenCode(v4)) return true;\n\n // Non-Apollo shapes (fetch-wrapped errors, custom throws) may hang extensions off the error itself.\n const extensionsLike = (err as { extensions?: Record<string, unknown> }).extensions;\n const codeFromExtensions = typeof extensionsLike?.code === 'string' ? extensionsLike.code : '';\n const errorCodeFromExtensions =\n typeof extensionsLike?.errorCode === 'string' ? extensionsLike.errorCode : '';\n if (codeFromExtensions === 'FORBIDDEN' || errorCodeFromExtensions === 'FORBIDDEN') return true;\n\n // Last-resort message substring match. Gated on the absence of any structured error payload so\n // a notification title / template body containing \"forbidden\" doesn't trigger a false positive.\n if (extensionsLike || Array.isArray(v3) || Array.isArray(v4)) return false;\n const messageFromError = (err as { message?: unknown }).message;\n const message = typeof messageFromError === 'string' ? messageFromError.toLowerCase() : '';\n return message.includes('forbidden') || message.includes('permission denied');\n}\n"],"mappings":";AAWA,SAAgB,EACd,GACA,GACQ;CACR,IAAM,oBAAM,IAAI,MAAM,EAChB,IAAO,IAAI,KAAK,EAAK,EACrB,IAAW,EAAI,SAAS,GAAG,EAAK,SAAS,EACzC,IAAgB,KAAK,MAAM,IAAW,IAAK,EAC3C,IAAgB,KAAK,MAAM,IAAgB,GAAG,EAC9C,IAAc,KAAK,MAAM,IAAgB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