@appcorp/fusion-storybook 0.5.13 → 0.5.17

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 (52) hide show
  1. package/base-modules/class/context/use-class-module.d.ts +55 -0
  2. package/base-modules/class/context/use-class-module.js +421 -0
  3. package/base-modules/class/context.d.ts +27 -52
  4. package/base-modules/class/context.js +18 -415
  5. package/base-modules/class/filter.js +16 -6
  6. package/base-modules/class/form.js +19 -3
  7. package/base-modules/class/more-actions.js +48 -10
  8. package/base-modules/class/page.js +15 -5
  9. package/base-modules/class/validate.d.ts +2 -2
  10. package/base-modules/class/validate.js +7 -3
  11. package/base-modules/class/view.js +2 -4
  12. package/base-modules/discount-code/context/use-discount-code-module.d.ts +65 -0
  13. package/base-modules/discount-code/context/use-discount-code-module.js +402 -0
  14. package/base-modules/discount-code/context.d.ts +32 -80
  15. package/base-modules/discount-code/context.js +14 -430
  16. package/base-modules/discount-code/filter.d.ts +1 -10
  17. package/base-modules/discount-code/filter.js +34 -8
  18. package/base-modules/discount-code/form.js +9 -35
  19. package/base-modules/discount-code/page.js +39 -19
  20. package/base-modules/discount-code/validate.d.ts +2 -1
  21. package/base-modules/discount-code/validate.js +10 -3
  22. package/base-modules/discount-code/view.js +15 -4
  23. package/base-modules/enrollment/context.d.ts +6 -0
  24. package/base-modules/enrollment/context.js +69 -25
  25. package/base-modules/enrollment/date.d.ts +8 -0
  26. package/base-modules/enrollment/date.js +21 -0
  27. package/base-modules/enrollment/filter.js +1 -1
  28. package/base-modules/enrollment/form.js +55 -24
  29. package/base-modules/enrollment/more-actions.js +47 -10
  30. package/base-modules/enrollment/page.js +11 -14
  31. package/base-modules/enrollment/validate.d.ts +1 -0
  32. package/base-modules/enrollment/validate.js +3 -1
  33. package/base-modules/enrollment/view.js +11 -19
  34. package/base-modules/expense/context/expense-api-provider.js +22 -9
  35. package/base-modules/expense/context/shared.d.ts +35 -0
  36. package/base-modules/expense/context/shared.js +11 -3
  37. package/base-modules/expense/context/use-expense-module.d.ts +7 -1
  38. package/base-modules/expense/context/use-expense-module.js +58 -55
  39. package/base-modules/expense/filter.js +25 -57
  40. package/base-modules/expense/form.js +17 -74
  41. package/base-modules/expense/page.js +60 -29
  42. package/base-modules/expense/validate.d.ts +17 -11
  43. package/base-modules/expense/validate.js +35 -14
  44. package/constants.d.ts +1 -3
  45. package/constants.js +0 -2
  46. package/package.json +1 -1
  47. package/tsconfig.build.tsbuildinfo +1 -1
  48. package/utils/resolve-rbac-permissions.js +10 -6
  49. package/base-modules/discount-code/more-actions.d.ts +0 -9
  50. package/base-modules/discount-code/more-actions.js +0 -13
  51. package/base-modules/expense/more-actions.d.ts +0 -1
  52. package/base-modules/expense/more-actions.js +0 -265
@@ -1,38 +1,15 @@
1
1
  "use client";
2
2
  /**
3
- * Class Context
3
+ * Class Module — configuration + provider.
4
4
  *
5
- * Wires the generic module state (created by `createGenericModule`) to network
6
- * actions using `useModuleEntityV2`. Contains domain-specific handlers for
7
- * CRUD operations.
8
- *
9
- * Key responsibilities:
10
- * - Expose `useClassModule()` which UI components call for actions
11
- * - Keep module-specific `apiParams` and callbacks in one place
12
- * - Ensure cache invalidation and toast notifications on mutation
13
- *
14
- * Exported utilities:
15
- * - `ClassProvider` — provider component used by the page
16
- * - `CLASS_ACTION_TYPES` — action type constants (from factory)
17
- * - `CLASS_DRAWER` — drawer type constants
18
- * - `useClassModule()` — hook that returns state, dispatch, and handlers
5
+ * Business logic lives in `context/use-class-module.ts` and is re-exported
6
+ * here so components keep importing from `./context`.
19
7
  */
