@appcorp/fusion-storybook 0.5.19 → 0.5.23

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 (38) hide show
  1. package/base-modules/fee-structure/context/fee-structure-api-provider.js +48 -18
  2. package/base-modules/fee-structure/context/shared.d.ts +5 -0
  3. package/base-modules/fee-structure/context/shared.js +3 -0
  4. package/base-modules/fee-structure/context/use-fee-structure-module.d.ts +1 -0
  5. package/base-modules/fee-structure/context/use-fee-structure-module.js +35 -26
  6. package/base-modules/fee-structure/form.js +16 -48
  7. package/base-modules/fee-structure/more-actions.js +68 -14
  8. package/base-modules/fee-structure/page.js +52 -25
  9. package/base-modules/fee-structure/validate.d.ts +8 -1
  10. package/base-modules/fee-structure/validate.js +6 -1
  11. package/base-modules/fee-structure/view.js +20 -4
  12. package/base-modules/rbac/assign-permissions.js +5 -3
  13. package/base-modules/rbac/context.d.ts +8 -1
  14. package/base-modules/rbac/context.js +92 -65
  15. package/base-modules/rbac/page.js +6 -8
  16. package/base-modules/school/cache.js +0 -1
  17. package/base-modules/school/context.d.ts +0 -2
  18. package/base-modules/school/context.js +77 -18
  19. package/base-modules/school/drawer.js +1 -3
  20. package/base-modules/school/form.js +4 -23
  21. package/base-modules/school/page.js +2 -2
  22. package/base-modules/section/context.d.ts +6 -0
  23. package/base-modules/section/context.js +66 -34
  24. package/base-modules/section/form.js +2 -2
  25. package/base-modules/section/more-actions.js +71 -16
  26. package/base-modules/section/page.js +7 -3
  27. package/constants.d.ts +8 -2
  28. package/package.json +1 -1
  29. package/tsconfig.build.tsbuildinfo +1 -1
  30. package/utils/resolve-rbac-permissions.js +8 -4
  31. package/base-modules/rbac/filter.d.ts +0 -1
  32. package/base-modules/rbac/filter.js +0 -20
  33. package/base-modules/rbac/more-actions.d.ts +0 -1
  34. package/base-modules/rbac/more-actions.js +0 -12
  35. package/base-modules/school/filter.d.ts +0 -1
  36. package/base-modules/school/filter.js +0 -13
  37. package/base-modules/school/more-actions.d.ts +0 -1
  38. package/base-modules/school/more-actions.js +0 -13
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef } from "react";
3
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, } from "react";
4
4
  import { useTheme } from "next-themes";
5
5
  import { useTranslations } from "next-intl";
6
6
  import { isCreatedOrUpdated } from "@react-pakistan/util-functions/general/is-created-or-updated";
@@ -45,7 +45,20 @@ export const FeeStructureApiProvider = ({ children, }) => {
45
45
  });
46
46
  }, [theme]);
47
47
  const resetFormAndCloseDrawer = useCallback(() => {
48
+ // `RESET_FORM` restores the initial state, which would wipe the list
49
+ // filter; preserve it across form open/close.
50
+ const applied = state.appliedFilterEnabled;
51
+ const staged = state.filterEnabled;
48
52
  dispatch({ type: FEE_STRUCTURE_ACTION_TYPES.RESET_FORM });
53
+ dispatch({
54
+ type: FEE_STRUCTURE_ACTION_TYPES.SET_FILTERS,
55
+ payload: {
56
+ filters: {
57
+ appliedFilterEnabled: applied,
58
+ filterEnabled: staged,
59
+ },
60
+ },
61
+ });
49
62
  dispatch({
50
63
  type: FEE_STRUCTURE_ACTION_TYPES.SET_ERRORS,
51
64
  payload: { errors: {} },
@@ -58,36 +71,51 @@ export const FeeStructureApiProvider = ({ children, }) => {
58
71
  type: FEE_STRUCTURE_ACTION_TYPES.SET_DRAWER,
59
72
  payload: { drawer: null },
60
73
  });
61
- }, [dispatch]);
74
+ }, [dispatch, state.appliedFilterEnabled, state.filterEnabled]);
62
75
  // ==========================================================================
63
76
  // API PARAMETERS
64
77
  // ==========================================================================
