@burdenoff/microfe-notification 2026.1130.2 → 2026.1202.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/answeredAt.d.ts +8 -0
- package/dist/hooks/answeredAt.js +33 -0
- package/dist/hooks/answeredAt.js.map +1 -0
- package/dist/hooks/useNotificationAdmin.d.ts +2 -0
- package/dist/hooks/useNotificationAdmin.js +32 -31
- package/dist/hooks/useNotificationAdmin.js.map +1 -1
- package/dist/hooks/useNotificationPreferences.d.ts +2 -0
- package/dist/hooks/useNotificationPreferences.js +45 -43
- package/dist/hooks/useNotificationPreferences.js.map +1 -1
- package/dist/hooks/useNotificationTemplates.d.ts +2 -0
- package/dist/hooks/useNotificationTemplates.js +92 -88
- package/dist/hooks/useNotificationTemplates.js.map +1 -1
- package/dist/hooks/useNotificationTopics.d.ts +2 -0
- package/dist/hooks/useNotificationTopics.js +19 -18
- package/dist/hooks/useNotificationTopics.js.map +1 -1
- package/dist/hooks/useNotifications.d.ts +2 -0
- package/dist/hooks/useNotifications.js +69 -68
- package/dist/hooks/useNotifications.js.map +1 -1
- package/dist/hooks/usePreferenceToggles.d.ts +2 -0
- package/dist/hooks/usePreferenceToggles.js +19 -18
- package/dist/hooks/usePreferenceToggles.js.map +1 -1
- package/dist/v2/InboxPage.js +100 -98
- package/dist/v2/InboxPage.js.map +1 -1
- package/dist/v2/PreferencesPage.js +98 -92
- package/dist/v2/PreferencesPage.js.map +1 -1
- package/dist/v2/StaleHint.d.ts +4 -0
- package/dist/v2/StaleHint.js +18 -0
- package/dist/v2/StaleHint.js.map +1 -0
- package/dist/v2/admin/DeliveryLogPage.js +71 -69
- package/dist/v2/admin/DeliveryLogPage.js.map +1 -1
- package/dist/v2/admin/TemplatesPage.js +135 -130
- package/dist/v2/admin/TemplatesPage.js.map +1 -1
- package/dist/v2/admin/TopicsPage.js +51 -49
- package/dist/v2/admin/TopicsPage.js.map +1 -1
- package/dist/v2/model/loadedAt.d.ts +5 -0
- package/dist/v2/model/loadedAt.js +8 -0
- package/dist/v2/model/loadedAt.js.map +1 -0
- package/package.json +3 -3
|
@@ -1,146 +1,150 @@
|
|
|
1
1
|
import { useNotification as e } from "../providers/NotificationProvider.js";
|
|
2
2
|
import { getGlobalNotificationClient as t } from "../graphql/global-client.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { answeredAt as n, inCache as r } from "./answeredAt.js";
|
|
4
|
+
import { CreateNotificationTemplateDocument as i, DeleteNotificationTemplateDocument as a, GetNotificationTemplateDocument as o, GetNotificationTemplatesDocument as s, UpdateNotificationTemplateDocument as c } from "../generated/global-operations.js";
|
|
5
|
+
import { useCallback as l, useEffect as u, useState as d } from "react";
|
|
5
6
|
// src/hooks/useNotificationTemplates.ts
|
|
6
|
-
function
|
|
7
|
-
let { authToken:
|
|
7
|
+
function f(o) {
|
|
8
|
+
let { authToken: f, apiGatewayUrl: p } = e(), [m, h] = d([]), [g, _] = d(!1), [v, y] = d(!1), [b, x] = d(!1), [S, C] = d(!1), [w, T] = d(null), [E, D] = d(!1), [O, k] = d(0), [A, j] = d(0), [M, N] = d(o || {}), [P, F] = d(0), I = l(() => t(p ?? void 0, f ?? void 0), [p, f]), L = l(() => {
|
|
8
9
|
let e = {};
|
|
9
|
-
return
|
|
10
|
-
}, [
|
|
11
|
-
|
|
10
|
+
return M.type && (e.type = M.type), M.locale && (e.locale = M.locale), M.enabled !== void 0 && (e.enabled = M.enabled), Object.keys(e).length > 0 ? e : void 0;
|
|
11
|
+
}, [M]), R = l(async () => {
|
|
12
|
+
_(!0), T(null);
|
|
12
13
|
try {
|
|
13
|
-
let e =
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
let e = I(), t = s, i = {
|
|
15
|
+
filter: L(),
|
|
16
|
+
limit: 50,
|
|
17
|
+
offset: 0
|
|
18
|
+
}, a = r(e, t, i), o = await e.query({
|
|
19
|
+
query: t,
|
|
20
|
+
variables: i,
|
|
20
21
|
fetchPolicy: "cache-first"
|
|
21
22
|
});
|
|
22
|
-
|
|
23
|
+
o.data?.notificationTemplates && (h(o.data.notificationTemplates.items || []), k(o.data.notificationTemplates.total || 0), D(o.data.notificationTemplates.hasMore || !1), j(50), F(n(e, t, i, a)));
|
|
23
24
|
} catch (e) {
|
|
24
25
|
let t = e instanceof Error ? e.message : "Failed to fetch templates";
|
|
25
|
-
console.error("[useNotificationTemplates] Failed to fetch templates:", e),
|
|
26
|
+
console.error("[useNotificationTemplates] Failed to fetch templates:", e), T(t);
|
|
26
27
|
} finally {
|
|
27
|
-
|
|
28
|
+
_(!1);
|
|
28
29
|
}
|
|
29
|
-
}, [
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}, [
|
|
33
|
-
let
|
|
34
|
-
|
|
30
|
+
}, [I, L]);
|
|
31
|
+
u(() => {
|
|
32
|
+
R();
|
|
33
|
+
}, [R]);
|
|
34
|
+
let z = M.search ? m.filter((e) => e.name.toLowerCase().includes(M.search.toLowerCase()) || e.slug.toLowerCase().includes(M.search.toLowerCase()) || e.description?.toLowerCase().includes(M.search.toLowerCase())) : m, B = l(async (e) => {
|
|
35
|
+
y(!0), T(null);
|
|
35
36
|
try {
|
|
36
|
-
let t = await
|
|
37
|
-
mutation:
|
|
37
|
+
let t = await I().mutate({
|
|
38
|
+
mutation: i,
|
|
38
39
|
variables: { input: e }
|
|
39
40
|
});
|
|
40
|
-
return await
|
|
41
|
+
return await R(), t.data.createNotificationTemplate;
|
|
41
42
|
} catch (e) {
|
|
42
43
|
let t = e instanceof Error ? e.message : "Failed to create template";
|
|
43
|
-
throw console.error("Failed to create template:", e),
|
|
44
|
+
throw console.error("Failed to create template:", e), T(t), e;
|
|
44
45
|
} finally {
|
|
45
|
-
|
|
46
|
+
y(!1);
|
|
46
47
|
}
|
|
47
|
-
}, [
|
|
48
|
-
|
|
48
|
+
}, [I, R]), V = l(async (e, t) => {
|
|
49
|
+
x(!0), T(null);
|
|
49
50
|
try {
|
|
50
|
-
let n = await
|
|
51
|
-
mutation:
|
|
51
|
+
let n = await I().mutate({
|
|
52
|
+
mutation: c,
|
|
52
53
|
variables: {
|
|
53
54
|
id: e,
|
|
54
55
|
input: t
|
|
55
56
|
}
|
|
56
57
|
});
|
|
57
|
-
return await
|
|
58
|
+
return await R(), n.data.updateNotificationTemplate;
|
|
58
59
|
} catch (e) {
|
|
59
60
|
let t = e instanceof Error ? e.message : "Failed to update template";
|
|
60
|
-
throw console.error("Failed to update template:", e),
|
|
61
|
+
throw console.error("Failed to update template:", e), T(t), e;
|
|
61
62
|
} finally {
|
|
62
|
-
|
|
63
|
+
x(!1);
|
|
63
64
|
}
|
|
64
|
-
}, [
|
|
65
|
-
|
|
65
|
+
}, [I, R]), H = l(async (e) => {
|
|
66
|
+
C(!0), T(null);
|
|
66
67
|
try {
|
|
67
|
-
return await
|
|
68
|
-
mutation:
|
|
68
|
+
return await I().mutate({
|
|
69
|
+
mutation: a,
|
|
69
70
|
variables: { id: e }
|
|
70
|
-
}), await
|
|
71
|
+
}), await R(), !0;
|
|
71
72
|
} catch (e) {
|
|
72
73
|
let t = e instanceof Error ? e.message : "Failed to delete template";
|
|
73
|
-
throw console.error("Failed to delete template:", e),
|
|
74
|
+
throw console.error("Failed to delete template:", e), T(t), e;
|
|
74
75
|
} finally {
|
|
75
|
-
|
|
76
|
+
C(!1);
|
|
76
77
|
}
|
|
77
|
-
}, [
|
|
78
|
-
if (
|
|
79
|
-
let e =
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
78
|
+
}, [I, R]), U = l(async () => {
|
|
79
|
+
if (E) try {
|
|
80
|
+
let e = I(), t = s, i = {
|
|
81
|
+
filter: L(),
|
|
82
|
+
limit: 50,
|
|
83
|
+
offset: A
|
|
84
|
+
}, a = r(e, t, i), o = await e.query({
|
|
85
|
+
query: t,
|
|
86
|
+
variables: i,
|
|
86
87
|
fetchPolicy: "cache-first"
|
|
87
88
|
});
|
|
88
|
-
if (
|
|
89
|
-
let
|
|
90
|
-
|
|
89
|
+
if (o.data?.notificationTemplates) {
|
|
90
|
+
let r = o.data.notificationTemplates.items || [];
|
|
91
|
+
h((e) => [...e, ...r]), D(o.data.notificationTemplates.hasMore || !1), j((e) => e + 50);
|
|
92
|
+
let s = n(e, t, i, a);
|
|
93
|
+
F((e) => Math.max(e, s));
|
|
91
94
|
}
|
|
92
95
|
} catch (e) {
|
|
93
96
|
let t = e instanceof Error ? e.message : "Failed to load more templates";
|
|
94
|
-
console.error("Failed to load more templates:", e),
|
|
97
|
+
console.error("Failed to load more templates:", e), T(t);
|
|
95
98
|
}
|
|
96
99
|
}, [
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
]),
|
|
102
|
-
|
|
100
|
+
I,
|
|
101
|
+
L,
|
|
102
|
+
E,
|
|
103
|
+
A
|
|
104
|
+
]), W = l((e) => {
|
|
105
|
+
N((t) => ({
|
|
103
106
|
...t,
|
|
104
107
|
...e
|
|
105
108
|
}));
|
|
106
|
-
}, []),
|
|
107
|
-
|
|
109
|
+
}, []), G = l(() => {
|
|
110
|
+
N({});
|
|
108
111
|
}, []);
|
|
109
112
|
return {
|
|
110
|
-
templates:
|
|
111
|
-
allTemplates:
|
|
112
|
-
isLoading:
|
|
113
|
-
isCreating:
|
|
114
|
-
isUpdating:
|
|
115
|
-
isDeleting:
|
|
116
|
-
isMutating:
|
|
117
|
-
error:
|
|
118
|
-
hasMore:
|
|
119
|
-
total:
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
113
|
+
templates: z,
|
|
114
|
+
allTemplates: m,
|
|
115
|
+
isLoading: g,
|
|
116
|
+
isCreating: v,
|
|
117
|
+
isUpdating: b,
|
|
118
|
+
isDeleting: S,
|
|
119
|
+
isMutating: v || b || S,
|
|
120
|
+
error: w,
|
|
121
|
+
hasMore: E,
|
|
122
|
+
total: O,
|
|
123
|
+
dataUpdatedAt: P,
|
|
124
|
+
filter: M,
|
|
125
|
+
refetch: R,
|
|
126
|
+
loadMore: U,
|
|
127
|
+
createTemplate: B,
|
|
128
|
+
updateTemplate: V,
|
|
129
|
+
deleteTemplate: H,
|
|
130
|
+
updateFilter: W,
|
|
131
|
+
resetFilter: G
|
|
128
132
|
};
|
|
129
133
|
}
|
|
130
|
-
function
|
|
131
|
-
let { authToken:
|
|
134
|
+
function p(n, r) {
|
|
135
|
+
let { authToken: i, apiGatewayUrl: a } = e(), [s, c] = d(void 0), [f, p] = d(!1), [m, h] = d(null), g = l(() => t(a ?? void 0, i ?? void 0), [a, i]), _ = l(async () => {
|
|
132
136
|
if (n) {
|
|
133
137
|
p(!0), h(null);
|
|
134
138
|
try {
|
|
135
139
|
let e = await g().query({
|
|
136
|
-
query:
|
|
140
|
+
query: o,
|
|
137
141
|
variables: {
|
|
138
142
|
slug: n,
|
|
139
143
|
locale: r
|
|
140
144
|
},
|
|
141
145
|
fetchPolicy: "cache-first"
|
|
142
146
|
});
|
|
143
|
-
e.data?.notificationTemplate &&
|
|
147
|
+
e.data?.notificationTemplate && c(e.data.notificationTemplate);
|
|
144
148
|
} catch (e) {
|
|
145
149
|
let t = e instanceof Error ? e.message : "Failed to fetch template";
|
|
146
150
|
console.error("[useNotificationTemplate] Failed to fetch template:", e), h(t);
|
|
@@ -153,15 +157,15 @@ function d(n, r) {
|
|
|
153
157
|
n,
|
|
154
158
|
r
|
|
155
159
|
]);
|
|
156
|
-
return
|
|
160
|
+
return u(() => {
|
|
157
161
|
_();
|
|
158
162
|
}, [_]), {
|
|
159
|
-
template:
|
|
163
|
+
template: s,
|
|
160
164
|
isLoading: f,
|
|
161
165
|
error: m,
|
|
162
166
|
refetch: _
|
|
163
167
|
};
|
|
164
168
|
}
|
|
165
|
-
export {
|
|
169
|
+
export { p as useNotificationTemplate, f as useNotificationTemplates };
|
|
166
170
|
|
|
167
171
|
//# sourceMappingURL=useNotificationTemplates.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationTemplates.js","names":["NotificationOps.GetNotificationTemplatesDocument","NotificationOps.CreateNotificationTemplateDocument","NotificationOps.UpdateNotificationTemplateDocument","NotificationOps.DeleteNotificationTemplateDocument","NotificationOps.GetNotificationTemplateDocument","useNotificationTemplates","useNotification","templates","setTemplates","useState","isLoading","setIsLoading","isCreating","setIsCreating","isUpdating","setIsUpdating","isDeleting","setIsDeleting","error","setError","hasMore","setHasMore","total","setTotal","offset","setOffset","filter","setFilter","initialFilter","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","buildBackendFilter","backendFilter","fetchTemplates","result","GetNotificationTemplatesDocument","err","message","filteredTemplates","t","createTemplate","CreateNotificationTemplateDocument","updateTemplate","UpdateNotificationTemplateDocument","deleteTemplate","DeleteNotificationTemplateDocument","loadMore","moreTemplates","prev","updateFilter","newFilter","resetFilter","useNotificationTemplate","template","setTemplate","fetchTemplate","slug","GetNotificationTemplateDocument","locale","useEffect"],"sources":["../../src/hooks/useNotificationTemplates.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport type { NotificationType } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTemplatesQuery,\n GetNotificationTemplateQuery,\n CreateNotificationTemplateMutation,\n UpdateNotificationTemplateMutation,\n} from '../generated/global-operations';\n\n/**\n * Backend template type derived from the generated query\n */\nexport type BackendNotificationTemplate =\n GetNotificationTemplatesQuery['notificationTemplates']['items'][number];\n/**\n * Input type for creating a template (matches backend CreateTemplateInput)\n * Note: Templates are content-only - channel is specified at send time\n */\nexport interface CreateTemplateInput {\n slug: string;\n name: string;\n description?: string;\n type: NotificationType;\n channel?: string;\n locale?: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input type for updating a template (matches backend UpdateTemplateInput)\n */\nexport interface UpdateTemplateInput {\n name?: string;\n description?: string;\n subject?: string;\n bodyTemplate?: string;\n htmlTemplate?: string;\n variables?: Record<string, unknown>;\n enabled?: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Filter options for templates (matches backend TemplateFilterInput)\n * Note: channel filter removed - templates are content-only\n */\nexport interface TemplateFilter {\n type?: NotificationType;\n locale?: string;\n enabled?: boolean;\n search?: string; // Local filter only\n}\n\n/**\n * Hook to manage notification templates\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplates(initialFilter?: TemplateFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [templates, setTemplates] = useState<BackendNotificationTemplate[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isCreating, setIsCreating] = useState(false);\n const [isUpdating, setIsUpdating] = useState(false);\n const [isDeleting, setIsDeleting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [total, setTotal] = useState(0);\n const [offset, setOffset] = useState(0);\n const [filter, setFilter] = useState<TemplateFilter>(initialFilter || {});\n\n const LIMIT = 50;\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Build backend filter (excludes local-only 'search')\n const buildBackendFilter = useCallback(() => {\n const backendFilter: Record<string, unknown> = {};\n if (filter.type) backendFilter.type = filter.type;\n if (filter.locale) backendFilter.locale = filter.locale;\n if (filter.enabled !== undefined) backendFilter.enabled = filter.enabled;\n return Object.keys(backendFilter).length > 0 ? backendFilter : undefined;\n }, [filter]);\n\n // Fetch templates\n const fetchTemplates = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplatesQuery>({\n query: NotificationOps.GetNotificationTemplatesDocument,\n variables: {\n filter: buildBackendFilter(),\n limit: LIMIT,\n offset: 0,\n },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplates) {\n setTemplates(result.data.notificationTemplates.items || []);\n setTotal(result.data.notificationTemplates.total || 0);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset(LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch templates';\n console.error('[useNotificationTemplates] Failed to fetch templates:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, buildBackendFilter]);\n\n // Initial fetch\n useEffect(() => {\n fetchTemplates();\n }, [fetchTemplates]);\n\n // Filter by search locally\n const filteredTemplates = filter.search\n ? templates.filter(\n (t) =>\n t.name.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.slug.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.description?.toLowerCase().includes(filter.search!.toLowerCase())\n )\n : templates;\n\n // Create template\n const createTemplate = useCallback(\n async (input: CreateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsCreating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTemplateMutation>({\n mutation: NotificationOps.CreateNotificationTemplateDocument,\n variables: { input },\n });\n await fetchTemplates();\n return result.data!.createNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to create template';\n console.error('Failed to create template:', err);\n setError(message);\n throw err;\n } finally {\n setIsCreating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Update template\n const updateTemplate = useCallback(\n async (id: string, input: UpdateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsUpdating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTemplateMutation>({\n mutation: NotificationOps.UpdateNotificationTemplateDocument,\n variables: { id, input },\n });\n await fetchTemplates();\n return result.data!.updateNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to update template';\n console.error('Failed to update template:', err);\n setError(message);\n throw err;\n } finally {\n setIsUpdating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Delete template\n const deleteTemplate = useCallback(\n async (id: string): Promise<boolean> => {\n setIsDeleting(true);\n setError(null);\n\n try {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTemplateDocument,\n variables: { id },\n });\n await fetchTemplates();\n return true;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to delete template';\n console.error('Failed to delete template:', err);\n setError(message);\n throw err;\n } finally {\n setIsDeleting(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Load more templates\n const loadMore = useCallback(async () => {\n if (!hasMore) return;\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplatesQuery>({\n query: NotificationOps.GetNotificationTemplatesDocument,\n variables: {\n filter: buildBackendFilter(),\n limit: LIMIT,\n offset: offset,\n },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplates) {\n const moreTemplates = result.data.notificationTemplates.items || [];\n setTemplates((prev) => [...prev, ...moreTemplates]);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset((prev) => prev + LIMIT);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to load more templates';\n console.error('Failed to load more templates:', err);\n setError(message);\n }\n }, [getClient, buildBackendFilter, hasMore, offset]);\n\n // Update filter\n const updateFilter = useCallback((newFilter: Partial<TemplateFilter>) => {\n setFilter((prev) => ({ ...prev, ...newFilter }));\n }, []);\n\n // Reset filter\n const resetFilter = useCallback(() => {\n setFilter({});\n }, []);\n\n return {\n templates: filteredTemplates,\n allTemplates: templates,\n isLoading,\n isCreating,\n isUpdating,\n isDeleting,\n isMutating: isCreating || isUpdating || isDeleting,\n error,\n hasMore,\n total,\n filter,\n refetch: fetchTemplates,\n loadMore,\n createTemplate,\n updateTemplate,\n deleteTemplate,\n updateFilter,\n resetFilter,\n };\n}\n\n/**\n * Hook to fetch a single template by slug\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplate(slug: string | undefined, locale?: string) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [template, setTemplate] = useState<BackendNotificationTemplate | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Fetch template\n const fetchTemplate = useCallback(async () => {\n if (!slug) return;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplateQuery>({\n query: NotificationOps.GetNotificationTemplateDocument,\n variables: { slug, locale },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplate) {\n setTemplate(result.data.notificationTemplate);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch template';\n console.error('[useNotificationTemplate] Failed to fetch template:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, slug, locale]);\n\n // Fetch on mount and when slug changes\n useEffect(() => {\n fetchTemplate();\n }, [fetchTemplate]);\n\n return {\n template,\n isLoading,\n error,\n refetch: fetchTemplate,\n };\n}\n"],"mappings":";;;;;AAgEA,SAAgBK,EAAyB,GAAgC;CACvE,IAAM,EAAE,cAAW,qBAAkBC,EAAgB,GAC/C,CAACC,GAAWC,KAAgBC,EAAwC,CAAC,CAAC,GACtE,CAACC,GAAWC,KAAgBF,EAAS,EAAK,GAC1C,CAACG,GAAYC,KAAiBJ,EAAS,EAAK,GAC5C,CAACK,GAAYC,KAAiBN,EAAS,EAAK,GAC5C,CAACO,GAAYC,KAAiBR,EAAS,EAAK,GAC5C,CAACS,GAAOC,KAAYV,EAAwB,IAAI,GAChD,CAACW,GAASC,KAAcZ,EA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ACA;EACA,SAASoB;EACT;EACA;EACA;EACA;EACA;EACA;CACF;AACF;AAMA,SAAgBmB,EAAwB,GAA0B,GAAiB;CACjF,IAAM,EAAE,cAAW,qBAAkBjD,EAAgB,GAC/C,CAACkD,GAAUC,KAAehD,EAAkD,KAAA,CAAS,GACrF,CAACC,GAAWC,KAAgBF,EAAS,EAAK,GAC1C,CAACS,GAAOC,KAAYV,EAAwB,IAAI,GAGhDoB,IAAYC,QACTC,EAA4BC,KAAiB,KAAA,GAAWC,KAAa,KAAA,CAAS,GACpF,CAACD,GAAeC,CAAS,CAAC,GAGvByB,IAAgB5B,EAAY,YAAY;EAC5C,IAAK6B,GAEL;GACA,AADAhD,EAAa,EAAI,GACjBQ,EAAS,IAAI;GAEb,IAAI;IAEF,IAAMkB,IAAS,MADAR,EACM,CAAA,CAAO,MAAoC;KAC9D,OAAOzB;KACP,WAAW;MAAE;MAAM;KAAO;KAC1B,aAAa;IACf,CAAC;IAED,AAAIiC,EAAO,MAAM,wBACfoB,EAAYpB,EAAO,KAAK,oBAAoB;GAEhD,SAASE,GAAc;IACrB,IAAMC,IAAUD,aAAe,QAAQA,EAAI,UAAU;IAErD,AADA,QAAQ,MAAM,uDAAuDA,CAAG,GACxEpB,EAASqB,CAAO;GAClB,UAAU;IACR,EAAa,EAAK;GACpB;EApBiB;CAqBnB,GAAG;EAACX;EAAW8B;EAAME;CAAM,CAAC;CAO5B,OAJAC,QAAgB;EACd,EAAc;CAChB,GAAG,CAACJ,CAAa,CAAC,GAEX;EACL;EACA;EACA;EACA,SAASA;CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"useNotificationTemplates.js","names":["NotificationOps.GetNotificationTemplatesDocument","NotificationOps.CreateNotificationTemplateDocument","NotificationOps.UpdateNotificationTemplateDocument","NotificationOps.DeleteNotificationTemplateDocument","NotificationOps.GetNotificationTemplateDocument","useNotificationTemplates","useNotification","templates","setTemplates","useState","isLoading","setIsLoading","isCreating","setIsCreating","isUpdating","setIsUpdating","isDeleting","setIsDeleting","error","setError","hasMore","setHasMore","total","setTotal","offset","setOffset","filter","setFilter","initialFilter","dataUpdatedAt","setDataUpdatedAt","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","buildBackendFilter","backendFilter","fetchTemplates","client","query","GetNotificationTemplatesDocument","variables","cached","inCache","result","answeredAt","err","message","filteredTemplates","t","createTemplate","CreateNotificationTemplateDocument","updateTemplate","UpdateNotificationTemplateDocument","deleteTemplate","DeleteNotificationTemplateDocument","loadMore","moreTemplates","prev","at","updateFilter","newFilter","resetFilter","useNotificationTemplate","template","setTemplate","fetchTemplate","slug","GetNotificationTemplateDocument","locale","useEffect"],"sources":["../../src/hooks/useNotificationTemplates.ts"],"sourcesContent":["import { useState, useCallback, useEffect } from 'react';\nimport { useNotification } from '../providers/NotificationProvider';\nimport { getGlobalNotificationClient } from '../graphql/global-client';\nimport { answeredAt, inCache } from './answeredAt';\nimport type { NotificationType } from '../types';\nimport * as NotificationOps from '../generated/global-operations';\nimport type {\n GetNotificationTemplatesQuery,\n GetNotificationTemplateQuery,\n CreateNotificationTemplateMutation,\n UpdateNotificationTemplateMutation,\n} from '../generated/global-operations';\n\n/**\n * Backend template type derived from the generated query\n */\nexport type BackendNotificationTemplate =\n GetNotificationTemplatesQuery['notificationTemplates']['items'][number];\n/**\n * Input type for creating a template (matches backend CreateTemplateInput)\n * Note: Templates are content-only - channel is specified at send time\n */\nexport interface CreateTemplateInput {\n slug: string;\n name: string;\n description?: string;\n type: NotificationType;\n channel?: string;\n locale?: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Input type for updating a template (matches backend UpdateTemplateInput)\n */\nexport interface UpdateTemplateInput {\n name?: string;\n description?: string;\n subject?: string;\n bodyTemplate?: string;\n htmlTemplate?: string;\n variables?: Record<string, unknown>;\n enabled?: boolean;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Filter options for templates (matches backend TemplateFilterInput)\n * Note: channel filter removed - templates are content-only\n */\nexport interface TemplateFilter {\n type?: NotificationType;\n locale?: string;\n enabled?: boolean;\n search?: string; // Local filter only\n}\n\n/**\n * Hook to manage notification templates\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplates(initialFilter?: TemplateFilter) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [templates, setTemplates] = useState<BackendNotificationTemplate[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isCreating, setIsCreating] = useState(false);\n const [isUpdating, setIsUpdating] = useState(false);\n const [isDeleting, setIsDeleting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasMore, setHasMore] = useState(false);\n const [total, setTotal] = useState(0);\n const [offset, setOffset] = useState(0);\n const [filter, setFilter] = useState<TemplateFilter>(initialFilter || {});\n // When the templates on hand arrived (ms since the epoch), as React Query's `dataUpdatedAt`.\n const [dataUpdatedAt, setDataUpdatedAt] = useState(0);\n\n const LIMIT = 50;\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Build backend filter (excludes local-only 'search')\n const buildBackendFilter = useCallback(() => {\n const backendFilter: Record<string, unknown> = {};\n if (filter.type) backendFilter.type = filter.type;\n if (filter.locale) backendFilter.locale = filter.locale;\n if (filter.enabled !== undefined) backendFilter.enabled = filter.enabled;\n return Object.keys(backendFilter).length > 0 ? backendFilter : undefined;\n }, [filter]);\n\n // Fetch templates\n const fetchTemplates = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const query = NotificationOps.GetNotificationTemplatesDocument;\n const variables = { filter: buildBackendFilter(), limit: LIMIT, offset: 0 };\n // A cache-first read: an answer from the cache keeps the time it really arrived.\n const cached = inCache(client, query, variables);\n const result = await client.query<GetNotificationTemplatesQuery>({\n query,\n variables,\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplates) {\n setTemplates(result.data.notificationTemplates.items || []);\n setTotal(result.data.notificationTemplates.total || 0);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset(LIMIT);\n setDataUpdatedAt(answeredAt(client, query, variables, cached));\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch templates';\n console.error('[useNotificationTemplates] Failed to fetch templates:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, buildBackendFilter]);\n\n // Initial fetch\n useEffect(() => {\n fetchTemplates();\n }, [fetchTemplates]);\n\n // Filter by search locally\n const filteredTemplates = filter.search\n ? templates.filter(\n (t) =>\n t.name.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.slug.toLowerCase().includes(filter.search!.toLowerCase()) ||\n t.description?.toLowerCase().includes(filter.search!.toLowerCase())\n )\n : templates;\n\n // Create template\n const createTemplate = useCallback(\n async (input: CreateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsCreating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<CreateNotificationTemplateMutation>({\n mutation: NotificationOps.CreateNotificationTemplateDocument,\n variables: { input },\n });\n await fetchTemplates();\n return result.data!.createNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to create template';\n console.error('Failed to create template:', err);\n setError(message);\n throw err;\n } finally {\n setIsCreating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Update template\n const updateTemplate = useCallback(\n async (id: string, input: UpdateTemplateInput): Promise<BackendNotificationTemplate> => {\n setIsUpdating(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.mutate<UpdateNotificationTemplateMutation>({\n mutation: NotificationOps.UpdateNotificationTemplateDocument,\n variables: { id, input },\n });\n await fetchTemplates();\n return result.data!.updateNotificationTemplate;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to update template';\n console.error('Failed to update template:', err);\n setError(message);\n throw err;\n } finally {\n setIsUpdating(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Delete template\n const deleteTemplate = useCallback(\n async (id: string): Promise<boolean> => {\n setIsDeleting(true);\n setError(null);\n\n try {\n const client = getClient();\n await client.mutate({\n mutation: NotificationOps.DeleteNotificationTemplateDocument,\n variables: { id },\n });\n await fetchTemplates();\n return true;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to delete template';\n console.error('Failed to delete template:', err);\n setError(message);\n throw err;\n } finally {\n setIsDeleting(false);\n }\n },\n [getClient, fetchTemplates]\n );\n\n // Load more templates\n const loadMore = useCallback(async () => {\n if (!hasMore) return;\n\n try {\n const client = getClient();\n const query = NotificationOps.GetNotificationTemplatesDocument;\n const variables = { filter: buildBackendFilter(), limit: LIMIT, offset: offset };\n const cached = inCache(client, query, variables);\n const result = await client.query<GetNotificationTemplatesQuery>({\n query,\n variables,\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplates) {\n const moreTemplates = result.data.notificationTemplates.items || [];\n setTemplates((prev) => [...prev, ...moreTemplates]);\n setHasMore(result.data.notificationTemplates.hasMore || false);\n setOffset((prev) => prev + LIMIT);\n // The list now holds this page too: the newest answer's time, as React Query's does.\n const at = answeredAt(client, query, variables, cached);\n setDataUpdatedAt((prev) => Math.max(prev, at));\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to load more templates';\n console.error('Failed to load more templates:', err);\n setError(message);\n }\n }, [getClient, buildBackendFilter, hasMore, offset]);\n\n // Update filter\n const updateFilter = useCallback((newFilter: Partial<TemplateFilter>) => {\n setFilter((prev) => ({ ...prev, ...newFilter }));\n }, []);\n\n // Reset filter\n const resetFilter = useCallback(() => {\n setFilter({});\n }, []);\n\n return {\n templates: filteredTemplates,\n allTemplates: templates,\n isLoading,\n isCreating,\n isUpdating,\n isDeleting,\n isMutating: isCreating || isUpdating || isDeleting,\n error,\n hasMore,\n total,\n /** When the templates on hand arrived (ms since the epoch); 0 before the first answer. */\n dataUpdatedAt,\n filter,\n refetch: fetchTemplates,\n loadMore,\n createTemplate,\n updateTemplate,\n deleteTemplate,\n updateFilter,\n resetFilter,\n };\n}\n\n/**\n * Hook to fetch a single template by slug\n * Uses the GLOBAL Apollo client for API calls\n */\nexport function useNotificationTemplate(slug: string | undefined, locale?: string) {\n const { authToken, apiGatewayUrl } = useNotification();\n const [template, setTemplate] = useState<BackendNotificationTemplate | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // Get global client — coerce null/undefined authToken to undefined\n const getClient = useCallback(() => {\n return getGlobalNotificationClient(apiGatewayUrl ?? undefined, authToken ?? undefined);\n }, [apiGatewayUrl, authToken]);\n\n // Fetch template\n const fetchTemplate = useCallback(async () => {\n if (!slug) return;\n\n setIsLoading(true);\n setError(null);\n\n try {\n const client = getClient();\n const result = await client.query<GetNotificationTemplateQuery>({\n query: NotificationOps.GetNotificationTemplateDocument,\n variables: { slug, locale },\n fetchPolicy: 'cache-first',\n });\n\n if (result.data?.notificationTemplate) {\n setTemplate(result.data.notificationTemplate);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : 'Failed to fetch template';\n console.error('[useNotificationTemplate] Failed to fetch template:', err);\n setError(message);\n } finally {\n setIsLoading(false);\n }\n }, [getClient, slug, locale]);\n\n // Fetch on mount and when slug changes\n useEffect(() => {\n fetchTemplate();\n }, [fetchTemplate]);\n\n return {\n template,\n isLoading,\n error,\n refetch: fetchTemplate,\n };\n}\n"],"mappings":";;;;;;AAiEA,SAAgBK,EAAyB,GAAgC;CACvE,IAAM,EAAE,cAAW,qBAAkBC,EAAgB,GAC/C,CAACC,GAAWC,KAAgBC,EAAwC,CAAC,CAAC,GACtE,CAACC,GAAWC,KAAgBF,EAAS,EAAK,GAC1C,CAACG,GAAYC,KAAiBJ,EAAS,EAAK,GAC5C,CAACK,GAAYC,KAAiBN,EAAS,EAAK,GAC5C,CAACO,GAAYC,KAAiBR,EAAS,EAAK,GAC5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,EAAa,EAAK;GACpB;EApBiB;CAqBnB,GAAG;EAACjB;EAAWqC;EAAME;CAAM,CAAC;CAO5B,OAJAC,QAAgB;EACd,EAAc;CAChB,GAAG,CAACJ,CAAa,CAAC,GAEX;EACL;EACA;EACA;EACA,SAASA;CACX;AACF"}
|
|
@@ -25,6 +25,8 @@ export declare function useNotificationTopics(initialFilter?: NotificationTopicF
|
|
|
25
25
|
isLoading: boolean;
|
|
26
26
|
error: string | null;
|
|
27
27
|
isForbidden: boolean;
|
|
28
|
+
/** When the topics on hand arrived (ms since the epoch); 0 before the first answer. */
|
|
29
|
+
dataUpdatedAt: number;
|
|
28
30
|
filter: NotificationTopicFilter;
|
|
29
31
|
setFilter: import('react').Dispatch<import('react').SetStateAction<NotificationTopicFilter>>;
|
|
30
32
|
refetch: () => Promise<void>;
|
|
@@ -26,10 +26,10 @@ function d(e) {
|
|
|
26
26
|
};
|
|
27
27
|
}
|
|
28
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]),
|
|
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, E] = u(0), D = c(() => t(m ?? void 0, p ?? void 0), [m, p]), O = c(async () => {
|
|
30
30
|
v(!0), b(null), S(!1);
|
|
31
31
|
try {
|
|
32
|
-
let e = await
|
|
32
|
+
let e = await D().query({
|
|
33
33
|
query: a,
|
|
34
34
|
variables: {
|
|
35
35
|
filter: {
|
|
@@ -42,29 +42,30 @@ function f(f) {
|
|
|
42
42
|
},
|
|
43
43
|
fetchPolicy: "network-only"
|
|
44
44
|
});
|
|
45
|
-
g((e.data?.notificationTopics.items || []).map(d));
|
|
45
|
+
g((e.data?.notificationTopics.items || []).map(d)), E(Date.now());
|
|
46
46
|
} catch (e) {
|
|
47
47
|
n(e) ? S(!0) : (console.error("[useNotificationTopics] Failed to fetch topics:", e), b(e instanceof Error ? e.message : "Failed to fetch topics")), g([]);
|
|
48
48
|
} finally {
|
|
49
49
|
v(!1);
|
|
50
50
|
}
|
|
51
|
-
}, [C,
|
|
51
|
+
}, [C, D]);
|
|
52
52
|
return l(() => {
|
|
53
|
-
|
|
54
|
-
}, [
|
|
53
|
+
O();
|
|
54
|
+
}, [O]), {
|
|
55
55
|
topics: h,
|
|
56
56
|
isLoading: _,
|
|
57
57
|
error: y,
|
|
58
58
|
isForbidden: x,
|
|
59
|
+
dataUpdatedAt: T,
|
|
59
60
|
filter: C,
|
|
60
61
|
setFilter: w,
|
|
61
|
-
refetch:
|
|
62
|
+
refetch: O,
|
|
62
63
|
createTopic: c(async (e) => {
|
|
63
|
-
let t = await
|
|
64
|
+
let t = await D().mutate({
|
|
64
65
|
mutation: r,
|
|
65
66
|
variables: { input: e }
|
|
66
67
|
});
|
|
67
|
-
await
|
|
68
|
+
await O();
|
|
68
69
|
let n = t.data?.createNotificationTopic;
|
|
69
70
|
return n ? {
|
|
70
71
|
id: n.id,
|
|
@@ -77,16 +78,16 @@ function f(f) {
|
|
|
77
78
|
createdAt: n.createdAt,
|
|
78
79
|
updatedAt: n.updatedAt
|
|
79
80
|
} : null;
|
|
80
|
-
}, [
|
|
81
|
+
}, [O, D]),
|
|
81
82
|
updateTopic: c(async (e, t) => {
|
|
82
|
-
let n = await
|
|
83
|
+
let n = await D().mutate({
|
|
83
84
|
mutation: s,
|
|
84
85
|
variables: {
|
|
85
86
|
id: e,
|
|
86
87
|
input: t
|
|
87
88
|
}
|
|
88
89
|
});
|
|
89
|
-
await
|
|
90
|
+
await O();
|
|
90
91
|
let r = n.data?.updateNotificationTopic;
|
|
91
92
|
return r ? {
|
|
92
93
|
id: r.id,
|
|
@@ -99,20 +100,20 @@ function f(f) {
|
|
|
99
100
|
createdAt: r.createdAt,
|
|
100
101
|
updatedAt: r.updatedAt
|
|
101
102
|
} : null;
|
|
102
|
-
}, [
|
|
103
|
-
deleteTopic: c(async (e) => (await
|
|
103
|
+
}, [O, D]),
|
|
104
|
+
deleteTopic: c(async (e) => (await D().mutate({
|
|
104
105
|
mutation: i,
|
|
105
106
|
variables: { id: e }
|
|
106
|
-
}), await
|
|
107
|
+
}), await O(), !0), [O, D]),
|
|
107
108
|
setTopicSubscription: c(async (e, t) => {
|
|
108
|
-
let n = await
|
|
109
|
+
let n = await D().mutate({
|
|
109
110
|
mutation: o,
|
|
110
111
|
variables: { input: {
|
|
111
112
|
topicId: e,
|
|
112
113
|
subscribed: t
|
|
113
114
|
} }
|
|
114
115
|
});
|
|
115
|
-
await
|
|
116
|
+
await O();
|
|
116
117
|
let r = n.data?.setNotificationTopicSubscription;
|
|
117
118
|
return r ? {
|
|
118
119
|
id: r.id,
|
|
@@ -121,7 +122,7 @@ function f(f) {
|
|
|
121
122
|
topicId: r.topicId,
|
|
122
123
|
userId: r.userId
|
|
123
124
|
} : null;
|
|
124
|
-
}, [
|
|
125
|
+
}, [O, D])
|
|
125
126
|
};
|
|
126
127
|
}
|
|
127
128
|
export { f as useNotificationTopics };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotificationTopics.js","names":["NotificationOps.GetNotificationTopicsDocument","NotificationOps.CreateNotificationTopicDocument","NotificationOps.UpdateNotificationTopicDocument","NotificationOps.DeleteNotificationTopicDocument","NotificationOps.SetNotificationTopicSubscriptionDocument","mapTopic","topic","useNotificationTopics","useNotification","topics","setTopics","useState","isLoading","setIsLoading","error","setError","isForbidden","setIsForbidden","filter","setFilter","initialFilter","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","fetchTopics","result","GetNotificationTopicsDocument","err","isPermissionError","useEffect","CreateNotificationTopicDocument","created","UpdateNotificationTopicDocument","updated","DeleteNotificationTopicDocument","SetNotificationTopicSubscriptionDocument","subscription"],"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,SAASK,EACP,GACmB;CACnB,OAAO;EACL,IAAIC,EAAM;EACV,MAAMA,EAAM;EACZ,MAAMA,EAAM;EACZ,aAAaA,EAAM,eAAe,KAAA;EAClC,MAAMA,EAAM;EACZ,UAAUA,EAAM;EAChB,UAAUA,EAAM,YAAY,KAAA;EAC5B,iBAAiBA,EAAM,mBAAmB;EAC1C,gBAAgBA,EAAM,iBAClB;GACE,I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EAAE,MAAG;EAClB,CAAC,GACD,MAAMuB,EAAY,GACX,KAET,CAACA,GAAaL,CAAS,CAyCvB;EACA,sBAvC2BC,EAC3B,OAAO,GAAiB,MAAuE;GAE7F,IAAMK,IAAS,MADAN,EACM,CAAA,CAAO,OAAiD;IAC3E,UAAUjB;IACV,WAAW,EACT,OAAO;KACL;KACA;IACF,EACF;GACF,CAAC;GACD,MAAMsB,EAAY;GAElB,IAAMY,IAAeX,EAAO,MAAM;GAClC,OAAOW,IACH;IACE,IAAIA,EAAa;IACjB,YAAYA,EAAa;IACzB,gBAAgBA,EAAa,kBAAkB,KAAA;IAC/C,SAASA,EAAa;IACtB,QAAQA,EAAa;GACvB,IACA;EACN,GACA,CAACZ,GAAaL,CAAS,CAcvB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"useNotificationTopics.js","names":["NotificationOps.GetNotificationTopicsDocument","NotificationOps.CreateNotificationTopicDocument","NotificationOps.UpdateNotificationTopicDocument","NotificationOps.DeleteNotificationTopicDocument","NotificationOps.SetNotificationTopicSubscriptionDocument","mapTopic","topic","useNotificationTopics","useNotification","topics","setTopics","useState","isLoading","setIsLoading","error","setError","isForbidden","setIsForbidden","filter","setFilter","initialFilter","dataUpdatedAt","setDataUpdatedAt","getClient","useCallback","getGlobalNotificationClient","apiGatewayUrl","authToken","fetchTopics","result","GetNotificationTopicsDocument","err","isPermissionError","useEffect","CreateNotificationTopicDocument","created","UpdateNotificationTopicDocument","updated","DeleteNotificationTopicDocument","SetNotificationTopicSubscriptionDocument","subscription"],"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 // When the topics on hand arrived (ms since the epoch), as React Query's `dataUpdatedAt`.\n const [dataUpdatedAt, setDataUpdatedAt] = useState(0);\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 setDataUpdatedAt(Date.now());\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 /** When the topics on hand arrived (ms since the epoch); 0 before the first answer. */\n dataUpdatedAt,\n filter,\n setFilter,\n refetch: fetchTopics,\n createTopic,\n updateTopic,\n deleteTopic,\n setTopicSubscription,\n };\n}\n"],"mappings":";;;;;;AAqCA,SAASK,EACP,GACmB;CACnB,OAAO;EACL,IAAIC,EAAM;EACV,MAAMA,EAAM;EACZ,MAAMA,EAAM;EACZ,aAAaA,EAAM,eAAe,KAAA;EAClC,MAAMA,EAAM;EACZ,UAAUA,EAAM;EAChB,UAAUA,EAAM,YAAY,KAAA;EAC5B,iBAAiBA,EAAM,mBAAmB;EAC1C,gBAAgBA,EAAM,iBAClB;GACE,IAAIA,EAAM,eAAe;GACzB,YAAYA,EAAM,eAAe;GACjC,gBAAgBA,EAAM,eAAe,kBAAkB,KAAA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WAAW,EAAE,MAAG;EAClB,CAAC,GACD,MAAMyB,EAAY,GACX,KAET,CAACA,GAAaL,CAAS,CA2CvB;EACA,sBAzC2BC,EAC3B,OAAO,GAAiB,MAAuE;GAE7F,IAAMK,IAAS,MADAN,EACM,CAAA,CAAO,OAAiD;IAC3E,UAAUnB;IACV,WAAW,EACT,OAAO;KACL;KACA;IACF,EACF;GACF,CAAC;GACD,MAAMwB,EAAY;GAElB,IAAMY,IAAeX,EAAO,MAAM;GAClC,OAAOW,IACH;IACE,IAAIA,EAAa;IACjB,YAAYA,EAAa;IACzB,gBAAgBA,EAAa,kBAAkB,KAAA;IAC/C,SAASA,EAAa;IACtB,QAAQA,EAAa;GACvB,IACA;EACN,GACA,CAACZ,GAAaL,CAAS,CAgBvB;CACF;AACF"}
|
|
@@ -33,6 +33,8 @@ export declare function useNotifications(options?: UseNotificationsOptions): {
|
|
|
33
33
|
error: string | null;
|
|
34
34
|
hasMore: boolean;
|
|
35
35
|
total: number;
|
|
36
|
+
/** When the notifications on hand arrived (ms since the epoch); 0 before the first answer. */
|
|
37
|
+
dataUpdatedAt: number;
|
|
36
38
|
markAsRead: (notificationId: string) => Promise<void>;
|
|
37
39
|
markAllAsRead: () => Promise<void>;
|
|
38
40
|
archiveNotification: (notificationId: string) => Promise<void>;
|