20
- import { useCallback, useEffect, useMemo, useRef } from "react";
21
- import { useTheme } from "next-themes";
22
- import { useTranslations } from "next-intl";
23
- import { isCreatedOrUpdated } from "@react-pakistan/util-functions/general/is-created-or-updated";
24
- import { validateForm } from "@react-pakistan/util-functions/general/validate-form";
25
- import { useModuleEntityV2, } from "@react-pakistan/util-functions/hooks/use-module-entity-v2";
26
- import { useDebounce } from "@react-pakistan/util-functions/hooks/use-debounce";
27
8
  import { createGenericModule } from "@react-pakistan/util-functions/factory/generic-module-factory";
28
9
  import { DRAWER_TYPES } from "@react-pakistan/util-functions/factory/generic-component-factory";
29
- import { generateThemeToast, TOAST_VARIANT, } from "@appcorp/shadcn/lib/toast-utils";
30
10
  import { pageLimit } from "./constants";
31
- import { CLASS_API_ROUTES } from "../../constants";
32
- import { classFormValidation } from "./validate";
33
- import { getCachedWorkspaceSync } from "../workspace/cache";
34
11
  // ============================================================================
35
- // 1.1 DRAWER TYPES
12
+ // DRAWER TYPES
36
13
  // ============================================================================
