@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
@@ -18,6 +18,7 @@
18
18
  "use client";
19
19
  import { jsx as _jsx } from "react/jsx-runtime";
20
20
  import { useMemo } from "react";
21
+ import { useTranslations } from "next-intl";
21
22
  import { COMPONENT_TYPE } from "@appcorp/shadcn/components/enhanced-table";
22
23
  import { createGenericModulePage, } from "@react-pakistan/util-functions/factory/generic-component-factory";
23
24
  import { useClassModule, ClassProvider, CLASS_ACTION_TYPES } from "./context";
@@ -35,6 +36,11 @@ const tableBodyCols = [
35
36
  { componentType: COMPONENT_TYPE.BOLD_TEXT, key: "name" },
36
37
  { componentType: COMPONENT_TYPE.TEXT, key: "description" },
37
38
  { componentType: COMPONENT_TYPE.TEXT, key: "code" },
39
+ {
40
+ componentType: COMPONENT_TYPE.TEXT,
41
+ key: "campus",
42
+ textFormatter: (_, row) => { var _a, _b; return (_b = (_a = row.campus) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : "—"; },
43
+ },
38
44
  { componentType: COMPONENT_TYPE.BOOLEAN, key: "enabled" },
39
45
  { componentType: COMPONENT_TYPE.ACTIONS },
40
46
  ];
@@ -47,17 +53,18 @@ const createComponentInstances = () => ({
47
53
  moreActions: _jsx(ClassMoreActions, {}),
48
54
  view: _jsx(ClassView, {}),
49
55
  });
50
- const createClassConfig = ({ cancelLabel, dispatch, drawerFilterDescription, drawerFilterTitle, drawerFormDescription, drawerFormTitle, drawerMoreActionsDescription, drawerMoreActionsTitle, drawerViewDescription, drawerViewTitle, labelActions, labelCode, labelDescription, labelEnabled, labelId, labelName, saveLabel, searchPlaceholder, tableDescription, tableTitle, }) => {
56
+ const createClassConfig = ({ cancelLabel, dispatch, drawerFilterDescription, drawerFilterTitle, drawerFormDescription, drawerFormTitle, drawerMoreActionsDescription, drawerMoreActionsTitle, drawerViewDescription, drawerViewTitle, labelActions, labelCampus, labelCode, labelDescription, labelEnabled, labelId, labelName, saveLabel, searchPlaceholder, tableDescription, tableTitle, }) => {
51
57
  const components = createComponentInstances();
52
58
  return {
53
59
  moduleName: "class",
54
60
  tableColumns: [
55
61
  { label: labelId, width: "5%" },
56
- { label: labelName, width: "25%" },
57
- { label: labelDescription, width: "40%" },
58
- { label: labelCode, width: "15%" },
62
+ { label: labelName, width: "20%" },
63
+ { label: labelDescription, width: "30%" },
64
+ { label: labelCode, width: "12%" },
65
+ { label: labelCampus, width: "15%" },
59
66
  { label: labelEnabled, width: "10%" },
60
- { label: labelActions, width: "5%" },
67
+ { label: labelActions, width: "8%" },
61
68
  ],
62
69
  cancelLabel,
63
70
  drawerFilterDescription,
@@ -87,6 +94,7 @@ const createClassConfig = ({ cancelLabel, dispatch, drawerFilterDescription, dra
87
94
  const GenericClassPage = createGenericModulePage();
88
95
  const ClassPageInner = (props) => {
89
96
  const context = useClassModule();
97
+ const t = useTranslations("class");
90
98
  const classConfig = useMemo(() => createClassConfig({
91
99
  dispatch: context.dispatch,
92
100
  cancelLabel: props.cancelLabel,
@@ -99,6 +107,7 @@ const ClassPageInner = (props) => {
99
107
  drawerMoreActionsTitle: props.drawerMoreActionsTitle,
100
108
  drawerMoreActionsDescription: props.drawerMoreActionsDescription,
101
109
  labelActions: props.labelActions,
110
+ labelCampus: t("tableColumnHeaderCampus"),
102
111
  labelCode: props.labelCode,
103
112
  labelDescription: props.labelDescription,
104
113
  labelEnabled: props.labelEnabled,
@@ -120,6 +129,7 @@ const ClassPageInner = (props) => {
120
129
  props.drawerMoreActionsTitle,
121
130
  props.drawerMoreActionsDescription,
122
131
  props.labelActions,
132
+ t,
123
133
  props.labelCode,
124
134
  props.labelDescription,
125
135
  props.labelEnabled,
@@ -2,7 +2,6 @@ import { z } from "zod";
2
2
  export declare const VALIDATION_KEYS: {
3
3
  readonly nameRequired: "validationClassNameRequired";
4
4
  readonly nameMaxLength: "validationClassNameMaxLength";
5
- readonly nameFormat: "validationClassNameFormat";
6
5
  readonly codeRequired: "validationClassCodeRequired";
7
6
  readonly codeMaxLength: "validationClassCodeMaxLength";
8
7
  readonly codeFormat: "validationClassCodeFormat";
@@ -12,6 +11,7 @@ export declare const VALIDATION_KEYS: {
12
11
  export declare const classFormValidation: z.ZodObject<{
13
12
  name: z.ZodString;
14
13
  code: z.ZodString;
15
- description: z.ZodOptional<z.ZodString>;
14
+ description: z.ZodOptional<z.ZodNullable<z.ZodString>>;
15
+ campusId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
16
16
  enabled: z.ZodOptional<z.ZodBoolean>;
17
17
  }, z.core.$strip>;
@@ -2,7 +2,6 @@ import { z } from "zod";
2
2
  export const VALIDATION_KEYS = {
3
3
  nameRequired: "validationClassNameRequired",
4
4
  nameMaxLength: "validationClassNameMaxLength",
5
- nameFormat: "validationClassNameFormat",
6
5
  codeRequired: "validationClassCodeRequired",
7
6
  codeMaxLength: "validationClassCodeMaxLength",
8
7
  codeFormat: "validationClassCodeFormat",
@@ -10,13 +9,16 @@ export const VALIDATION_KEYS = {
10
9
  descriptionMaxLength: "validationClassDescriptionMaxLength",
11
10
  };
12
11
  export const classFormValidation = z.object({
12
+ // Names may be in any language; only length is enforced.
13
13
  name: z
14
14
  .string()
15
+ .trim()
15
16
  .min(1, VALIDATION_KEYS.nameRequired)
16
- .max(100, VALIDATION_KEYS.nameMaxLength)
17
- .regex(/^[a-zA-Z0-9\s\-_]+$/, VALIDATION_KEYS.nameFormat),
17
+ .max(100, VALIDATION_KEYS.nameMaxLength),
18
18
  code: z
19
19
  .string()
20
+ .trim()
21
+ .toUpperCase()
20
22
  .min(1, VALIDATION_KEYS.codeRequired)
21
23
  .max(20, VALIDATION_KEYS.codeMaxLength)
22
24
  .regex(/^[A-Z0-9\-_]+$/, VALIDATION_KEYS.codeFormat)
@@ -24,6 +26,8 @@ export const classFormValidation = z.object({
24
26
  description: z
25
27
  .string()
26
28
  .max(500, VALIDATION_KEYS.descriptionMaxLength)
29
+ .nullable()
27
30
  .optional(),
31
+ campusId: z.string().nullable().optional(),
28
32
  enabled: z.boolean().optional(),
29
33
  });
@@ -14,9 +14,7 @@ import { useTranslations } from "next-intl";
14
14
  import { formatValue } from "@react-pakistan/util-functions/general/format-value";
15
15
  export const ClassView = () => {
16
16
  const { state } = useClassModule();
17
- const { code, description, enabled, name } = state;
17
+ const { campus, code, description, enabled, name } = state;
18
18
  const t = useTranslations("class");
19
- return (_jsxs("div", { className: "space-y-4", children: [_jsx(Card, { children: _jsx(CardContent, { className: "pt-6", children: _jsxs("div", { className: "flex items-center gap-6", children: [_jsx("div", { className: "bg-primary/10 flex h-24 w-24 items-center justify-center rounded-full", children: _jsx(GraduationCap, { className: "text-primary h-12 w-12" }) }), _jsxs("div", { className: "flex-1", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("h2", { className: "text-2xl font-bold", children: name }), enabled ? (_jsx(CheckCircle2, { className: "h-5 w-5 text-green-500" })) : (_jsx(XCircle, { className: "h-5 w-5 text-red-500" }))] }), _jsxs("p", { className: "text-muted-foreground mt-1", children: [t("viewFieldCode"), ": ", code] })] })] }) }) }), _jsxs(Card, { children: [_jsxs(CardHeader, { className: "pb-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(GraduationCap, { className: "text-primary h-5 w-5" }), _jsx(CardTitle, { className: "text-lg", children: t("viewSectionClassDetails") })] }), _jsx(CardDescription, { children: t("viewSectionCompleteClassInformation") })] }), _jsx(Separator, {}), _jsx(CardContent, { className: "pt-6", children: _jsxs("div", { className: "grid grid-cols-1 gap-6 md:grid-cols-2", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldClassName") }), _jsx("p", { className: "text-base", children: formatValue(name) })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldClassCode") }), _jsx("p", { className: "text-base", children: formatValue(code) })] }), _jsxs("div", { className: "space-y-1 md:col-span-2", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldDescription") }), _jsx("p", { className: "text-base", children: formatValue(description) })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldStatus") }), _jsx(Badge, { variant: enabled ? "default" : "secondary", children: enabled
20
- ? t("badgeActive")
21
- : t("badgeInactive") })] })] }) })] })] }));
19
+ return (_jsxs("div", { className: "space-y-4", children: [_jsx(Card, { children: _jsx(CardContent, { className: "pt-6", children: _jsxs("div", { className: "flex items-center gap-6", children: [_jsx("div", { className: "bg-primary/10 flex h-24 w-24 items-center justify-center rounded-full", children: _jsx(GraduationCap, { className: "text-primary h-12 w-12" }) }), _jsxs("div", { className: "flex-1", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("h2", { className: "text-2xl font-bold", children: name }), enabled ? (_jsx(CheckCircle2, { className: "h-5 w-5 text-green-500" })) : (_jsx(XCircle, { className: "h-5 w-5 text-red-500" }))] }), _jsxs("p", { className: "text-muted-foreground mt-1", children: [t("viewFieldCode"), ": ", code] })] })] }) }) }), _jsxs(Card, { children: [_jsxs(CardHeader, { className: "pb-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(GraduationCap, { className: "text-primary h-5 w-5" }), _jsx(CardTitle, { className: "text-lg", children: t("viewSectionClassDetails") })] }), _jsx(CardDescription, { children: t("viewSectionCompleteClassInformation") })] }), _jsx(Separator, {}), _jsx(CardContent, { className: "pt-6", children: _jsxs("div", { className: "grid grid-cols-1 gap-6 md:grid-cols-2", children: [_jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldClassName") }), _jsx("p", { className: "text-base", children: formatValue(name) })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldClassCode") }), _jsx("p", { className: "text-base", children: formatValue(code) })] }), _jsxs("div", { className: "space-y-1 md:col-span-2", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldDescription") }), _jsx("p", { className: "text-base", children: formatValue(description) })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldCampus") }), _jsx("p", { className: "text-base", children: campus ? `${campus.name} (${campus.code})` : "—" })] }), _jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: "text-muted-foreground text-sm font-medium", children: t("viewFieldStatus") }), _jsx(Badge, { variant: enabled ? "default" : "secondary", children: enabled ? t("badgeActive") : t("badgeInactive") })] })] }) })] })] }));
22
20
  };