65
- const listParams = useMemo(() => (Object.assign({ currentPage: state.currentPage, pageLimit: state.pageLimit, schoolId }, (debouncedQuery ? { searchQuery: debouncedQuery } : {}))), [state.currentPage, state.pageLimit, debouncedQuery, schoolId]);
66
- const updateParams = useMemo(() => (Object.assign(Object.assign(Object.assign({}, (state.id ? { id: state.id } : {})), (!state.id ? { schoolId } : {})), { amount: Number(state.amount), classId: state.classId || null, description: state.description || null, enabled: state.enabled, feeType: state.feeType, frequency: state.frequency || null, name: state.name })), [state, schoolId]);
67
- const byIdParams = useMemo(() => ({ id: state.id }), [state.id]);
68
- const deleteParams = useMemo(() => ({ id: state.id }), [state.id]);
78
+ const listParams = useMemo(() => (Object.assign(Object.assign({ currentPage: state.currentPage, pageLimit: state.pageLimit, schoolId }, (state.appliedFilterEnabled !== undefined
79
+ ? { filterEnabled: String(state.appliedFilterEnabled) }
80
+ : {})), (debouncedQuery ? { searchQuery: debouncedQuery } : {}))), [
81
+ state.appliedFilterEnabled,
82
+ state.currentPage,
83
+ state.pageLimit,
84
+ debouncedQuery,
85
+ schoolId,
86
+ ]);
87
+ const updateParams = useMemo(() => (Object.assign(Object.assign({}, (state.id ? { id: state.id } : {})), {
88
+ // Always sent: the API verifies the record belongs to this school.
89
+ schoolId, amount: Number(state.amount), classId: state.classId || null, description: state.description || null, enabled: state.enabled, feeType: state.feeType, frequency: state.frequency || null, name: state.name })), [state, schoolId]);
90
+ const byIdParams = useMemo(() => ({ id: state.id, schoolId }), [state.id, schoolId]);
91
+ const deleteParams = useMemo(() => ({ id: state.id, schoolId }), [state.id, schoolId]);
69
92
  // ==========================================================================
70
93
  // API CALLBACKS
71
94
  // ==========================================================================
95
+ const apiError = (data) => data === null || data === void 0 ? void 0 : data.error;
72
96
  const listCallback = useCallback(({ data, error }) => {
73
- var _a, _b;
97
+ var _a, _b, _c;
74
98
  if (error) {
75
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
99
+ showToast((_a = apiError(data)) !== null && _a !== void 0 ? _a : t("messagesNetworkError"), TOAST_VARIANT.ERROR);
76
100
  return;
77
101
  }
78
102
  if (data) {
79
103
  const response = data;
80
104
  dispatch({
81
105
  type: FEE_STRUCTURE_ACTION_TYPES.SET_ITEMS,
82
- payload: { items: (_a = response.items) !== null && _a !== void 0 ? _a : [], count: (_b = response.count) !== null && _b !== void 0 ? _b : 0 },
106
+ payload: { items: (_b = response.items) !== null && _b !== void 0 ? _b : [], count: (_c = response.count) !== null && _c !== void 0 ? _c : 0 },
83
107
  });
84
108
  }
85
109
  }, [dispatch, showToast, t]);
86
110
  const listFetchNowRef = useRef(null);
87
111
  const updateCallback = useCallback(({ data, error }) => {
88
- var _a;
112
+ var _a, _b;
89
113
  if (error) {
90
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
114
+ dispatch({
115
+ type: FEE_STRUCTURE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
116
+ payload: { disabled: false },
117
+ });
118
+ showToast((_a = apiError(data)) !== null && _a !== void 0 ? _a : t("messagesNetworkError"), TOAST_VARIANT.ERROR);
91
119
  return;
92
120
  }
93
121
  if (data) {
@@ -96,30 +124,32 @@ export const FeeStructureApiProvider = ({ children, }) => {
96
124
  ? t("messagesFeeStructureCreated")
97
125
  : t("messagesFeeStructureUpdated"), TOAST_VARIANT.SUCCESS);
98
126
  resetFormAndCloseDrawer();
99
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
127
+ (_b = listFetchNowRef.current) === null || _b === void 0 ? void 0 : _b.call(listFetchNowRef);
100
128
  }
101
- }, [resetFormAndCloseDrawer, showToast, t]);
129
+ }, [dispatch, resetFormAndCloseDrawer, showToast, t]);
102
130
  const byIdCallback = useCallback(({ data, error }) => {
131
+ var _a;
103
132
  if (error) {
104
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
133
+ showToast((_a = apiError(data)) !== null && _a !== void 0 ? _a : t("messagesNetworkError"), TOAST_VARIANT.ERROR);
105
134
  return;
106
135
  }
107
136
  if (data) {
137
+ // Keep the staged filter untouched when opening a record.
108
138
  dispatch({
109
139
  type: FEE_STRUCTURE_ACTION_TYPES.SET_FORM_DATA,
110
- payload: { form: Object.assign(Object.assign({}, data), { filterEnabled: undefined }) },
140
+ payload: { form: data },
111
141
  });
112
142
  }
113
143
  }, [dispatch, showToast, t]);
