@shiva004/surveys 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +52 -2
  3. package/package.json +45 -4
  4. package/src/Pages/Allsurvey/Allsurvey.tsx +157 -0
  5. package/src/Pages/Allsurvey/SurveyGridCard.tsx +124 -0
  6. package/src/Pages/Allsurvey/index.ts +1 -0
  7. package/src/Pages/Allsurvey/surveysTable.config.ts +15 -0
  8. package/src/Pages/Createsurvey/Createsurvey.tsx +318 -0
  9. package/src/Pages/Createsurvey/index.ts +1 -0
  10. package/src/Pages/NPStracker/NPStracker.tsx +78 -0
  11. package/src/Pages/NPStracker/index.ts +1 -0
  12. package/src/Pages/Responses/Responses.tsx +61 -0
  13. package/src/Pages/Responses/index.ts +1 -0
  14. package/src/Pages/Responses/responsesTable.config.ts +74 -0
  15. package/src/Pages/Surveyanalytics/Surveyanalytics.tsx +154 -0
  16. package/src/Pages/Surveyanalytics/analyticsTable.config.ts +123 -0
  17. package/src/Pages/Surveyanalytics/index.ts +1 -0
  18. package/src/Pages/Surveydetails/Surveydetails.tsx +202 -0
  19. package/src/Pages/Surveydetails/index.ts +1 -0
  20. package/src/Pages/Surveytemplates/Surveytemplates.tsx +299 -0
  21. package/src/Pages/Surveytemplates/index.ts +1 -0
  22. package/src/Pages/surveyPage.module.scss +49 -0
  23. package/src/cells/SurveyCells.tsx +370 -0
  24. package/src/components/ui.ts +3 -0
  25. package/src/hooks/useSurveyResponses.ts +37 -0
  26. package/src/hooks/useTableConfig.ts +77 -0
  27. package/src/hooks/useTableData.ts +184 -0
  28. package/src/index.ts +24 -0
  29. package/src/nav.ts +55 -0
  30. package/src/routes.ts +98 -0
  31. package/src/services/api/TableConfigDto.ts +36 -0
  32. package/src/services/api/TableQueryParams.ts +10 -0
  33. package/src/services/api/surveys.api.ts +144 -0
  34. package/src/services/api/types.ts +113 -0
  35. package/src/types/survey.types.ts +175 -0