@@ -0,0 +1,65 @@
1
+ import { type TableRow } from "@appcorp/shadcn/components/enhanced-table";
2
+ import { DiscountCodeBE } from "../../../type";
3
+ export declare const useDiscountCodeModule: () => {
4
+ applyFilters: () => void;
5
+ byIdLoading: boolean;
6
+ clearFilters: () => void;
7
+ clearSearch: () => void;
8
+ closeDrawer: () => void;
9
+ deleteLoading: boolean;
10
+ handleChange: (key: string, value: string | number | boolean | string[] | undefined) => void;
11
+ handleCreate: () => void;
12
+ handleDelete: (row?: TableRow) => void;
13
+ handleEdit: (row?: TableRow) => void;
14
+ handleFilters: () => void;
15
+ handlePageChange: (page: number | unknown) => void;
16
+ handlePageLimitChange: (_k: string, value: object) => void;
17
+ handleSearch: (query: string) => void;
18
+ handleSubmit: () => void;
19
+ handleView: (row?: TableRow) => void;
20
+ headerActions: {
21
+ enabled: boolean;
22
+ handleOnClick: () => void;
23
+ label: string;
24
+ order: number;
25
+ }[];
26
+ listError: Error | undefined;
27
+ listFetchNow: (url?: string, config?: import("@react-pakistan/util-functions/hooks/use-fetch").FetchConfig) => void;
28
+ listLoading: boolean;
29
+ rowActions: ({
30
+ enabled: boolean;
31
+ handleOnClick: (row?: TableRow) => void;
32
+ label: string;
33
+ order: number;
34
+ variant?: undefined;
35
+ } | {
36
+ enabled: boolean;
37
+ handleOnClick: (row?: TableRow) => void;
38
+ label: string;
39
+ order: number;
40
+ variant: "destructive";
41
+ })[];
42
+ updateLoading: boolean;
43
+ handleCloseDrawer?: () => void;
44
+ state: {
45
+ code: string;
46
+ description: string;
47
+ discountType: import("../../../types").DISCOUNT_TYPE | "";
48
+ discountValue: number;
49
+ enabled: boolean;
50
+ errors: Record<string, string>;
51
+ id: string;
52
+ count: number;
53
+ items: DiscountCodeBE[];
54
+ currentPage: number;
55
+ pageLimit: number;
56
+ searchQuery: string;
57
+ disableSaveButton: boolean;
58
+ drawer: string | null;
59
+ filterEnabled: boolean | undefined;
60
+ filterDiscountType: import("../../../types").DISCOUNT_TYPE | undefined;
61
+ appliedFilterEnabled: boolean | undefined;
62
+ appliedFilterDiscountType: import("../../../types").DISCOUNT_TYPE | undefined;
63
+ };
64
+ dispatch: React.Dispatch<any>;
65
+ };
@@ -0,0 +1,402 @@
1
+ "use client";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ /**
14
+ * Discount code module business logic.
15
+ *
16
+ * Extracted from `context.tsx` so it can be unit-tested without loading the
17
+ * page/components (and their ESM-only UI package).
18
+ */
19
+ import { useCallback, useEffect, useMemo, useRef } from "react";
20
+ import { useTheme } from "next-themes";
21
+ import { useTranslations } from "next-intl";
22
+ import { isCreatedOrUpdated } from "@react-pakistan/util-functions/general/is-created-or-updated";
23
+ import { validateForm } from "@react-pakistan/util-functions/general/validate-form";
24
+ import { useModuleEntityV2, } from "@react-pakistan/util-functions/hooks/use-module-entity-v2";
25
+ import { useDebounce } from "@react-pakistan/util-functions/hooks/use-debounce";
26
+ import { generateThemeToast, TOAST_VARIANT, } from "@appcorp/shadcn/lib/toast-utils";
27
+ import { DISCOUNT_CODE_API_ROUTES } from "../../../constants";
28
+ import { accountDiscountCodeFormValidation } from "../validate";
29
+ import { getCachedWorkspaceSync } from "../../workspace/cache";
30
+ import { DISCOUNT_CODE_ACTION_TYPES, DISCOUNT_CODE_DRAWER, useDiscountCodeStateContext, } from "../context";
31
+ /** Prisma Decimal arrives as a string; normalise it for the form/math. */
32
+ const normalizeCode = (item) => (Object.assign(Object.assign({}, item), { discountValue: Number(item.discountValue) }));
33
+ export const useDiscountCodeModule = () => {
34
+ var _a;
35
+ const context = useDiscountCodeStateContext();
36
+ const { dispatch } = context;
37
+ const state = context.state;
38
+ const t = useTranslations("discountCode");
39
+ const { theme } = useTheme();
40
+ const workspace = getCachedWorkspaceSync();
41
+ const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
42
+ const listFetchNowRef = useRef(null);
43
+ const debouncedQuery = useDebounce(state.searchQuery, 800);
44
+ // ---------------------------------------------------------------------------
45
+ // API parameters
46
+ // ---------------------------------------------------------------------------
47
+ const listParams = useMemo(() => (Object.assign(Object.assign(Object.assign({ currentPage: state.currentPage, pageLimit: state.pageLimit, schoolId }, (debouncedQuery ? { searchQuery: debouncedQuery } : {})), (state.appliedFilterEnabled !== undefined
48
+ ? { filterEnabled: String(state.appliedFilterEnabled) }
49
+ : {})), (state.appliedFilterDiscountType
50
+ ? { filterDiscountType: state.appliedFilterDiscountType }
51
+ : {}))), [
52
+ state.appliedFilterDiscountType,
53
+ state.appliedFilterEnabled,
54
+ state.currentPage,
55
+ state.pageLimit,
56
+ debouncedQuery,
57
+ schoolId,
58
+ ]);
59
+ const updateParams = useMemo(() => ({
60
+ code: state.code,
61
+ description: state.description,
62
+ discountType: state.discountType,
63
+ discountValue: Number(state.discountValue),
64
+ enabled: state.enabled,
65
+ id: state.id,
66
+ schoolId,
67
+ }), [
68
+ state.code,
69
+ state.description,
70
+ state.discountType,
71
+ state.discountValue,
72
+ state.enabled,
73
+ state.id,
74
+ schoolId,
75
+ ]);
76
+ // Single-record calls must carry the tenant.
77
+ const byIdParams = useMemo(() => ({ id: state.id, schoolId }), [state.id, schoolId]);
78
+ const deleteParams = useMemo(() => ({ id: state.id, schoolId }), [state.id, schoolId]);
79
+ // ---------------------------------------------------------------------------
80
+ // Utilities
81
+ // ---------------------------------------------------------------------------
82
+ const showToast = useCallback((description, variant) => {
83
+ generateThemeToast({
84
+ description,
85
+ theme: theme,
86
+ variant,
87
+ });
88
+ }, [theme]);
89
+ const resetFormFields = useCallback(() => {
90
+ dispatch({
91
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_FORM_DATA,
92
+ payload: {
93
+ form: {
94
+ code: "",
95
+ description: "",
96
+ discountType: "",
97
+ discountValue: 0,
98
+ enabled: true,
99
+ id: "",
100
+ },
101
+ },
102
+ });
103
+ dispatch({
104
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_ERRORS,
105
+ payload: { errors: {} },
106
+ });
107
+ dispatch({
108
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
109
+ payload: { disabled: false },
110
+ });
111
+ }, [dispatch]);
112
+ const resetFormAndCloseDrawer = useCallback(() => {
113
+ resetFormFields();
114
+ dispatch({
115
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DRAWER,
116
+ payload: { drawer: null },
117
+ });
118
+ }, [dispatch, resetFormFields]);
119
+ // ---------------------------------------------------------------------------
120
+ // API callbacks
121
+ // ---------------------------------------------------------------------------
122
+ const listCallback = useCallback(({ data, error }) => {
123
+ var _a, _b;
124
+ if (error) {
125
+ showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
126
+ return;
127
+ }
128
+ if (data) {
129
+ const response = data;
130
+ dispatch({
131
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_ITEMS,
132
+ payload: {
133
+ items: ((_a = response.items) !== null && _a !== void 0 ? _a : []).map(normalizeCode),
134
+ count: (_b = response.count) !== null && _b !== void 0 ? _b : 0,
135
+ },
136
+ });
137
+ }
138
+ }, [dispatch, showToast, t]);
139
+ const updateCallback = useCallback(({ data, error }) => {
140
+ if (error) {
141
+ showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
142
+ return;
143
+ }
144
+ if (data) {
145
+ const isCreated = isCreatedOrUpdated(data);
146
+ showToast(isCreated
147
+ ? t("messagesDiscountCodeCreated")
148
+ : t("messagesDiscountCodeUpdated"), TOAST_VARIANT.SUCCESS);
149
+ // `useModuleEntityV2` schedules the list refresh.
150
+ resetFormAndCloseDrawer();
151
+ }
152
+ }, [resetFormAndCloseDrawer, showToast, t]);
153
+ const byIdCallback = useCallback(({ data, error }) => {
154
+ var _a;
155
+ if (error) {
156
+ showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
157
+ return;
158
+ }
159
+ if (data) {
160
+ const record = normalizeCode(data);
161
+ dispatch({
162
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_FORM_DATA,
163
+ payload: {
164
+ form: Object.assign(Object.assign({}, record), { description: (_a = record.description) !== null && _a !== void 0 ? _a : "" }),
165
+ },
166
+ });
167
+ }
168
+ }, [dispatch, showToast, t]);
169
+ const deleteCallback = useCallback(({ data, error }) => {
170
+ if (error) {
171
+ showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
172
+ return;
173
+ }
174
+ if (data) {
175
+ showToast(t("messagesDiscountCodeDeleted"), TOAST_VARIANT.SUCCESS);
176
+ }
177
+ }, [showToast, t]);
178
+ const { byIdFetchNow, byIdLoading, deleteFetchNow, deleteLoading, listError, listFetchNow, listLoading, updateFetchNow, updateLoading, } = useModuleEntityV2({
179
+ byIdCallback,
180
+ byIdParams,
181
+ deleteCallback,
182
+ deleteParams,
183
+ listCallback,
184
+ listParams,
185
+ listUrl: DISCOUNT_CODE_API_ROUTES.UNIT,
186
+ searchQuery: debouncedQuery,
187
+ unitByIdUrl: DISCOUNT_CODE_API_ROUTES.UNIT,
188
+ unitUrl: DISCOUNT_CODE_API_ROUTES.UNIT,
189
+ updateCallback,
190
+ updateParams,
191
+ headers: { "Content-Type": "application/json" },
192
+ });
193
+ // ---------------------------------------------------------------------------
194
+ // Handlers
195
+ // ---------------------------------------------------------------------------
196
+ const handleChange = useCallback((key, value) => {
197
+ dispatch({
198
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_ERRORS,
199
+ payload: { errors: {} },
200
+ });
201
+ dispatch({
202
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
203
+ payload: { disabled: false },
204
+ });
205
+ dispatch({
206
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_INPUT_FIELD,
207
+ payload: { key, value },
208
+ });
209
+ }, [dispatch]);
210
+ const closeDrawer = useCallback(() => {
211
+ resetFormAndCloseDrawer();
212
+ }, [resetFormAndCloseDrawer]);
213
+ const handlePageChange = useCallback((page) => {
214
+ const nextPage = typeof page === "number" ? page : state.currentPage + 1;
215
+ dispatch({
216
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_CURRENT_PAGE,
217
+ payload: { currentPage: nextPage },
218
+ });
219
+ }, [dispatch, state.currentPage]);
220
+ const handlePageLimitChange = useCallback((_k, value) => {
221
+ const val = Object.assign({}, value);
222
+ dispatch({
223
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_PAGE_LIMIT,
224
+ payload: { pageLimit: Number(val.option) },
225
+ });
226
+ dispatch({
227
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_CURRENT_PAGE,
228
+ payload: { currentPage: 1 },
229
+ });
230
+ }, [dispatch]);
231
+ const handleView = useCallback((row) => {
232
+ byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
233
+ dispatch({
234
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DRAWER,
235
+ payload: { drawer: DISCOUNT_CODE_DRAWER.VIEW_DRAWER },
236
+ });
237
+ }, [byIdFetchNow, dispatch]);
238
+ const handleEdit = useCallback((row) => {
239
+ byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
240
+ dispatch({
241
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DRAWER,
242
+ payload: { drawer: DISCOUNT_CODE_DRAWER.FORM_DRAWER },
243
+ });
244
+ }, [byIdFetchNow, dispatch]);
245
+ const handleCreate = useCallback(() => {
246
+ resetFormFields();
247
+ dispatch({
248
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DRAWER,
249
+ payload: { drawer: DISCOUNT_CODE_DRAWER.FORM_DRAWER },
250
+ });
251
+ }, [dispatch, resetFormFields]);
252
+ const handleDelete = useCallback((row) => {
253
+ if (!confirm(t("messagesDeleteConfirmation")))
254
+ return;
255
+ deleteFetchNow === null || deleteFetchNow === void 0 ? void 0 : deleteFetchNow(undefined, {
256
+ body: JSON.stringify({ id: row === null || row === void 0 ? void 0 : row.id, schoolId }),
257
+ });
258
+ }, [deleteFetchNow, schoolId, t]);
259
+ const handleFilters = useCallback(() => {
260
+ dispatch({
261
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DRAWER,
262
+ payload: { drawer: DISCOUNT_CODE_DRAWER.FILTER_DRAWER },
263
+ });
264
+ }, [dispatch]);
265
+ const clearSearch = useCallback(() => {
266
+ dispatch({
267
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_SEARCH_QUERY,
268
+ payload: { searchQuery: "" },
269
+ });
270
+ }, [dispatch]);
271
+ const handleSearch = useCallback((query) => {
272
+ dispatch({
273
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_SEARCH_QUERY,
274
+ payload: { searchQuery: query },
275
+ });
276
+ }, [dispatch]);
277
+ const applyFilters = useCallback(() => {
278
+ dispatch({
279
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_FILTERS,
280
+ payload: {
281
+ filters: {
282
+ appliedFilterEnabled: state.filterEnabled,
283
+ appliedFilterDiscountType: state.filterDiscountType,
284
+ },
285
+ },
286
+ });
287
+ dispatch({
288
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_CURRENT_PAGE,
289
+ payload: { currentPage: 1 },
290
+ });
291
+ closeDrawer();
292
+ }, [closeDrawer, dispatch, state.filterDiscountType, state.filterEnabled]);
293
+ const clearFilters = useCallback(() => {
294
+ dispatch({ type: DISCOUNT_CODE_ACTION_TYPES.RESET_FORM });
295
+ dispatch({
296
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_CURRENT_PAGE,
297
+ payload: { currentPage: 1 },
298
+ });
299
+ }, [dispatch]);
300
+ // ---------------------------------------------------------------------------
301
+ // Submit
302
+ // ---------------------------------------------------------------------------
303
+ const handleSubmit = useCallback(() => {
304
+ dispatch({
305
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
306
+ payload: { disabled: true },
307
+ });
308
+ validateForm({
309
+ params: updateParams,
310
+ schema: accountDiscountCodeFormValidation,
311
+ successCallback: () => {
312
+ const { id } = updateParams, createParams = __rest(updateParams, ["id"]);
313
+ updateFetchNow(undefined, {
314
+ body: JSON.stringify(id ? updateParams : createParams),
315
+ });
316
+ },
317
+ errorCallback: (errors) => {
318
+ dispatch({
319
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
320
+ payload: { disabled: false },
321
+ });
322
+ dispatch({
323
+ type: DISCOUNT_CODE_ACTION_TYPES.SET_ERRORS,
324
+ payload: { errors },
325
+ });
326
+ showToast(t("messagesValidationError"), TOAST_VARIANT.ERROR);
327
+ },
328
+ });
329
+ }, [dispatch, showToast, t, updateFetchNow, updateParams]);
330
+ // ---------------------------------------------------------------------------
331
+ // Header & row actions
332
+ // ---------------------------------------------------------------------------
333
+ const headerActions = useMemo(() => [
334
+ {
335
+ enabled: true,
336
+ handleOnClick: handleFilters,
337
+ label: t("actionsButtonFilters"),
338
+ order: 1,
339
+ },
340
+ {
341
+ enabled: true,
342
+ handleOnClick: handleCreate,
343
+ label: t("actionsButtonAdd"),
344
+ order: 2,
345
+ },
346
+ ], [handleCreate, handleFilters, t]);
347
+ const rowActions = useMemo(() => [
348
+ {
349
+ enabled: true,
350
+ handleOnClick: handleView,
351
+ label: t("actionsButtonView"),
352
+ order: 1,
353
+ },
354
+ {
355
+ enabled: true,
356
+ handleOnClick: handleEdit,
357
+ label: t("actionsButtonEdit"),
358
+ order: 2,
359
+ },
360
+ {
361
+ enabled: true,
362
+ handleOnClick: handleDelete,
363
+ label: t("actionsButtonDelete"),
364
+ order: 3,
365
+ variant: "destructive",
366
+ },
367
+ ], [handleDelete, handleEdit, handleView, t]);
368
+ // ---------------------------------------------------------------------------
369
+ // Effects
370
+ // ---------------------------------------------------------------------------
371
+ useEffect(() => {
372
+ listFetchNowRef.current = listFetchNow;
373
+ }, [listFetchNow]);
374
+ useEffect(() => {
375
+ var _a;
376
+ if (!(workspace === null || workspace === void 0 ? void 0 : workspace.id))
377
+ return;
378
+ (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
379
+ }, [listParams, workspace === null || workspace === void 0 ? void 0 : workspace.id]);
380
+ return Object.assign(Object.assign({}, context), { applyFilters,
381
+ byIdLoading,
382
+ clearFilters,
383
+ clearSearch,
384
+ closeDrawer,
385
+ deleteLoading,
386
+ handleChange,
387
+ handleCreate,
388
+ handleDelete,
389
+ handleEdit,
390
+ handleFilters,
391
+ handlePageChange,
392
+ handlePageLimitChange,
393
+ handleSearch,
394
+ handleSubmit,
395
+ handleView,
396
+ headerActions,
397
+ listError,
398
+ listFetchNow,
399
+ listLoading,
400
+ rowActions,
401
+ updateLoading });
402
+ };