114
144
  const deleteCallback = useCallback(({ data, error }) => {
115
- var _a;
145
+ var _a, _b;
116
146
  if (error) {
117
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
147
+ showToast((_a = apiError(data)) !== null && _a !== void 0 ? _a : t("messagesNetworkError"), TOAST_VARIANT.ERROR);
118
148
  return;
119
149
  }
120
150
  if (data) {
121
151
  showToast(t("messagesFeeStructureDeleted"), TOAST_VARIANT.SUCCESS);
122
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
152
+ (_b = listFetchNowRef.current) === null || _b === void 0 ? void 0 : _b.call(listFetchNowRef);
123
153
  }
124
154
  }, [showToast, t]);
125
155
  // ==========================================================================
@@ -38,6 +38,7 @@ export declare const FEE_STRUCTURE_ACTION_TYPES: {
38
38
  errors: Record<string, string>;
39
39
  feeType: FEE_TYPE;
40
40
  filterEnabled: boolean | undefined;
41
+ appliedFilterEnabled: boolean | undefined;
41
42
  frequency: string | null;
42
43
  id: string;
43
44
  name: string;
@@ -57,6 +58,7 @@ export declare const FEE_STRUCTURE_ACTION_TYPES: {
57
58
  errors: Record<string, string>;
58
59
  feeType: FEE_TYPE;
59
60
  filterEnabled: boolean | undefined;
61
+ appliedFilterEnabled: boolean | undefined;
60
62
  frequency: string | null;
61
63
  id: string;
62
64
  name: string;
@@ -78,6 +80,7 @@ export declare const FEE_STRUCTURE_ACTION_TYPES: {
78
80
  errors: Record<string, string>;
79
81
  feeType: FEE_TYPE;
80
82
  filterEnabled: boolean | undefined;
83
+ appliedFilterEnabled: boolean | undefined;
81
84
  frequency: string | null;
82
85
  id: string;
83
86
  name: string;
@@ -97,6 +100,7 @@ export declare const FEE_STRUCTURE_ACTION_TYPES: {
97
100
  errors: Record<string, string>;
98
101
  feeType: FEE_TYPE;
99
102
  filterEnabled: boolean | undefined;
103
+ appliedFilterEnabled: boolean | undefined;
100
104
  frequency: string | null;
101
105
  id: string;
102
106
  name: string;
@@ -116,6 +120,7 @@ export declare const FEE_STRUCTURE_ACTION_TYPES: {
116
120
  errors: Record<string, string>;
117
121
  feeType: FEE_TYPE;
118
122
  filterEnabled: boolean | undefined;
123
+ appliedFilterEnabled: boolean | undefined;
119
124
  frequency: string | null;
120
125
  id: string;
121
126
  name: string;
@@ -35,6 +35,9 @@ const feeStructureConfig = {
35
35
  errors: {},
36
36
  feeType: FEE_TYPE.TUITION,
37
37
  filterEnabled: undefined,
38
+ // Staged filter: the drawer edits `filterEnabled`; Apply copies it to
39
+ // `appliedFilterEnabled`, which drives `listParams`.
40
+ appliedFilterEnabled: undefined,
38
41
  frequency: null,
39
42
  id: "",
40
43
  name: "",
@@ -45,6 +45,7 @@ export declare const useFeeStructureModule: () => {
45
45
  errors: Record<string, string>;
46
46
  feeType: FEE_TYPE;
47
47
  filterEnabled: boolean | undefined;
48
+ appliedFilterEnabled: boolean | undefined;
48
49
  frequency: string | null;
49
50
  id: string;
50
51
  name: string;
@@ -17,7 +17,7 @@ export const useFeeStructureModule = () => {
17
17
  // ============================================================================
18
18
  var _a;
19
19
  const context = useFeeStructureContext();
20
- const { dispatch } = context;
20
+ const { dispatch, handleCloseDrawer } = context;
21
21
  const state = context.state;
22
22
  const { listFetchNow, listLoading, updateFetchNow, updateLoading, byIdFetchNow, byIdLoading, deleteFetchNow, deleteLoading, resetFormAndCloseDrawer, } = useFeeStructureApiContext();
23
23
  const t = useTranslations("feeStructure");
@@ -59,11 +59,23 @@ export const useFeeStructureModule = () => {
59
59
  resetFormAndCloseDrawer();
60
60
  }, [resetFormAndCloseDrawer]);
61
61
  const handleCreate = useCallback(() => {
62
+ // Start from a blank form: opening Add after View/Edit must not reuse the
63
+ // previous record's id (which would update it instead of creating).
64
+ // `RESET_FORM` also restores the initial filter, so keep it.
65
+ const applied = state.appliedFilterEnabled;
66
+ const staged = state.filterEnabled;
67
+ dispatch({ type: FEE_STRUCTURE_ACTION_TYPES.RESET_FORM });
68
+ dispatch({
69
+ type: FEE_STRUCTURE_ACTION_TYPES.SET_FILTERS,
70
+ payload: {
71
+ filters: { appliedFilterEnabled: applied, filterEnabled: staged },
72
+ },
73
+ });
62
74
  dispatch({
63
75
  type: FEE_STRUCTURE_ACTION_TYPES.SET_DRAWER,
64
76
  payload: { drawer: FEE_STRUCTURE_DRAWER.FORM_DRAWER },
65
77
  });
66
- }, [dispatch]);
78
+ }, [dispatch, state.appliedFilterEnabled, state.filterEnabled]);
67
79
  const handleView = useCallback((row) => {
68
80
  byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
69
81
  dispatch({
@@ -82,9 +94,9 @@ export const useFeeStructureModule = () => {
82
94
  if (!confirm(t("messagesDeleteConfirmation")))
83
95
  return;
84
96
  deleteFetchNow === null || deleteFetchNow === void 0 ? void 0 : deleteFetchNow(undefined, {
85
- body: JSON.stringify({ id: row === null || row === void 0 ? void 0 : row.id }),
97
+ body: JSON.stringify({ id: row === null || row === void 0 ? void 0 : row.id, schoolId }),
86
98
  });
87
- }, [deleteFetchNow, t]);
99
+ }, [deleteFetchNow, schoolId, t]);
88
100
  const handleFilters = useCallback(() => {
89
101
  dispatch({
90
102
  type: FEE_STRUCTURE_ACTION_TYPES.SET_DRAWER,
@@ -128,43 +140,40 @@ export const useFeeStructureModule = () => {
128
140
  });
129
141
  }, [dispatch]);
130
142
  const applyFilters = useCallback(() => {
131
- closeDrawer();
143
+ // Copy the staged value into the applied filter; `listParams` (driven by
144
+ // `appliedFilterEnabled`) triggers the single list fetch.
132
145
  dispatch({
133
- type: FEE_STRUCTURE_ACTION_TYPES.SET_INPUT_FIELD,
134
- payload: { key: "filterEnabled", value: state.filterEnabled },
146
+ type: FEE_STRUCTURE_ACTION_TYPES.SET_FILTERS,
147
+ payload: { filters: { appliedFilterEnabled: state.filterEnabled } },
135
148
  });
136
149
  dispatch({
137
150
  type: FEE_STRUCTURE_ACTION_TYPES.SET_CURRENT_PAGE,
138
151
  payload: { currentPage: 1 },
139
152
  });
140
- listFetchNow === null || listFetchNow === void 0 ? void 0 : listFetchNow(undefined, {
141
- params: Object.assign({ currentPage: 1, pageLimit: state.pageLimit, schoolId }, (state.filterEnabled !== undefined
142
- ? { filterEnabled: String(state.filterEnabled) }
143
- : {})),
144
- });
145
- }, [closeDrawer, dispatch, listFetchNow, schoolId, state.filterEnabled, state.pageLimit]);
153
+ handleCloseDrawer === null || handleCloseDrawer === void 0 ? void 0 : handleCloseDrawer();
154
+ }, [dispatch, handleCloseDrawer, state.filterEnabled]);
146
155
  const clearFilters = useCallback(() => {
147
156
  dispatch({
148
157
  type: FEE_STRUCTURE_ACTION_TYPES.SET_FILTERS,
149
- payload: { filters: { filterEnabled: undefined } },
158
+ payload: {
159
+ filters: { filterEnabled: undefined, appliedFilterEnabled: undefined },
160
+ },
150
161
  });
151
162
  dispatch({
152
163
  type: FEE_STRUCTURE_ACTION_TYPES.SET_CURRENT_PAGE,
153
164
  payload: { currentPage: 1 },
154
165
  });
155
- listFetchNow === null || listFetchNow === void 0 ? void 0 : listFetchNow(undefined, {
156
- params: {
157
- currentPage: 1,
158
- pageLimit: state.pageLimit,
159
- schoolId,
160
- },
161
- });
162
- }, [dispatch, listFetchNow, state.pageLimit, schoolId]);
166
+ handleCloseDrawer === null || handleCloseDrawer === void 0 ? void 0 : handleCloseDrawer();
167
+ }, [dispatch, handleCloseDrawer]);
163
168
  const toggleStatus = useCallback((row) => {
164
169
  updateFetchNow(undefined, {
165
- body: JSON.stringify(Object.assign(Object.assign({}, row), { enabled: !(row === null || row === void 0 ? void 0 : row.enabled) })),
170
+ body: JSON.stringify({
171
+ id: row === null || row === void 0 ? void 0 : row.id,
172
+ schoolId,
173
+ enabled: !(row === null || row === void 0 ? void 0 : row.enabled),
174
+ }),
166
175
  });
167
- }, [updateFetchNow]);
176
+ }, [schoolId, updateFetchNow]);
168
177
  // ============================================================================
169
178
  // 1.4.5 NETWORK ACTIONS
170
179
  // ============================================================================
@@ -231,14 +240,14 @@ export const useFeeStructureModule = () => {
231
240
  order: 2,
232
241
  },
233
242
  {
234
- enabled: false,
243
+ enabled: (row) => Boolean(row === null || row === void 0 ? void 0 : row.enabled),
235
244
  handleOnClick: handleDelete,
236
245
  label: t("actionsButtonDelete"),
237
246
  order: 3,
238
247
  variant: "destructive",
239
248
  },
240
249
  {
241
- enabled: false,
250
+ enabled: true,
242
251
  handleOnClick: toggleStatus,
243
252
  label: t("actionsButtonToggleStatus"),
244
253
  order: 4,
@@ -6,12 +6,13 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
6
6
  * Form for creating/updating fee structures.
7
7
  */
8
8
  import { EnhancedCheckbox } from "@appcorp/shadcn/components/enhanced-checkbox";
9
+ import { EnhancedCombobox } from "@appcorp/shadcn/components/enhanced-combobox";
9
10
  import { useEnhancedCombobox } from "@appcorp/shadcn/hooks/use-enhanced-combobox";
10
11
  import { EnhancedInput } from "@appcorp/shadcn/components/enhanced-input";
11
12
  import { EnhancedTextarea } from "@appcorp/shadcn/components/enhanced-textarea";
12
13
  import { useFeeStructureModule } from "./context";
13
14
  import { FEE_TYPE_OPTIONS, FREQUENCY_OPTIONS } from "./constants";
14
- import { CLASS_API_ROUTES, FEE_STRUCTURE_API_ROUTES } from "../../constants";
15
+ import { CLASS_API_ROUTES } from "../../constants";
15
16
  import { getCachedWorkspaceSync } from "../workspace/cache";
16
17
  import { useTranslations } from "next-intl";
17
18
  import { useFetch } from "@react-pakistan/util-functions/hooks/use-fetch";
@@ -19,7 +20,7 @@ import { API_METHODS } from "@react-pakistan/util-functions/constants/api-method
19
20
  import { useEffect } from "react";
20
21
  import { getTranslatedError } from "../../utils/get-translated-error";
21
22
  export const FeeStructureForm = () => {
22
- var _a, _b, _c;
23
+ var _a, _b, _c, _d;
23
24
  const { state, handleChange } = useFeeStructureModule();
24
25
  const { amount, classId, description, enabled, errors, feeType, frequency, name, } = state;
25
26
  const t = useTranslations("feeStructure");
@@ -42,8 +43,9 @@ export const FeeStructureForm = () => {
42
43
  "One-time": t("formOptionOneTime"),
43
44
  };
44
45
  const workspace = getCachedWorkspaceSync();
45
- const { fetchNow, data: classes } = useFetch(FEE_STRUCTURE_API_ROUTES.CLASS, {
46
- params: { workspaceId: workspace === null || workspace === void 0 ? void 0 : workspace.id },
46
+ const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
47
+ const { fetchNow, data: classes } = useFetch(CLASS_API_ROUTES.UNIT, {
48
+ params: { schoolId },
47
49
  method: API_METHODS.GET,
48
50
  });
49
51
  useEffect(() => {
@@ -51,63 +53,29 @@ export const FeeStructureForm = () => {
51
53
  // eslint-disable-next-line react-hooks/exhaustive-deps
52
54
  }, []);
53
55
  // const cachedClasses = getCachedClassesSync();
54
- const { enhancedComboboxElement: feeTypeCombo } = useEnhancedCombobox({
55
- emptyText: t("formNoFeeTypeEmpty"),
56
- id: "feeType",
57
- info: t("formFeeTypeInfo"),
58
- label: t("formFeeTypeLabel"),
59
- onValueChange: (value) => handleChange("feeType", value),
60
- options: FEE_TYPE_OPTIONS.map((opt) => ({
56
+ // Fee type and frequency are static enums: no remote search endpoint.
57
+ const feeTypeCombo = (_jsx(EnhancedCombobox, { emptyText: t("formNoFeeTypeEmpty"), error: getTranslatedError({ errors, key: "feeType", t }), id: "feeType", info: t("formFeeTypeInfo"), label: t("formFeeTypeLabel"), onValueChange: (value) => handleChange("feeType", value), options: FEE_TYPE_OPTIONS.map((opt) => ({
61
58
  value: opt.value,
62
59
  label: feeTypeLabelMap[opt.value] || opt.label,
63
- })),
64
- placeholder: t("formFeeTypePlaceholder"),
65
- required: true,
66
- searchEndpoint: FEE_STRUCTURE_API_ROUTES.UNIT,
67
- searchPlaceholder: t("formSearchFeeTypePlaceholder"),
68
- formatSearchResult: (item) => {
69
- var _a, _b;
70
- return ({
71
- label: String((_a = item.label) !== null && _a !== void 0 ? _a : ""),
72
- value: String((_b = item.value) !== null && _b !== void 0 ? _b : ""),
73
- });
74
- },
75
- value: feeType || "",
76
- });
77
- const { enhancedComboboxElement: frequencyCombo } = useEnhancedCombobox({
78
- emptyText: t("formNoFrequencyEmpty"),
79
- id: "frequency",
80
- info: t("formFrequencyInfo"),
81
- label: t("formFrequencyLabel"),
82
- onValueChange: (value) => handleChange("frequency", value),
83
- options: FREQUENCY_OPTIONS.map((opt) => ({
60
+ })), placeholder: t("formFeeTypePlaceholder"), required: true, value: feeType || "" }));
61
+ const frequencyCombo = (_jsx(EnhancedCombobox, { emptyText: t("formNoFrequencyEmpty"), error: getTranslatedError({ errors, key: "frequency", t }), id: "frequency", info: t("formFrequencyInfo"), label: t("formFrequencyLabel"), onValueChange: (value) => handleChange("frequency", value || null), options: FREQUENCY_OPTIONS.map((opt) => ({
84
62
  value: opt.value,
85
63
  label: frequencyLabelMap[opt.value] || opt.label,
86
- })),
87
- placeholder: t("formFrequencyPlaceholder"),
88
- searchEndpoint: FEE_STRUCTURE_API_ROUTES.UNIT,
89
- searchPlaceholder: t("formSearchFrequencyPlaceholder"),
90
- formatSearchResult: (item) => {
91
- var _a, _b;
92
- return ({
93
- label: String((_a = item.label) !== null && _a !== void 0 ? _a : ""),
94
- value: String((_b = item.value) !== null && _b !== void 0 ? _b : ""),
95
- });
96
- },
97
- value: frequency || "",
98
- });
64
+ })), placeholder: t("formFrequencyPlaceholder"), value: frequency || "" }));
99
65
  const { enhancedComboboxElement: classIdCombo } = useEnhancedCombobox({
100
66
  emptyText: t("formNoClassEmpty"),
101
67
  id: "classId",
102
68
  info: t("formClassInfo"),
103
69
  label: t("formClassLabel"),
104
70
  onValueChange: (value) => handleChange("classId", value || null),
105
- options: (_a = classes === null || classes === void 0 ? void 0 : classes.items) === null || _a === void 0 ? void 0 : _a.map((cls) => ({
71
+ options: (_b = classes === null || classes === void 0 ? void 0 : classes.items) === null || _b === void 0 ? void 0 : _b.map((cls) => ({
106
72
  value: cls.id,
107
73
  label: `${cls.name} (${cls.code})`,
108
74
  })),
109
75
  placeholder: t("formClassPlaceholder"),
110
76
  searchEndpoint: CLASS_API_ROUTES.UNIT,
77
+ // Tenant scope for both the initial fetch and remote search.
78
+ searchParams: { schoolId },
111
79
  searchPlaceholder: t("formSearchClassPlaceholder"),
112
80
  formatSearchResult: (item) => {
113
81
  const classItem = item;
@@ -119,6 +87,6 @@ export const FeeStructureForm = () => {
119
87
  value: classId || "",
120
88
  });
121
89
  return (_jsxs("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("formNameInfo"), label: t("formNameLabel"), onChange: (e) => handleChange("name", e.target.value), placeholder: t("formNamePlaceholder"), required: true, value: name || "" }), feeTypeCombo, _jsx(EnhancedInput, { error: getTranslatedError({ errors, key: "amount", t }), id: "amount", info: t("formAmountInfo", {
122
- currency: (_c = (_b = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _b === void 0 ? void 0 : _b.currency) !== null && _c !== void 0 ? _c : "",
123
- }), label: t("formAmountLabel"), min: "0", onChange: (e) => handleChange("amount", Number(e.target.value)), placeholder: t("formAmountPlaceholder"), required: true, step: "0.01", type: "number", value: amount }), frequencyCombo, classIdCombo, _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, { defaultChecked: enabled, label: t("formActiveFeeStructureLabel"), onCheckedChange: (checked) => handleChange("enabled", checked) })] }));
90
+ currency: (_d = (_c = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _c === void 0 ? void 0 : _c.currency) !== null && _d !== void 0 ? _d : "",
91
+ }), label: t("formAmountLabel"), min: "0.01", onChange: (e) => handleChange("amount", Number(e.target.value)), placeholder: t("formAmountPlaceholder"), required: true, step: "0.01", type: "number", value: amount }), frequencyCombo, classIdCombo, _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, { defaultChecked: enabled, label: t("formActiveFeeStructureLabel"), onCheckedChange: (checked) => handleChange("enabled", checked) })] }));
124
92
  };