@@ -0,0 +1,370 @@
1
+ // src/features/surveys/cells/SurveyCells.tsx
2
+ import type { CellRegistration } from '@/app/cells/types';
3
+ import type { RecordIdentifier, TableCellProps } from '@/shared/components/DataTable/types';
4
+ import { Icon } from '@/shared/components/ui/Icon/Icon';
5
+ import React, { memo } from 'react';
6
+ import type { SurveyAnalyticsRow, SurveyResponseItem, SurveyRow } from '../types/survey.types';
7
+
8
+ type CellProps = TableCellProps<RecordIdentifier>;
9
+
10
+ /** Row actions the page can inject through DataTable's `extra`. */
11
+ type SurveyActions = {
12
+ onView?: (row: SurveyRow) => void;
13
+ onEdit?: (row: SurveyRow) => void;
14
+ onDelete?: (row: SurveyRow) => void;
15
+ };
16
+
17
+ const asSurvey = (row: RecordIdentifier) => row as unknown as SurveyRow;
18
+ const asAnalytics = (row: RecordIdentifier) => row as unknown as SurveyAnalyticsRow;
19
+ const asResponse = (row: RecordIdentifier) => row as unknown as SurveyResponseItem;
20
+
21
+ // ─────────────────────────────────────────────────────────────────────────────
22
+ // Status map & Helpers
23
+ // ─────────────────────────────────────────────────────────────────────────────
24
+
25
+ const str = (v: unknown): string => (v != null ? String(v) : '');
26
+
27
+ const num = (v: unknown): number => {
28
+ const n = Number(v);
29
+ return Number.isFinite(n) ? n : 0;
30
+ };
31
+
32
+ const STATUS: Record<string, { dot: string; badge: string }> = {
33
+ active: {
34
+ dot: 'bg-[#4edea3] animate-pulse',
35
+ badge: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]',
36
+ },
37
+ draft: {
38
+ dot: 'bg-[#ffcc6b]',
39
+ badge: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]',
40
+ },
41
+ paused: {
42
+ dot: 'bg-[#adc6ff]',
43
+ badge: 'bg-[color:color-mix(in_srgb,var(--th-info-soft)_10%,transparent)] text-[color:var(--th-info-soft)]',
44
+ },
45
+ closed: {
46
+ dot: 'bg-[#958da1]',
47
+ badge: 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)]',
48
+ },
49
+ };
50
+
51
+ // ─────────────────────────────────────────────────────────────────────────────
52
+ // 1. Survey Status Cell
53
+ // ─────────────────────────────────────────────────────────────────────────────
54
+
55
+ const SurveyStatusCell = memo(({ row }: CellProps) => {
56
+ const status = str(asSurvey(row).status);
57
+ const c = STATUS[status] ?? STATUS.draft;
58
+
59
+ return (
60
+ <div className="flex items-center justify-center">
61
+ <span className={`w-2.5 h-2.5 rounded-full ${c.dot}`} />
62
+ </div>
63
+ );
64
+ });
65
+ SurveyStatusCell.displayName = 'SurveyStatusCell';
66
+
67
+ // ─────────────────────────────────────────────────────────────────────────────
68
+ // 2. Survey Name Cell
69
+ // ─────────────────────────────────────────────────────────────────────────────
70
+
71
+ const SurveyNameCell = memo(({ row }: CellProps) => {
72
+ const x = asSurvey(row);
73
+ const status = str(x.status);
74
+ const c = STATUS[status] ?? STATUS.draft;
75
+ const name = str(x.name);
76
+ const description = str(x.description);
77
+ const npsScore = x.npsScore;
78
+
79
+ return (
80
+ <div className="flex flex-col gap-0.5 min-w-0">
81
+ <div className="flex items-center gap-1.5 flex-wrap">
82
+ <Icon
83
+ icon="ClipboardList"
84
+ size={14}
85
+ className="text-[#7c3aed] shrink-0"
86
+ />
87
+
88
+ <span className="text-[13px] font-medium text-white truncate max-w-[280px]">
89
+ {name}
90
+ </span>
91
+
92
+ <span
93
+ className={`text-[9px] px-1.5 py-0.5 rounded font-medium capitalize shrink-0 ${c.badge}`}
94
+ >
95
+ {status}
96
+ </span>
97
+
98
+ {npsScore !== null && npsScore !== undefined && (
99
+ <span
100
+ className={`text-[9px] px-1.5 py-0.5 rounded shrink-0 ${npsScore >= 70
101
+ ? 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]'
102
+ : npsScore >= 50
103
+ ? 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]'
104
+ : 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]'
105
+ }`}
106
+ >
107
+ NPS {npsScore}
108
+ </span>
109
+ )}
110
+ </div>
111
+
112
+ {description && (
113
+ <span className="text-[11px] text-[color:var(--th-text-3)] truncate max-w-[320px] pl-5">
114
+ {description}
115
+ </span>
116
+ )}
117
+ </div>
118
+ );
119
+ });
120
+ SurveyNameCell.displayName = 'SurveyNameCell';
121
+
122
+ // ─────────────────────────────────────────────────────────────────────────────
123
+ // 3. Response Progress Cell
124
+ // ─────────────────────────────────────────────────────────────────────────────
125
+
126
+ const ResponseProgressCell = memo(({ row }: CellProps) => {
127
+ const x = asSurvey(row);
128
+ const responses = num(x.responses);
129
+ const target = num(x.target);
130
+ const pct = target > 0 ? Math.min((responses / target) * 100, 100) : 0;
131
+
132
+ return (
133
+ <div className="flex flex-col items-center gap-1 min-w-[100px]">
134
+ <span className="text-[12px] font-mono text-[color:var(--th-text-1)] tabular-nums">
135
+ {responses.toLocaleString()}
136
+ <span className="text-[color:var(--th-text-3)]">/{target.toLocaleString()}</span>
137
+ </span>
138
+
139
+ <div className="w-full h-1.5 rounded-full bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] overflow-hidden">
140
+ <div
141
+ className={`h-full rounded-full ${pct >= 80 ? 'bg-[#4edea3]' : 'bg-[#7c3aed]'
142
+ }`}
143
+ style={{ width: `${pct}%` }}
144
+ />
145
+ </div>
146
+ </div>
147
+ );
148
+ });
149
+ ResponseProgressCell.displayName = 'ResponseProgressCell';
150
+
151
+ // ─────────────────────────────────────────────────────────────────────────────
152
+ // 4. NPS Score Cell
153
+ // ─────────────────────────────────────────────────────────────────────────────
154
+
155
+ const NpsScoreCell = memo(({ row }: CellProps) => {
156
+ const value = asSurvey(row).npsScore;
157
+ if (value == null) {
158
+ return <span className="text-[12px] text-[color:var(--th-text-3)]">—</span>;
159
+ }
160
+
161
+ const n = num(value);
162
+ const cls =
163
+ n >= 70
164
+ ? 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]'
165
+ : n >= 50
166
+ ? 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]'
167
+ : 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]';
168
+
169
+ return (
170
+ <span className={`text-[12px] font-bold font-mono px-2 py-0.5 rounded ${cls}`}>
171
+ {n}
172
+ </span>
173
+ );
174
+ });
175
+ NpsScoreCell.displayName = 'NpsScoreCell';
176
+
177
+ // ─────────────────────────────────────────────────────────────────────────────
178
+ // 5. Survey Actions Cell
179
+ // ─────────────────────────────────────────────────────────────────────────────
180
+
181
+ const SurveyActionsCell = memo(({ row, extra }: CellProps) => {
182
+ const actions = extra as SurveyActions | undefined;
183
+ const x = asSurvey(row);
184
+
185
+ return (
186
+ <div className="flex items-center justify-end gap-1">
187
+ <button
188
+ onClick={(e) => {
189
+ e.stopPropagation();
190
+ actions?.onView?.(x);
191
+ }}
192
+ className="p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-2)] transition-colors"
193
+ >
194
+ <Icon icon="BarChart3" size={13} />
195
+ </button>
196
+
197
+ <button
198
+ onClick={(e) => {
199
+ e.stopPropagation();
200
+ actions?.onEdit?.(x);
201
+ }}
202
+ className="p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-text-2)] transition-colors"
203
+ >
204
+ <Icon icon="Edit3" size={13} />
205
+ </button>
206
+
207
+ <button
208
+ onClick={(e) => {
209
+ e.stopPropagation();
210
+ actions?.onDelete?.(x);
211
+ }}
212
+ className="p-1.5 rounded-lg hover:bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-text-3)] hover:text-[color:var(--th-danger-soft)] transition-colors"
213
+ >
214
+ <Icon icon="Trash2" size={13} />
215
+ </button>
216
+ </div>
217
+ );
218
+ });
219
+ SurveyActionsCell.displayName = 'SurveyActionsCell';
220
+
221
+ // ─────────────────────────────────────────────────────────────────────────────
222
+ // 6-9. Response table cells
223
+ // ─────────────────────────────────────────────────────────────────────────────
224
+
225
+ const NPS_CAT: Record<string, string> = {
226
+ promoter: 'bg-[color:color-mix(in_srgb,var(--th-success)_10%,transparent)] text-[color:var(--th-success)]',
227
+ passive: 'bg-[color:color-mix(in_srgb,var(--th-warning-soft)_10%,transparent)] text-[color:var(--th-warning-soft)]',
228
+ detractor: 'bg-[color:color-mix(in_srgb,var(--th-danger-soft)_10%,transparent)] text-[color:var(--th-danger-soft)]',
229
+ };
230
+
231
+ const ResponseUserCell = memo(({ row }: CellProps) => {
232
+ const x = asResponse(row);
233
+ return (
234
+ <div className="flex items-center gap-2.5 min-w-0">
235
+ <div className="w-8 h-8 rounded-full bg-[#7c3aed]/20 flex items-center justify-center shrink-0">
236
+ <Icon icon="User" size={14} className="text-[color:var(--th-accent-soft)]" />
237
+ </div>
238
+ <span className="text-[12px] font-mono text-[color:var(--th-text-2)] truncate">{str(x.userId)}</span>
239
+ </div>
240
+ );
241
+ });
242
+ ResponseUserCell.displayName = 'ResponseUserCell';
243
+
244
+ const ResponseNpsCategoryCell = memo(({ row }: CellProps) => {
245
+ const cat = str(asResponse(row).npsCategory);
246
+ if (!cat) return <span className="text-[12px] text-[color:var(--th-text-3)]">—</span>;
247
+ return (
248
+ <span className={`text-[10px] px-2 py-0.5 rounded font-medium capitalize ${NPS_CAT[cat] ?? 'bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] text-[color:var(--th-text-3)]'}`}>
249
+ {cat}
250
+ </span>
251
+ );
252
+ });
253
+ ResponseNpsCategoryCell.displayName = 'ResponseNpsCategoryCell';
254
+
255
+ const ResponseRatingCell = memo(({ row }: CellProps) => {
256
+ const rating = asResponse(row).rating;
257
+ if (rating == null) return <span className="text-[12px] text-[color:var(--th-text-3)]">—</span>;
258
+ return (
259
+ <div className="flex items-center gap-0.5">
260
+ {Array.from({ length: 5 }, (_, i) => (
261
+ <Icon
262
+ key={i}
263
+ icon="Star"
264
+ size={11}
265
+ className={i < rating ? 'text-[color:var(--th-warning-soft)] fill-[color:var(--th-warning-soft)]' : 'text-[color:color-mix(in_srgb,var(--th-text-3)_20%,transparent)]'}
266
+ />
267
+ ))}
268
+ </div>
269
+ );
270
+ });
271
+ ResponseRatingCell.displayName = 'ResponseRatingCell';
272
+
273
+ const ResponseTextCell = memo(({ row }: CellProps) => {
274
+ const t = str(asResponse(row).responseText);
275
+ return t ? (
276
+ <span className="block max-w-[360px] truncate text-[12px] text-[color:var(--th-text-1)]" title={t}>{t}</span>
277
+ ) : (
278
+ <span className="text-[12px] text-[color:var(--th-text-3)]">—</span>
279
+ );
280
+ });
281
+ ResponseTextCell.displayName = 'ResponseTextCell';
282
+
283
+ // ─────────────────────────────────────────────────────────────────────────────
284
+ // 10-12. Survey Analytics table cells
285
+ // ─────────────────────────────────────────────────────────────────────────────
286
+
287
+ const AnalyticsSurveyCell = memo(({ row }: CellProps) => (
288
+ <div className="flex items-center gap-2.5 min-w-0">
289
+ <div className="w-8 h-8 rounded-lg bg-[#7c3aed]/15 flex items-center justify-center shrink-0">
290
+ <Icon icon="BarChart3" size={14} className="text-[color:var(--th-accent-soft)]" />
291
+ </div>
292
+ <span className="text-[13px] font-medium text-white truncate max-w-[260px]">
293
+ {str(asAnalytics(row).surveyName)}
294
+ </span>
295
+ </div>
296
+ ));
297
+ AnalyticsSurveyCell.displayName = 'AnalyticsSurveyCell';
298
+
299
+ const AnalyticsCompletionCell = memo(({ row }: CellProps) => {
300
+ const pct = Math.min(100, Math.max(0, num(asAnalytics(row).completionRate)));
301
+ return (
302
+ <div className="w-28">
303
+ <div className="mb-1 text-[12px] font-mono tabular-nums text-[color:var(--th-text-1)]">{pct}%</div>
304
+ <div className="h-1.5 rounded-full bg-[color:color-mix(in_srgb,var(--th-ov-base)_5%,transparent)] overflow-hidden">
305
+ <div
306
+ className={`h-full rounded-full ${pct >= 80 ? 'bg-[#4edea3]' : pct >= 60 ? 'bg-[#ffcc6b]' : 'bg-[#ffb4ab]'}`}
307
+ style={{ width: `${pct}%` }}
308
+ />
309
+ </div>
310
+ </div>
311
+ );
312
+ });
313
+ AnalyticsCompletionCell.displayName = 'AnalyticsCompletionCell';
314
+
315
+ const AnalyticsRatingCell = memo(({ row }: CellProps) => {
316
+ const r = num(asAnalytics(row).averageRating);
317
+ return (
318
+ <div className="flex items-center gap-1.5">
319
+ <Icon icon="Star" size={12} className="text-[color:var(--th-warning-soft)] fill-[color:var(--th-warning-soft)]" />
320
+ <span className="text-[12px] font-mono tabular-nums text-[color:var(--th-text-1)]">{r.toFixed(1)}</span>
321
+ </div>
322
+ );
323
+ });
324
+ AnalyticsRatingCell.displayName = 'AnalyticsRatingCell';
325
+
326
+ // ─────────────────────────────────────────────────────────────────────────────
327
+ // Registration
328
+ // ─────────────────────────────────────────────────────────────────────────────
329
+
330
+ /**
331
+ * Registers the survey cells.
332
+ *
333
+ * @returns The `CellRegistration[]` result.
334
+ */
335
+ export default function registerSurveyCells(): CellRegistration[] {
336
+ return [
337
+ {
338
+ type: 'surveyStatus',
339
+ module: 'Surveys',
340
+ component: SurveyStatusCell,
341
+ },
342
+ {
343
+ type: 'surveyName',
344
+ module: 'Surveys',
345
+ component: SurveyNameCell,
346
+ },
347
+ {
348
+ type: 'responseProgress',
349
+ module: 'Surveys',
350
+ component: ResponseProgressCell,
351
+ },
352
+ {
353
+ type: 'npsScore',
354
+ module: 'Surveys',
355
+ component: NpsScoreCell,
356
+ },
357
+ {
358
+ type: 'surveyActions',
359
+ module: 'Surveys',
360
+ component: SurveyActionsCell,
361
+ },
362
+ { type: 'responseUser', module: 'Surveys', component: ResponseUserCell },
363
+ { type: 'responseNpsCategory', module: 'Surveys', component: ResponseNpsCategoryCell },
364
+ { type: 'responseRating', module: 'Surveys', component: ResponseRatingCell },
365
+ { type: 'responseText', module: 'Surveys', component: ResponseTextCell },
366
+ { type: 'analyticsSurvey', module: 'Surveys', component: AnalyticsSurveyCell },
367
+ { type: 'analyticsCompletion', module: 'Surveys', component: AnalyticsCompletionCell },
368
+ { type: 'analyticsRating', module: 'Surveys', component: AnalyticsRatingCell },
369
+ ];
370
+ }
@@ -0,0 +1,3 @@
1
+ /* Single seam for the shared Card used across modules (same one Queue uses).
2
+ If Card is later promoted to '@/shared/components/ui', change ONLY this line. */
3
+ export { Card } from '@/modules/queue/components/ui';
@@ -0,0 +1,37 @@
1
+ import { useInfiniteQuery } from '@tanstack/react-query';
2
+ import { useMemo } from 'react';
3
+ import { surveysApi } from '../services/api/surveys.api';
4
+ import type { PagedResponse, SurveyResponseItem } from '../types/survey.types';
5
+
6
+ /** Cursor-paged survey responses, flattened for the DataTable. */
7
+ export function useSurveyResponses(pageSize = 50) {
8
+ const query = useInfiniteQuery({
9
+ queryKey: ['survey-responses'],
10
+ queryFn: ({ pageParam }): Promise<PagedResponse<SurveyResponseItem>> =>
11
+ surveysApi.getResponses({ cursor: pageParam, pageSize }),
12
+ getNextPageParam: (last) => (last?.hasMore ? last.nextCursor ?? undefined : undefined),
13
+ initialPageParam: undefined as string | undefined,
14
+ staleTime: 30_000,
15
+ });
16
+
17
+ const items = useMemo(
18
+ () =>
19
+ (query.data?.pages ?? [])
20
+ .flatMap((p) => (Array.isArray(p?.items) ? p.items : []))
21
+ .filter((r) => Boolean(r?.id)),
22
+ [query.data]
23
+ );
24
+
25
+ const totalCount = query.data?.pages[0]?.totalCount ?? items.length;
26
+
27
+ return {
28
+ items,
29
+ totalCount,
30
+ isLoading: query.isLoading,
31
+ isError: query.isError,
32
+ hasMore: query.hasNextPage ?? false,
33
+ loadMore: () => {
34
+ if (query.hasNextPage && !query.isFetchingNextPage) query.fetchNextPage();
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,77 @@
1
+ // src/features/surveys/hooks/useTableConfig.ts
2
+ import { useQuery } from '@tanstack/react-query';
3
+ import axios from 'axios';
4
+ import type { TableConfigDto } from '../types/survey.types';
5
+
6
+ const BASE = import.meta.env.VITE_API_URL;
7
+
8
+ const getHeaders = () => ({
9
+ Authorization: `Bearer ${localStorage.getItem('zelisy_access_token')}`,
10
+ 'X-Organization-Id': localStorage.getItem('zelisy_org_id') ?? '',
11
+ });
12
+
13
+ /**
14
+ * Custom hook for table config.
15
+ *
16
+ * @param tableName - The table name.
17
+ * @returns The hook's state and actions.
18
+ */
19
+ export function useTableConfig<T = any>(tableName: string) {
20
+ const { data, isLoading, isError } = useQuery({
21
+ queryKey: ['table-config', tableName],
22
+ queryFn: async () => {
23
+ const res = await axios.get<TableConfigDto>(
24
+ `${BASE}/tables/${tableName}/config`,
25
+ { headers: getHeaders() }
26
+ );
27
+ return res.data; // ← critical: unwrap AxiosResponse
28
+ },
29
+ staleTime: 5 * 60_000,
30
+ gcTime: 10 * 60_000,
31
+ retry: 2,
32
+ });
33
+
34
+ const columns = (data?.columns ?? []).map((col) => ({
35
+ key: col.key as keyof T & string,
36
+ label: col.label,
37
+ cellType: col.cellType ?? undefined,
38
+ align: col.align ?? 'left',
39
+ width: col.width ?? undefined,
40
+ minWidth: col.minWidth ?? undefined,
41
+ maxWidth: col.maxWidth ?? undefined,
42
+ sortable: col.sortable,
43
+ hidden: col.hidden ?? false,
44
+ hideBelow: col.hideBelow ?? undefined,
45
+ className: col.className ?? undefined,
46
+ toggleable: col.toggleable ?? true,
47
+ }));
48
+
49
+ const tabs = (data?.tabs ?? []).map((t) => ({
50
+ key: t.key,
51
+ label: t.label,
52
+ count: t.count,
53
+ icon: t.icon,
54
+ }));
55
+
56
+ const controls = (data?.controls ?? []).map((c) => ({
57
+ action: c.action,
58
+ label: c.label,
59
+ icon: c.icon,
60
+ variant: c.variant,
61
+ showOnSelection: c.showOnSelection ?? false,
62
+ disabled: c.disabled ?? false,
63
+ onClick: undefined as (() => void) | undefined,
64
+ }));
65
+
66
+ return {
67
+ columns,
68
+ tabs,
69
+ controls,
70
+ defaultSortBy: data?.defaultSortBy ?? 'createdAt',
71
+ defaultSortOrder: (data?.defaultSortOrder ?? 'desc') as 'asc' | 'desc',
72
+ defaultPageSize: data?.defaultPageSize ?? 50,
73
+ tabFilterKey: data?.tabFilterKey ?? undefined,
74
+ isLoading,
75
+ isError,
76
+ };
77
+ }
@@ -0,0 +1,184 @@
1
+ import { useCallback, useMemo, useState } from 'react';
2
+ import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
3
+ import type { PagedResponse } from '../types/survey.types';
4
+
5
+ interface UseTableDataOptions<T> {
6
+ resource: string;
7
+ queryKey: (string | number | Record<string, unknown>)[];
8
+ fetchFn: (params: Record<string, unknown>) => Promise<PagedResponse<T> | T[]>;
9
+ pageSize?: number;
10
+ defaultSortBy?: string;
11
+ defaultSortOrder?: 'asc' | 'desc';
12
+ }
13
+
14
+ /**
15
+ * Custom hook for table data.
16
+ *
17
+ * @param options - Options that customize the behavior.
18
+ * @returns The hook's state and actions.
19
+ */
20
+ export function useTableData<T extends { id: string | number }>(
21
+ options: UseTableDataOptions<T>
22
+ ) {
23
+ const {
24
+ queryKey,
25
+ fetchFn,
26
+ pageSize = 50,
27
+ defaultSortBy = 'createdAt',
28
+ defaultSortOrder = 'desc',
29
+ } = options;
30
+
31
+ const queryClient = useQueryClient();
32
+
33
+ const [search, setSearch] = useState('');
34
+ const [sortBy, setSortBy] = useState(defaultSortBy);
35
+ const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>(defaultSortOrder);
36
+ const [activeTab, setActiveTab] = useState('All');
37
+ const [filters, setFilters] = useState<Record<string, string>>({});
38
+
39
+ const buildParams = useCallback(
40
+ (cursor?: string): Record<string, unknown> => ({
41
+ pageSize,
42
+ ...(cursor ? { cursor } : {}),
43
+ ...(search ? { search } : {}),
44
+ ...(sortBy ? { sortBy } : {}),
45
+ ...(sortOrder ? { sortOrder } : {}),
46
+ ...(activeTab && activeTab !== 'All' ? { tab: activeTab } : {}),
47
+ ...filters,
48
+ }),
49
+ [pageSize, search, sortBy, sortOrder, activeTab, filters]
50
+ );
51
+
52
+ const {
53
+ data,
54
+ isLoading,
55
+ isFetchingNextPage,
56
+ isRefetching,
57
+ isError,
58
+ fetchNextPage,
59
+ hasNextPage,
60
+ refetch,
61
+ } = useInfiniteQuery({
62
+ queryKey: [...queryKey, search, sortBy, sortOrder, activeTab, filters],
63
+ queryFn: async ({ pageParam }) => {
64
+ const result = await fetchFn(buildParams(pageParam as string | undefined));
65
+
66
+ if (Array.isArray(result)) {
67
+ return {
68
+ items: result,
69
+ totalCount: result.length,
70
+ pageSize,
71
+ hasMore: false,
72
+ nextCursor: null,
73
+ } as PagedResponse<T>;
74
+ }
75
+
76
+ return result;
77
+ },
78
+ getNextPageParam: (lastPage: PagedResponse<T>) =>
79
+ lastPage.hasMore ? lastPage.nextCursor ?? undefined : undefined,
80
+ initialPageParam: undefined as string | undefined,
81
+ staleTime: 30_000,
82
+ });
83
+
84
+ const items = useMemo<T[]>(
85
+ () => data?.pages.flatMap((p) => p.items) ?? [],
86
+ [data]
87
+ );
88
+
89
+ const totalCount = data?.pages[0]?.totalCount ?? 0;
90
+ const hasMore = hasNextPage ?? false;
91
+
92
+ const loadMore = useCallback(() => {
93
+ if (hasMore && !isFetchingNextPage) {
94
+ fetchNextPage();
95
+ }
96
+ }, [hasMore, isFetchingNextPage, fetchNextPage]);
97
+
98
+ const handleSort = useCallback((key: string, order: 'asc' | 'desc') => {
99
+ setSortBy(key);
100
+ setSortOrder(order);
101
+ }, []);
102
+
103
+ const handleTabChange = useCallback((tab: string) => {
104
+ setActiveTab(tab);
105
+ }, []);
106
+
107
+ const updateFilter = useCallback((key: string, value: string) => {
108
+ setFilters((prev) => ({ ...prev, [key]: value }));
109
+ }, []);
110
+
111
+ const optimisticUpdate = useCallback(
112
+ (id: string | number, updater: (item: T) => T) => {
113
+ queryClient.setQueriesData(
114
+ { queryKey: [...queryKey] },
115
+ (old: any) => {
116
+ if (!old) return old;
117
+ return {
118
+ ...old,
119
+ pages: old.pages.map((page: any) => ({
120
+ ...page,
121
+ items: page.items.map((item: T) =>
122
+ item.id === id ? updater(item) : item
123
+ ),
124
+ })),
125
+ };
126
+ }
127
+ );
128
+ },
129
+ [queryClient, queryKey]
130
+ );
131
+
132
+ const optimisticRemove = useCallback(
133
+ (id: string | number) => {
134
+ queryClient.setQueriesData(
135
+ { queryKey: [...queryKey] },
136
+ (old: any) => {
137
+ if (!old) return old;
138
+ return {
139
+ ...old,
140
+ pages: old.pages.map((page: any) => ({
141
+ ...page,
142
+ items: page.items.filter((item: T) => item.id !== id),
143
+ totalCount: Math.max(0, (page.totalCount ?? 1) - 1),
144
+ })),
145
+ };
146
+ }
147
+ );
148
+ },
149
+ [queryClient, queryKey]
150
+ );
151
+
152
+ return {
153
+ items,
154
+ totalCount,
155
+ hasMore,
156
+
157
+ isLoading,
158
+ isFetchingNextPage,
159
+ isRefetching,
160
+ isError,
161
+ refetch,
162
+
163
+ search,
164
+ setSearch,
165
+
166
+ sortBy,
167
+ sortOrder,
168
+ setSortBy,
169
+ setSortOrder,
170
+ handleSort,
171
+
172
+ activeTab,
173
+ setActiveTab,
174
+ handleTabChange,
175
+
176
+ filters,
177
+ updateFilter,
178
+
179
+ loadMore,
180
+
181
+ optimisticUpdate,
182
+ optimisticRemove,
183
+ };
184
+ }