37
14
  export const CLASS_DRAWER = {
38
15
  FILTER_DRAWER: DRAWER_TYPES.FILTER_DRAWER,
@@ -40,6 +17,9 @@ export const CLASS_DRAWER = {
40
17
  MORE_ACTIONS_DRAWER: DRAWER_TYPES.MORE_ACTIONS_DRAWER,
41
18
  VIEW_DRAWER: DRAWER_TYPES.VIEW_DRAWER,
42
19
  };
20
+ // ============================================================================
21
+ // MODULE CONFIGURATION
22
+ // ============================================================================
43
23
  const classConfig = {
44
24
  name: "Class",
45
25
  displayName: "Class",
@@ -57,404 +37,27 @@ const classConfig = {
57
37
  drawer: null,
58
38
  errors: {},
59
39
  // Form State
40
+ campusId: null,
41
+ campus: undefined,
60
42
  code: "",
61
43
  description: "",
62
44
  enabled: true,
63
45
  id: "",
64
46
  name: "",
65
47
  schoolId: "",
66
- // Filter State
67
- filterEnabled: undefined,
48
+ // Staged filter state: the drawer edits `filter*`; Apply copies them to
49
+ // `appliedFilter*`, which is what the list request uses.
50
+ filterEnabled: true,
51
+ filterCampusId: undefined,
52
+ appliedFilterEnabled: true,
53
+ appliedFilterCampusId: undefined,
68
54
  },
69
55
  };
70
56
  // ============================================================================
71
- // 1.3 CREATE CLASS MODULE
57
+ // CREATE CLASS MODULE
72
58
  // ============================================================================
73
59
  export const { actionTypes: CLASS_ACTION_TYPES, config: classModuleConfig, initialState: initialClassState, Provider: ClassProvider, reducer: classReducer, useContext: useClassContext, } = createGenericModule(classConfig);
74
60
  // ============================================================================
75
- // 1.4 ENHANCED CLASS HOOK WITH API INTEGRATION
61
+ // EXPORT ENHANCED HOOK
76
62
  // ============================================================================
77
- export const useClassModule = () => {
78
- var _a;
79
- // ============================================================================
80
- // 1.4.1 STATE & CORE HOOKS
81
- // ============================================================================
82
- const context = useClassContext();
83
- const { dispatch } = context;
84
- const state = context.state;
85
- const t = useTranslations("class");
86
- const { theme } = useTheme();
87
- const workspace = getCachedWorkspaceSync();
88
- const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
89
- const listFetchNowRef = useRef(null);
90
- const debouncedQuery = useDebounce(state.searchQuery, 800);
91
- // ============================================================================
92
- // 1.4.2 API PARAMETERS
93
- // ============================================================================
94
- const listParams = useMemo(() => (Object.assign(Object.assign({ currentPage: state.currentPage, pageLimit: state.pageLimit, schoolId }, (debouncedQuery ? { searchQuery: debouncedQuery } : {})), (state.filterEnabled !== undefined
95
- ? { filterEnabled: String(state.filterEnabled) }
96
- : {}))), [
97
- state.currentPage,
98
- state.filterEnabled,
99
- state.pageLimit,
100
- debouncedQuery,
101
- schoolId,
102
- ]);
103
- const updateParams = useMemo(() => ({
104
- code: state.code,
105
- description: state.description,
106
- enabled: state.enabled,
107
- id: state.id,
108
- name: state.name,
109
- schoolId: state.schoolId || schoolId,
110
- }), [state, schoolId]);
111
- const byIdParams = useMemo(() => ({ id: state.id }), [state.id]);
112
- const deleteParams = useMemo(() => ({ id: state.id }), [state.id]);
113
- // ============================================================================
114
- // 1.4.3 UTILITIES
115
- // ============================================================================
116
- const showToast = useCallback((description, variant) => {
117
- generateThemeToast({
118
- description,
119
- theme: theme,
120
- variant,
121
- });
122
- }, [theme]);
123
- const resetFormAndCloseDrawer = useCallback(() => {
124
- dispatch({ type: CLASS_ACTION_TYPES.RESET_FORM });
125
- dispatch({
126
- type: CLASS_ACTION_TYPES.SET_ERRORS,
127
- payload: { errors: {} },
128
- });
129
- dispatch({
130
- type: CLASS_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
131
- payload: { disabled: false },
132
- });
133
- dispatch({
134
- type: CLASS_ACTION_TYPES.SET_DRAWER,
135
- payload: { drawer: null },
136
- });
137
- }, [dispatch]);
138
- // ============================================================================
139
- // 1.4.4 API CALLBACKS
140
- // ============================================================================
141
- const listCallback = useCallback(({ data, error }) => {
142
- var _a, _b;
143
- if (error) {
144
- showToast(t("messagesFetchFailed"), TOAST_VARIANT.ERROR);
145
- return;
146
- }
147
- if (data) {
148
- const response = data;
149
- dispatch({
150
- type: CLASS_ACTION_TYPES.SET_ITEMS,
151
- payload: { items: (_a = response.items) !== null && _a !== void 0 ? _a : [], count: (_b = response.count) !== null && _b !== void 0 ? _b : 0 },
152
- });
153
- }
154
- }, [dispatch, showToast, t]);
155
- const updateCallback = useCallback(({ data, error }) => {
156
- var _a;
157
- if (error) {
158
- showToast(t("messagesUpdateFailed"), TOAST_VARIANT.ERROR);
159
- return;
160
- }
161
- if (data) {
162
- const isCreated = isCreatedOrUpdated(data);
163
- showToast(isCreated ? t("messagesCreateSuccess") : t("messagesSaveSuccess"), TOAST_VARIANT.SUCCESS);
164
- resetFormAndCloseDrawer();
165
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
166
- }
167
- }, [resetFormAndCloseDrawer, showToast, t]);
168
- const byIdCallback = useCallback(({ data, error }) => {
169
- if (error) {
170
- showToast(t("messagesDetailsFetchFailed"), TOAST_VARIANT.ERROR);
171
- return;
172
- }
173
- if (data) {
174
- dispatch({
175
- type: CLASS_ACTION_TYPES.SET_FORM_DATA,
176
- payload: { form: Object.assign(Object.assign({}, data), { filterEnabled: undefined }) },
177
- });
178
- }
179
- }, [dispatch, showToast, t]);
180
- const deleteCallback = useCallback(({ data, error }) => {
181
- var _a;
182
- if (error) {
183
- showToast(t("messagesDeleteFailed"), TOAST_VARIANT.ERROR);
184
- return;
185
- }
186
- if (data) {
187
- showToast(t("messagesDeleteSuccess"), TOAST_VARIANT.SUCCESS);
188
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
189
- }
190
- }, [showToast, t]);
191
- // ============================================================================
192
- // 1.4.5 API HOOKS
193
- // ============================================================================
194
- const { byIdFetchNow, byIdLoading, deleteFetchNow, deleteLoading, listFetchNow, listLoading, updateFetchNow, updateLoading, } = useModuleEntityV2({
195
- byIdCallback,
196
- byIdParams,
197
- deleteCallback,
198
- deleteParams,
199
- listCallback,
200
- listParams,
201
- listUrl: CLASS_API_ROUTES.UNIT,
202
- searchQuery: debouncedQuery,
203
- unitByIdUrl: CLASS_API_ROUTES.UNIT,
204
- unitUrl: CLASS_API_ROUTES.UNIT,
205
- updateCallback,
206
- updateParams,
207
- headers: {
208
- "Content-Type": "application/json",
209
- // "x-api-token": process.env.NEXT_PUBLIC_API_KEY!,
210
- },
211
- });
212
- // ============================================================================
213
- // 1.4.6 HANDLERS
214
- // ============================================================================
215
- const handleChange = useCallback((field, value) => {
216
- let formatted = value;
217
- if (field === "code" && typeof value === "string") {
218
- formatted = value.toUpperCase();
219
- }
220
- dispatch({
221
- type: CLASS_ACTION_TYPES.SET_ERRORS,
222
- payload: { errors: {} },
223
- });
224
- dispatch({
225
- type: CLASS_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
226
- payload: { disabled: false },
227
- });
228
- dispatch({
229
- type: CLASS_ACTION_TYPES.SET_INPUT_FIELD,
230
- payload: { key: field, value: formatted !== null && formatted !== void 0 ? formatted : value },
231
- });
232
- }, [dispatch]);
233
- const closeDrawer = useCallback(() => {
234
- resetFormAndCloseDrawer();
235
- }, [resetFormAndCloseDrawer]);
236
- const handleCreate = useCallback(() => {
237
- dispatch({
238
- type: CLASS_ACTION_TYPES.SET_DRAWER,
239
- payload: { drawer: CLASS_DRAWER.FORM_DRAWER },
240
- });
241
- }, [dispatch]);
242
- const handleView = useCallback((row) => {
243
- byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
244
- dispatch({
245
- type: CLASS_ACTION_TYPES.SET_DRAWER,
246
- payload: { drawer: CLASS_DRAWER.VIEW_DRAWER },
247
- });
248
- }, [byIdFetchNow, dispatch]);
249
- const handleEdit = useCallback((row) => {
250
- byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
251
- dispatch({
252
- type: CLASS_ACTION_TYPES.SET_DRAWER,
253
- payload: { drawer: CLASS_DRAWER.FORM_DRAWER },
254
- });
255
- }, [byIdFetchNow, dispatch]);
256
- const handleDelete = useCallback((row) => {
257
- if (!confirm(t("messagesDeleteConfirmation")))
258
- return;
259
- deleteFetchNow === null || deleteFetchNow === void 0 ? void 0 : deleteFetchNow(undefined, {
260
- body: JSON.stringify({ id: row === null || row === void 0 ? void 0 : row.id }),
261
- });
262
- }, [deleteFetchNow, t]);
263
- const handleFilters = useCallback(() => {
264
- dispatch({
265
- type: CLASS_ACTION_TYPES.SET_DRAWER,
266
- payload: { drawer: CLASS_DRAWER.FILTER_DRAWER },
267
- });
268
- }, [dispatch]);
269
- const handleMoreActions = useCallback(() => {
270
- dispatch({
271
- type: CLASS_ACTION_TYPES.SET_DRAWER,
272
- payload: { drawer: CLASS_DRAWER.MORE_ACTIONS_DRAWER },
273
- });
274
- }, [dispatch]);
275
- const handlePageChange = useCallback((pageOrEvent) => {
276
- // The factory passes handlePageChange directly as the Next button's onClick
277
- // handler (receiving a MouseEvent), but wraps Previous as () => handlePageChange(currentPage - 1).
278
- // We detect which case we're in: a valid number means an explicit page target
279
- // (Previous path); anything else means "advance to next page".
280
- const page = typeof pageOrEvent === "number" && !isNaN(pageOrEvent)
281
- ? pageOrEvent
282
- : state.currentPage + 1;
283
- dispatch({
284
- type: CLASS_ACTION_TYPES.SET_CURRENT_PAGE,
285
- payload: { currentPage: page },
286
- });
287
- }, [dispatch, state.currentPage]);
288
- const handlePageLimitChange = useCallback((k, value) => {
289
- const val = Object.assign({}, value);
290
- dispatch({
291
- type: CLASS_ACTION_TYPES.SET_PAGE_LIMIT,
292
- payload: { pageLimit: Number(val.option) },
293
- });
294
- dispatch({
295
- type: CLASS_ACTION_TYPES.SET_CURRENT_PAGE,
296
- payload: { currentPage: 1 },
297
- });
298
- }, [dispatch]);
299
- const handleSearch = useCallback((query) => {
300
- dispatch({
301
- type: CLASS_ACTION_TYPES.SET_SEARCH_QUERY,
302
- payload: { searchQuery: query },
303
- });
304
- }, [dispatch]);
305
- const clearSearch = useCallback(() => {
306
- dispatch({
307
- type: CLASS_ACTION_TYPES.SET_SEARCH_QUERY,
308
- payload: { searchQuery: "" },
309
- });
310
- }, [dispatch]);
311
- const handleAvatar = useCallback((files) => {
312
- if (!files || files.length === 0)
313
- return;
314
- const file = files[0];
315
- const blob = new Blob([file], { type: file.type });
316
- const url = URL.createObjectURL(blob);
317
- dispatch({
318
- type: CLASS_ACTION_TYPES.SET_INPUT_FIELD,
319
- payload: { key: "avatar", value: url },
320
- });
321
- }, [dispatch]);
322
- const applyFilters = useCallback(() => {
323
- dispatch({
324
- type: CLASS_ACTION_TYPES.SET_CURRENT_PAGE,
325
- payload: { currentPage: 1 },
326
- });
327
- closeDrawer();
328
- }, [dispatch, closeDrawer]);
329
- const clearFilters = useCallback(() => {
330
- dispatch({
331
- type: CLASS_ACTION_TYPES.SET_FILTERS,
332
- payload: { filters: { filterEnabled: undefined } },
333
- });
334
- dispatch({
335
- type: CLASS_ACTION_TYPES.SET_CURRENT_PAGE,
336
- payload: { currentPage: 1 },
337
- });
338
- }, [dispatch]);
339
- const toggleStatus = useCallback((row) => {
340
- updateFetchNow(undefined, {
341
- body: JSON.stringify(Object.assign(Object.assign({}, row), { enabled: !(row === null || row === void 0 ? void 0 : row.enabled) })),
342
- });
343
- }, [updateFetchNow]);
344
- // ============================================================================
345
- // 1.4.7 SUBMIT
346
- // ============================================================================
347
- const handleSubmit = useCallback(() => {
348
- dispatch({
349
- type: CLASS_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
350
- payload: { disabled: true },
351
- });
352
- validateForm({
353
- params: updateParams,
354
- schema: classFormValidation,
355
- successCallback: () => {
356
- updateFetchNow(undefined, {
357
- body: JSON.stringify(updateParams),
358
- });
359
- },
360
- errorCallback: (errors) => {
361
- dispatch({
362
- type: CLASS_ACTION_TYPES.SET_ERRORS,
363
- payload: { errors },
364
- });
365
- dispatch({
366
- type: CLASS_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
367
- payload: { disabled: false },
368
- });
369
- showToast(t("messagesFormErrors"), TOAST_VARIANT.ERROR);
370
- },
371
- });
372
- }, [dispatch, updateParams, t, showToast, updateFetchNow]);
373
- // ============================================================================
374
- // 1.4.8 HEADER & ROW ACTIONS
375
- // ============================================================================
376
- const headerActions = useMemo(() => [
377
- {
378
- enabled: true,
379
- handleOnClick: handleMoreActions,
380
- label: t("actionsButtonMoreActions"),
381
- order: 0,
382
- },
383
- {
384
- enabled: true,
385
- handleOnClick: handleFilters,
386
- label: t("actionsButtonFilters"),
387
- order: 1,
388
- },
389
- {
390
- enabled: true,
391
- handleOnClick: handleCreate,
392
- label: t("actionsButtonAdd"),
393
- order: 2,
394
- },
395
- ], [handleCreate, handleFilters, handleMoreActions, t]);
396
- const rowActions = useMemo(() => [
397
- {
398
- enabled: true,
399
- handleOnClick: handleView,
400
- label: t("actionsButtonView"),
401
- order: 1,
402
- },
403
- {
404
- enabled: (row) => (row === null || row === void 0 ? void 0 : row.enabled) === true,
405
- handleOnClick: handleEdit,
406
- label: t("actionsButtonEdit"),
407
- order: 2,
408
- },
409
- {
410
- enabled: (row) => (row === null || row === void 0 ? void 0 : row.enabled) === false,
411
- handleOnClick: handleDelete,
412
- label: t("actionsButtonDelete"),
413
- order: 3,
414
- variant: "destructive",
415
- },
416
- {
417
- enabled: false,
418
- handleOnClick: toggleStatus,
419
- label: t("actionsButtonToggleStatus"),
420
- order: 4,
421
- },
422
- ], [handleDelete, handleEdit, handleView, t, toggleStatus]);
423
- // ============================================================================
424
- // 1.4.9 EFFECTS
425
- // ============================================================================
426
- useEffect(() => {
427
- listFetchNowRef.current = listFetchNow;
428
- }, [listFetchNow]);
429
- useEffect(() => {
430
- var _a;
431
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
432
- }, [listParams]);
433
- // ============================================================================
434
- // 1.4.10 RETURN
435
- // ============================================================================
436
- return Object.assign(Object.assign({}, context), { applyFilters,
437
- byIdLoading,
438
- clearFilters,
439
- clearSearch,
440
- closeDrawer,
441
- deleteLoading,
442
- handleAvatar,
443
- handleChange,
444
- handleCreate,
445
- handleDelete,
446
- handleEdit,
447
- handleFilters,
448
- handleMoreActions,
449
- handlePageChange,
450
- handlePageLimitChange,
451
- handleSearch,
452
- handleSubmit,
453
- handleView,
454
- headerActions,
455
- listFetchNow,
456
- listLoading,
457
- rowActions,
458
- toggleStatus,
459
- updateLoading });
460
- };
63
+ export { useClassModule } from "./context/use-class-module";
@@ -1,28 +1,38 @@
1
1
  "use client";
2
- import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  /**
4
4
  * Class Filter Component
5
5
  *
6
- * Renders filter controls for the class list view.
6
+ * Filter drawer: record state + campus. Values are staged and only applied
7
+ * when the drawer's "Apply Filters" button is pressed.
7
8
  */
9
+ import { useMemo } from "react";
10
+ import { EnhancedCombobox } from "@appcorp/shadcn/components/enhanced-combobox";
8
11
  import { EnhancedRadio } from "@appcorp/shadcn/components/enhanced-radio";
9
12
  import { useClassModule } from "./context";
10
13
  import { useTranslations } from "next-intl";
11
14
  export const ClassFilter = () => {
12
- const { state, handleChange } = useClassModule();
13
- const { filterEnabled } = state;
15
+ const { state, handleChange, campuses } = useClassModule();
16
+ const { filterCampusId, filterEnabled } = state;
14
17
  const t = useTranslations("class");
15
18
  const filterEnabledValue = filterEnabled === undefined
16
19
  ? "undefined"
17
20
  : filterEnabled
18
21
  ? "true"
19
22
  : "false";
20
- return (_jsx("div", { className: "space-y-4", children: _jsx("div", { className: "grid grid-cols-1 gap-4", children: _jsx(EnhancedRadio, { label: t("filterOptionEnabled"), name: "filterEnabled", value: filterEnabledValue, options: [
23
+ const campusOptions = useMemo(() => [
24
+ { value: "", label: t("filterAllCampuses") },
25
+ ...campuses.map((campus) => ({
26
+ value: campus.id,
27
+ label: `${campus.name} (${campus.code})`,
28
+ })),
29
+ ], [campuses, t]);
30
+ return (_jsxs("div", { className: "space-y-4", children: [_jsx(EnhancedCombobox, { emptyText: t("filterAllCampuses"), id: "filterCampusId", info: t("filterCampusInfo"), label: t("filterCampusLabel"), onValueChange: (value) => handleChange("filterCampusId", value || undefined), options: campusOptions, placeholder: t("filterCampusPlaceholder"), searchPlaceholder: t("filterCampusPlaceholder"), value: filterCampusId !== null && filterCampusId !== void 0 ? filterCampusId : "" }), _jsx(EnhancedRadio, { label: t("filterRecordStateLabel"), name: "filterEnabled", value: filterEnabledValue, options: [
21
31
  { label: t("filterOptionAll"), value: "undefined" },
22
32
  { label: t("filterOptionEnabled"), value: "true" },
23
33
  { label: t("filterOptionDisabled"), value: "false" },
24
34
  ], onValueChange: (next) => {
25
35
  const parsed = next === "true" ? true : next === "false" ? false : undefined;
26
36
  handleChange("filterEnabled", parsed);
27
- } }) }) }));
37
+ } })] }));
28
38
  };
@@ -8,12 +8,28 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
8
8
  import { EnhancedInput } from "@appcorp/shadcn/components/enhanced-input";
9
9
  import { EnhancedTextarea } from "@appcorp/shadcn/components/enhanced-textarea";
10
10
  import { EnhancedCheckbox } from "@appcorp/shadcn/components/enhanced-checkbox";
11
+ import { useMemo } from "react";
12
+ import { EnhancedCombobox } from "@appcorp/shadcn/components/enhanced-combobox";
11
13
  import { useClassModule } from "./context";
12
14
  import { useTranslations } from "next-intl";
13
15
  import { getTranslatedError } from "../../utils/get-translated-error";
14
16
  export const ClassForm = () => {
15
- const { state, handleChange } = useClassModule();
16
- const { code, description, enabled, errors, name } = state;
17
+ const { state, handleChange, campuses } = useClassModule();
18
+ const { campus, campusId, code, description, enabled, errors, name } = state;
17
19
  const t = useTranslations("class");
18
- return (_jsx("div", { className: "space-y-4", children: _jsxs("div", { className: "grid grid-cols-1 gap-4", children: [_jsx(EnhancedInput, { error: getTranslatedError({ errors, key: "name", t }), id: "name", info: t("formClassNameInfo"), label: t("formClassNameLabel"), onChange: (e) => handleChange("name", e.target.value), placeholder: t("formClassNamePlaceholder"), required: true, value: name }), _jsx(EnhancedInput, { error: getTranslatedError({ errors, key: "code", t }), id: "code", info: t("formClassCodeInfo"), label: t("formClassCodeLabel"), onChange: (e) => handleChange("code", e.target.value), placeholder: t("formClassCodePlaceholder"), required: true, value: code }), _jsx(EnhancedTextarea, { error: getTranslatedError({ errors, key: "description", t }), id: "description", info: t("formDescriptionInfo"), label: t("formDescriptionLabel"), onChange: (e) => handleChange("description", e.target.value), placeholder: t("formDescriptionPlaceholder"), rows: 3, value: description || "" }), _jsx(EnhancedCheckbox, { label: t("formActiveClassLabel"), defaultChecked: enabled, onCheckedChange: (checked) => handleChange("enabled", checked), info: t("formActiveClassInfo") })] }) }));
20
+ const campusOptions = useMemo(() => {
21
+ const items = campuses.map((item) => ({
22
+ value: item.id,
23
+ label: `${item.name} (${item.code})`,
24
+ }));
25
+ // Keep the record's own campus selectable even if it is disabled.
26
+ if (campus && !items.some((item) => item.value === campus.id)) {
27
+ items.unshift({
28
+ value: campus.id,
29
+ label: `${campus.name} (${campus.code})`,
30
+ });
31
+ }
32
+ return [{ value: "", label: t("formNoCampusOption") }, ...items];
33
+ }, [campuses, campus, t]);
34
+ return (_jsx("div", { className: "space-y-4", children: _jsxs("div", { className: "grid grid-cols-1 gap-4", children: [_jsx(EnhancedInput, { error: getTranslatedError({ errors, key: "name", t }), id: "name", info: t("formClassNameInfo"), label: t("formClassNameLabel"), maxLength: 100, onChange: (e) => handleChange("name", e.target.value), placeholder: t("formClassNamePlaceholder"), required: true, value: name }), _jsx(EnhancedInput, { error: getTranslatedError({ errors, key: "code", t }), id: "code", info: t("formClassCodeInfo"), label: t("formClassCodeLabel"), maxLength: 20, onChange: (e) => handleChange("code", e.target.value), placeholder: t("formClassCodePlaceholder"), required: true, value: code }), _jsx(EnhancedTextarea, { error: getTranslatedError({ errors, key: "description", t }), id: "description", info: t("formDescriptionInfo"), label: t("formDescriptionLabel"), maxLength: 500, onChange: (e) => handleChange("description", e.target.value), placeholder: t("formDescriptionPlaceholder"), rows: 3, value: description || "" }), _jsx(EnhancedCombobox, { emptyText: t("formNoCampusOption"), id: "campusId", info: t("formCampusInfo"), label: t("formCampusLabel"), onValueChange: (value) => handleChange("campusId", value || null), options: campusOptions, placeholder: t("formCampusPlaceholder"), searchPlaceholder: t("formCampusPlaceholder"), value: campusId !== null && campusId !== void 0 ? campusId : "" }), _jsx(EnhancedCheckbox, { checked: enabled, id: "enabled", info: t("formActiveClassInfo"), label: t("formActiveClassLabel"), onCheckedChange: (checked) => handleChange("enabled", checked) })] }) }));
19
35
  };
@@ -10,18 +10,55 @@ import { pageLimit } from "./constants";
10
10
  import { CLASS_API_ROUTES } from "../../constants";
11
11
  import { CLASS_ACTION_TYPES, useClassContext } from "./context";
12
12
  import { useRef, useEffect, useCallback } from "react";
13
- const workspace = getCachedWorkspaceSync();
14
13
  const POLL_INTERVAL_MS = 2000;
15
14
  const POLL_TIMEOUT_MS = 300000;
16
- const handleGetAllRecords = async (schoolId, pageLimit) => {
17
- const response = await fetch(`${CLASS_API_ROUTES.UNIT}?pageLimit=${pageLimit}&currentPage=1&schoolId=${schoolId}`);
18
- const result = await response.json();
19
- const csv = await converter.json2csv(result.items || [], {});
15
+ const TEMPLATE_HEADERS = [
16
+ "id",
17
+ "code",
18
+ "name",
19
+ "description",
20
+ "campusId",
21
+ "enabled",
22
+ ];
23
+ /** The create template is header-only; the update template exports the rows. */
24
+ const CREATE_TEMPLATE_HEADERS = [
25
+ "code",
26
+ "name",
27
+ "description",
28
+ "campusId",
29
+ "enabled",
30
+ ];
31
+ const toCsvRow = (row) => {
32
+ var _a, _b, _c, _d, _e;
33
+ return ({
34
+ id: (_a = row.id) !== null && _a !== void 0 ? _a : "",
35
+ code: (_b = row.code) !== null && _b !== void 0 ? _b : "",
36
+ name: (_c = row.name) !== null && _c !== void 0 ? _c : "",
37
+ description: (_d = row.description) !== null && _d !== void 0 ? _d : "",
38
+ campusId: (_e = row.campusId) !== null && _e !== void 0 ? _e : "",
39
+ enabled: row.enabled === false ? "false" : "true",
40
+ });
41
+ };
42
+ const downloadCsv = async (csv, filename) => {
20
43
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
21
- await downloadFromUrl(blob, "class.csv");
44
+ await downloadFromUrl(blob, filename);
45
+ };
46
+ const downloadCreateTemplate = async () => {
47
+ await downloadCsv(CREATE_TEMPLATE_HEADERS.join(",") + "\n", "class-template.csv");
48
+ };
49
+ const downloadUpdateTemplate = async (schoolId) => {
50
+ var _a;
51
+ const response = await fetch(`${CLASS_API_ROUTES.UNIT}?pageLimit=1000&currentPage=1&schoolId=${schoolId}`);
52
+ const result = await response.json();
53
+ const rows = ((_a = result.items) !== null && _a !== void 0 ? _a : []).map((row) => toCsvRow(row));
54
+ const csv = await converter.json2csv(rows, {
55
+ keys: TEMPLATE_HEADERS,
56
+ });
57
+ await downloadCsv(csv, "class.csv");
22
58
  };
23
59
  async function submitBulkJob(csvData, method, signal) {
24
60
  var _a;
61
+ const workspace = getCachedWorkspaceSync();
25
62
  const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
26
63
  if (!schoolId)
27
64
  throw new Error("School ID not found");
@@ -82,7 +119,9 @@ t, errors) {
82
119
  return lines.join("\n");
83
120
  }
84
121
  export const ClassMoreActions = () => {
122
+ var _a;
85
123
  const t = useTranslations("class");
124
+ const workspace = getCachedWorkspaceSync();
86
125
  const { dispatch } = useClassContext();
87
126
  const abortRef = useRef(null);
88
127
  // Abort any in-flight polling on unmount
@@ -225,7 +264,7 @@ export const ClassMoreActions = () => {
225
264
  error: error instanceof Error ? error.message : t("unknownError"),
226
265
  }));
227
266
  }
228
- }, [dispatch, t]);
267
+ }, [dispatch, t, (_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id]);
229
268
  const handleBulkCreate = useCallback((files) => handleBulkFlow(files, "POST"), [handleBulkFlow]);
230
269
  const handleBulkUpdate = useCallback((files) => handleBulkFlow(files, "PUT"), [handleBulkFlow]);
231
270
  const create = [
@@ -233,8 +272,7 @@ export const ClassMoreActions = () => {
233
272
  id: "1",
234
273
  title: t("downloadEmptyCsvTemplate"),
235
274
  handleOnClick: async () => {
236
- var _a;
237
- await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1);
275
+ await downloadCreateTemplate();
238
276
  },
239
277
  },
240
278
  { id: "2", title: t("addYourDataToTheCsv") },
@@ -249,7 +287,7 @@ export const ClassMoreActions = () => {
249
287
  title: t("downloadPopulatedCsvTemplate"),
250
288
  handleOnClick: async () => {
251
289
  var _a;
252
- await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1000);
290
+ await downloadUpdateTemplate(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "");
253
291
  },
254
292
  },
255
293
  { id: "2", title: t("updateYourDataInTheCsv") },