@@ -11,19 +11,45 @@ import { pageLimit } from "./constants";
11
11
  import { FEE_STRUCTURE_API_ROUTES } from "../../constants";
12
12
  import { FEE_STRUCTURE_ACTION_TYPES, useFeeStructureContext } from "./context";
13
13
  import { useRef, useEffect, useCallback } from "react";
14
- const workspace = getCachedWorkspaceSync();
14
+ /** Read at call time — never cache a workspace captured at module load. */
15
+ const currentSchoolId = () => { var _a, _b; return ((_b = (_a = getCachedWorkspaceSync()) === null || _a === void 0 ? void 0 : _a.school) === null || _b === void 0 ? void 0 : _b.id) || ""; };
15
16
  const POLL_INTERVAL_MS = 2000;
16
17
  const POLL_TIMEOUT_MS = 300000;
18
+ const EXPORT_PAGE_LIMIT = 200;
19
+ const EXPORT_MAX_PAGES = 50;
20
+ /**
21
+ * Export fee structures as CSV. Walks every page (the API caps a page at 200)
22
+ * and stops on a short page or after a safety cap.
23
+ */
17
24
  const handleGetAllRecords = async (schoolId, pageLimit) => {
18
- const response = await fetch(`${FEE_STRUCTURE_API_ROUTES.UNIT}?pageLimit=${pageLimit}&currentPage=1&schoolId=${schoolId}`);
19
- const result = await response.json();
20
- const csv = await converter.json2csv(result.items || [], {});
25
+ var _a, _b, _c;
26
+ const take = Math.min(pageLimit, EXPORT_PAGE_LIMIT);
27
+ const items = [];
28
+ for (let page = 1; page <= EXPORT_MAX_PAGES; page++) {
29
+ const params = new URLSearchParams({
30
+ currentPage: String(page),
31
+ pageLimit: String(take),
32
+ schoolId,
33
+ });
34
+ const response = await fetch(`${FEE_STRUCTURE_API_ROUTES.UNIT}?${params.toString()}`);
35
+ if (!response.ok) {
36
+ const body = (await response.json().catch(() => ({})));
37
+ throw new Error((_a = body.error) !== null && _a !== void 0 ? _a : `Export failed (${response.status})`);
38
+ }
39
+ const result = (await response.json());
40
+ const pageItems = (_b = result.items) !== null && _b !== void 0 ? _b : [];
41
+ items.push(...pageItems);
42
+ if (pageItems.length < take ||
43
+ items.length >= ((_c = result.count) !== null && _c !== void 0 ? _c : items.length)) {
44
+ break;
45
+ }
46
+ }
47
+ const csv = await converter.json2csv(items, {});
21
48
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
22
49
  await downloadFromUrl(blob, "fee-structure.csv");
23
50
  };
24
51
  async function submitBulkJob(csvData, method, signal) {
25
- var _a;
26
- const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
52
+ const schoolId = currentSchoolId();
27
53
  if (!schoolId)
28
54
  throw new Error("School ID not found");
29
55
  const res = await fetch(FEE_STRUCTURE_API_ROUTES.BULK, {
@@ -114,13 +140,27 @@ export const FeeStructureMoreActions = () => {
114
140
  const row = records[i];
115
141
  const msgs = [];
116
142
  if (method === "POST") {
117
- const result = feeStructureFormValidation.safeParse(Object.assign(Object.assign({}, row), { amount: Number(row.amount) }));
143
+ const rawEnabled = (_b = row.enabled) === null || _b === void 0 ? void 0 : _b.trim().toLowerCase();
144
+ const result = feeStructureFormValidation.safeParse({
145
+ name: row.name,
146
+ feeType: row.feeType,
147
+ amount: Number(row.amount),
148
+ classId: row.classId || null,
149
+ // CSV cells are strings; normalise before Zod validates them.
150
+ frequency: row.frequency || null,
151
+ description: row.description || null,
152
+ enabled: rawEnabled === undefined || rawEnabled === ""
153
+ ? undefined
154
+ : rawEnabled === "true" ||
155
+ rawEnabled === "1" ||
156
+ rawEnabled === "yes",
157
+ });
118
158
  if (!result.success) {
119
159
  msgs.push(...result.error.issues.map((issue) => `${issue.path.join(".")}: ${t(issue.message)}`));
120
160
  }
121
161
  }
122
162
  else {
123
- if (!((_b = row.id) === null || _b === void 0 ? void 0 : _b.trim()))
163
+ if (!((_c = row.id) === null || _c === void 0 ? void 0 : _c.trim()))
124
164
  msgs.push(t("validationFeeStructureIdForUpdateRequired"));
125
165
  }
126
166
  if (msgs.length > 0) {
@@ -163,7 +203,7 @@ export const FeeStructureMoreActions = () => {
163
203
  return;
164
204
  if (status.status === "completed") {
165
205
  const r = status.results;
166
- if (r && ((_c = r.errors) === null || _c === void 0 ? void 0 : _c.length) > 0) {
206
+ if (r && ((_d = r.errors) === null || _d === void 0 ? void 0 : _d.length) > 0) {
167
207
  const summary = formatErrorSummary(t, r.errors);
168
208
  showSuccessToast(t("messagesBulkResults", {
169
209
  created: r.created,
@@ -183,7 +223,7 @@ export const FeeStructureMoreActions = () => {
183
223
  else {
184
224
  showSuccessToast(t("messagesBulkSuccess"));
185
225
  }
186
- const schoolId = ((_d = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _d === void 0 ? void 0 : _d.id) || "";
226
+ const schoolId = currentSchoolId();
187
227
  fetch(`${FEE_STRUCTURE_API_ROUTES.UNIT}?currentPage=1&pageLimit=${pageLimit}&schoolId=${schoolId}`, {
188
228
  headers: {
189
229
  "Content-Type": "application/json",
@@ -229,8 +269,15 @@ export const FeeStructureMoreActions = () => {
229
269
  id: "1",
230
270
  title: t("downloadEmptyCsvTemplate"),
231
271
  handleOnClick: async () => {
232
- var _a;
233
- await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1);
272
+ try {
273
+ await handleGetAllRecords(currentSchoolId(), 1);
274
+ }
275
+ catch (error) {
276
+ showErrorToast(t("messagesBulkFailedDetail", {
277
+ action: "download",
278
+ error: error instanceof Error ? error.message : t("unknownError"),
279
+ }));
280
+ }
234
281
  },
235
282
  },
236
283
  { id: "2", title: t("addYourDataToTheCsv") },
@@ -244,8 +291,15 @@ export const FeeStructureMoreActions = () => {
244
291
  id: "1",
245
292
  title: t("downloadPopulatedCsvTemplate"),
246
293
  handleOnClick: async () => {
247
- var _a;
248
- await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1000);
294
+ try {
295
+ await handleGetAllRecords(currentSchoolId(), EXPORT_PAGE_LIMIT);
296
+ }
297
+ catch (error) {
298
+ showErrorToast(t("messagesBulkFailedDetail", {
299
+ action: "download",
300
+ error: error instanceof Error ? error.message : t("unknownError"),
301
+ }));
302
+ }
249
303
  },
250
304
  },
251
305
  { id: "2", title: t("updateYourDataInTheCsv") },