@appcorp/fusion-storybook 0.5.7 → 0.5.11

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.
@@ -1,36 +1,20 @@
1
1
  "use client";
2
2
  /**
3
- * Attendance Module — business logic + API integration
3
+ * Attendance Module — configuration + provider.
4
4
  *
5
- * This module wires the generic module state (created by
6
- * `createGenericModule`) to network actions using `useModuleEntityV2`.
7
- * It contains the domain-specific handlers (create/view/edit/delete),
8
- * local validation wiring, and optimistic UI helpers.
9
- *
10
- * Key responsibilities:
11
- * - expose `useAttendanceModule()` which UI components call for actions
12
- * - keep the module-specific `apiParams` and callbacks in one place
13
- * - ensure cache invalidation and toast notifications on mutation
5
+ * `createGenericModule` owns the reducer/state; the business logic lives in
6
+ * `context/use-attendance-module.ts` and is re-exported from here so
7
+ * components keep importing from `./context`.
14
8
  *
15
9
  * Exported utilities:
16
10
  * - `AttendanceProvider` — provider component used by the page
17
11
  * - `useAttendanceModule()` — hook that returns handlers and state
18
12
  */
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
13
  import { createGenericModule } from "@react-pakistan/util-functions/factory/generic-module-factory";
27
14
  import { DRAWER_TYPES } from "@react-pakistan/util-functions/factory/generic-component-factory";
28
15
  import { pageLimit } from "./constants";
29
- import { ATTENDANCE_API_ROUTES } from "../../constants";
30
- import { attendanceFormValidation } from "./validate";
31
- import { generateThemeToast, TOAST_VARIANT, } from "@appcorp/shadcn/lib/toast-utils";
32
16
  import { ATTENDANCE_STATUS, } from "../../type";
33
- import { getCachedWorkspaceSync } from "../workspace/cache";
17
+ import { toDateInput } from "./date";
34
18
  // ============================================================================
35
19
  // 1.1 DRAWER TYPES
36
20
  // ============================================================================
@@ -40,6 +24,9 @@ export const ATTENDANCE_DRAWER = {
40
24
  MORE_ACTIONS_DRAWER: DRAWER_TYPES.MORE_ACTIONS_DRAWER,
41
25
  VIEW_DRAWER: DRAWER_TYPES.VIEW_DRAWER,
42
26
  };
27
+ // ============================================================================
28
+ // 1.2 MODULE CONFIGURATION
29
+ // ============================================================================
43
30
  const attendanceConfig = {
44
31
  name: "Attendance",
45
32
  displayName: "Attendance",
@@ -56,10 +43,19 @@ const attendanceConfig = {
56
43
  disableSaveButton: false,
57
44
  drawer: null,
58
45
  // Form State
59
- date: new Date().toISOString().split("T")[0],
46
+ date: toDateInput(new Date()),
60
47
  enabled: true,
61
48
  errors: {},
62
- filterEnabled: undefined,
49
+ // Staged filters: the drawer edits `filter*`; Apply copies them to
50
+ // `appliedFilter*`, which is what the list request uses.
51
+ filterEnabled: true,
52
+ filterStatus: undefined,
53
+ filterStartDate: undefined,
54
+ filterEndDate: undefined,
55
+ appliedFilterEnabled: true,
56
+ appliedFilterStatus: undefined,
57
+ appliedFilterStartDate: undefined,
58
+ appliedFilterEndDate: undefined,
63
59
  id: "",
64
60
  remarks: "",
65
61
  schoolId: "",
@@ -77,356 +73,6 @@ export const { actionTypes: ATTENDANCE_ACTION_TYPES, config: attendanceModuleCon
77
73
  // ============================================================================
78
74
  // 1.4 ENHANCED ATTENDANCE HOOK WITH API INTEGRATION
79
75
  // ============================================================================
80
- export const useAttendanceModule = () => {
81
- var _a, _b;
82
- const context = useAttendanceContext();
83
- const { dispatch } = context;
84
- const state = context.state;
85
- // ==========================================================================
86
- // 1.4.1 STATE & CORE HOOKS
87
- // ==========================================================================
88
- const t = useTranslations("attendance");
89
- const { theme } = useTheme();
90
- const workspace = getCachedWorkspaceSync();
91
- const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
92
- const listFetchNowRef = useRef(null);
93
- const debouncedQuery = useDebounce(state.searchQuery, 800);
94
- // ==========================================================================
95
- // 1.4.2 API PARAMETERS
96
- // ==========================================================================
97
- const listParams = useMemo(() => (Object.assign(Object.assign({ currentPage: state.currentPage, pageLimit: state.pageLimit, schoolId }, (debouncedQuery ? { searchQuery: debouncedQuery } : {})), (state.filterEnabled !== undefined
98
- ? { filterEnabled: String(state.filterEnabled) }
99
- : {}))), [
100
- state.currentPage,
101
- state.filterEnabled,
102
- state.pageLimit,
103
- debouncedQuery,
104
- schoolId,
105
- ]);
106
- const updateParams = useMemo(() => ({
107
- date: state.date,
108
- enabled: state.enabled,
109
- id: state.id,
110
- remarks: state.remarks,
111
- schoolId,
112
- status: state.status,
113
- studentProfileId: state.studentProfileId,
114
- }), [state, schoolId]);
115
- const byIdParams = useMemo(() => ({ id: state.id }), [state.id]);
116
- const deleteParams = useMemo(() => ({ id: state.id }), [state.id]);
117
- // ==========================================================================
118
- // 1.4.3 UTILITIES
119
- // ==========================================================================
120
- const showToast = useCallback((description, variant) => {
121
- generateThemeToast({
122
- description,
123
- theme: theme,
124
- variant,
125
- });
126
- }, [theme]);
127
- const resetFormAndCloseDrawer = useCallback(() => {
128
- dispatch({ type: ATTENDANCE_ACTION_TYPES.RESET_FORM });
129
- dispatch({
130
- type: ATTENDANCE_ACTION_TYPES.SET_ERRORS,
131
- payload: { errors: {} },
132
- });
133
- dispatch({
134
- type: ATTENDANCE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
135
- payload: { disabled: false },
136
- });
137
- dispatch({
138
- type: ATTENDANCE_ACTION_TYPES.SET_DRAWER,
139
- payload: { drawer: null },
140
- });
141
- }, [dispatch]);
142
- // ==========================================================================
143
- // 1.4.4 API CALLBACKS
144
- // ==========================================================================
145
- const listCallback = useCallback(({ data, error }) => {
146
- var _a;
147
- if (error) {
148
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
149
- return;
150
- }
151
- if (data) {
152
- const response = data;
153
- dispatch({
154
- type: ATTENDANCE_ACTION_TYPES.SET_ITEMS,
155
- payload: {
156
- items: (_a = response.items) !== null && _a !== void 0 ? _a : [],
157
- count: typeof response.count === "number" ? response.count : 0,
158
- },
159
- });
160
- }
161
- }, [dispatch, showToast, t]);
162
- const updateCallback = useCallback(({ data, error }) => {
163
- var _a;
164
- if (error) {
165
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
166
- return;
167
- }
168
- if (data) {
169
- showToast(isCreatedOrUpdated(data)
170
- ? t("messagesAttendanceCreated")
171
- : t("messagesAttendanceUpdated"), TOAST_VARIANT.SUCCESS);
172
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
173
- resetFormAndCloseDrawer();
174
- }
175
- }, [resetFormAndCloseDrawer, showToast, t]);
176
- const byIdCallback = useCallback(({ data, error }) => {
177
- if (error) {
178
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
179
- return;
180
- }
181
- if (data) {
182
- dispatch({
183
- type: ATTENDANCE_ACTION_TYPES.SET_FORM_DATA,
184
- payload: { form: Object.assign(Object.assign({}, data), { filterEnabled: undefined }) },
185
- });
186
- }
187
- }, [dispatch, showToast, t]);
188
- const deleteCallback = useCallback(({ data, error }) => {
189
- var _a;
190
- if (error) {
191
- showToast(t("messagesNetworkError"), TOAST_VARIANT.ERROR);
192
- return;
193
- }
194
- if (data) {
195
- showToast(t("messagesAttendanceDeleted"), TOAST_VARIANT.SUCCESS);
196
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
197
- }
198
- }, [showToast, t]);
199
- // ==========================================================================
200
- // 1.4.5 API HOOKS
201
- // ==========================================================================
202
- const { listFetchNow, listLoading, updateFetchNow, updateLoading, byIdFetchNow, deleteFetchNow, deleteLoading, byIdLoading, } = useModuleEntityV2({
203
- byIdCallback,
204
- byIdParams,
205
- deleteCallback,
206
- deleteParams,
207
- listCallback,
208
- listParams,
209
- listUrl: ATTENDANCE_API_ROUTES.UNIT,
210
- searchQuery: debouncedQuery,
211
- unitByIdUrl: ATTENDANCE_API_ROUTES.UNIT,
212
- unitUrl: ATTENDANCE_API_ROUTES.UNIT,
213
- updateCallback,
214
- updateParams,
215
- headers: {
216
- "Content-Type": "application/json",
217
- // "x-api-token": process.env.NEXT_PUBLIC_API_KEY!,
218
- },
219
- });
220
- // ==========================================================================
221
- // 1.4.6 HANDLERS
222
- // ==========================================================================
223
- const handleChange = useCallback((field, value) => {
224
- dispatch({
225
- type: ATTENDANCE_ACTION_TYPES.SET_ERRORS,
226
- payload: { errors: {} },
227
- });
228
- dispatch({
229
- type: ATTENDANCE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
230
- payload: { disabled: false },
231
- });
232
- dispatch({
233
- type: ATTENDANCE_ACTION_TYPES.SET_INPUT_FIELD,
234
- payload: { key: field, value },
235
- });
236
- }, [dispatch]);
237
- const handlePageChange = useCallback((pageOrEvent) => {
238
- const page = typeof pageOrEvent === "number" && !isNaN(pageOrEvent)
239
- ? pageOrEvent
240
- : state.currentPage + 1;
241
- dispatch({
242
- type: ATTENDANCE_ACTION_TYPES.SET_CURRENT_PAGE,
243
- payload: { currentPage: page },
244
- });
245
- }, [dispatch, state.currentPage]);
246
- const handlePageLimitChange = useCallback((k, value) => {
247
- const val = Object.assign({}, value);
248
- dispatch({
249
- type: ATTENDANCE_ACTION_TYPES.SET_PAGE_LIMIT,
250
- payload: { pageLimit: Number(val.option) },
251
- });
252
- dispatch({
253
- type: ATTENDANCE_ACTION_TYPES.SET_CURRENT_PAGE,
254
- payload: { currentPage: 1 },
255
- });
256
- }, [dispatch]);
257
- const closeDrawer = useCallback(() => {
258
- resetFormAndCloseDrawer();
259
- }, [resetFormAndCloseDrawer]);
260
- const handleCreate = useCallback(() => {
261
- dispatch({
262
- type: ATTENDANCE_ACTION_TYPES.SET_DRAWER,
263
- payload: { drawer: ATTENDANCE_DRAWER.FORM_DRAWER },
264
- });
265
- }, [dispatch]);
266
- const handleFilters = useCallback(() => {
267
- dispatch({
268
- type: ATTENDANCE_ACTION_TYPES.SET_DRAWER,
269
- payload: { drawer: ATTENDANCE_DRAWER.FILTER_DRAWER },
270
- });
271
- }, [dispatch]);
272
- const handleMoreActions = useCallback(() => {
273
- dispatch({
274
- type: ATTENDANCE_ACTION_TYPES.SET_DRAWER,
275
- payload: { drawer: ATTENDANCE_DRAWER.MORE_ACTIONS_DRAWER },
276
- });
277
- }, [dispatch]);
278
- const handleSearch = useCallback((query) => {
279
- var _a;
280
- dispatch({
281
- type: ATTENDANCE_ACTION_TYPES.SET_SEARCH_QUERY,
282
- payload: { searchQuery: query, schoolId: ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "" },
283
- });
284
- }, [dispatch, (_b = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _b === void 0 ? void 0 : _b.id]);
285
- const clearFilters = useCallback(() => {
286
- dispatch({
287
- type: ATTENDANCE_ACTION_TYPES.RESET_FORM,
288
- });
289
- }, [dispatch]);
290
- const clearSearch = useCallback(() => {
291
- dispatch({
292
- type: ATTENDANCE_ACTION_TYPES.SET_SEARCH_QUERY,
293
- payload: { searchQuery: "" },
294
- });
295
- }, [dispatch]);
296
- const handleView = useCallback((row) => {
297
- byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
298
- dispatch({
299
- type: ATTENDANCE_ACTION_TYPES.SET_DRAWER,
300
- payload: { drawer: ATTENDANCE_DRAWER.VIEW_DRAWER },
301
- });
302
- }, [byIdFetchNow, dispatch]);
303
- const handleEdit = useCallback((row) => {
304
- byIdFetchNow === null || byIdFetchNow === void 0 ? void 0 : byIdFetchNow(undefined, { params: { id: row === null || row === void 0 ? void 0 : row.id } });
305
- dispatch({
306
- type: ATTENDANCE_ACTION_TYPES.SET_DRAWER,
307
- payload: { drawer: ATTENDANCE_DRAWER.FORM_DRAWER },
308
- });
309
- }, [byIdFetchNow, dispatch]);
310
- const handleDelete = useCallback((row) => {
311
- if (!confirm(t("messagesDeleteConfirmation")))
312
- return;
313
- deleteFetchNow === null || deleteFetchNow === void 0 ? void 0 : deleteFetchNow(undefined, {
314
- body: JSON.stringify({ id: row === null || row === void 0 ? void 0 : row.id }),
315
- });
316
- }, [deleteFetchNow, t]);
317
- // ==========================================================================
318
- // 1.4.7 NETWORK ACTIONS
319
- // ==========================================================================
320
- const handleSubmit = useCallback(() => {
321
- dispatch({
322
- type: ATTENDANCE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
323
- payload: { disabled: true },
324
- });
325
- validateForm({
326
- params: updateParams,
327
- schema: attendanceFormValidation,
328
- successCallback: () => {
329
- updateFetchNow(undefined, {
330
- body: JSON.stringify(Object.assign(Object.assign({}, updateParams), { markedBy: "" })),
331
- });
332
- },
333
- errorCallback: (errors) => {
334
- dispatch({
335
- type: ATTENDANCE_ACTION_TYPES.SET_ERRORS,
336
- payload: { errors },
337
- });
338
- dispatch({
339
- type: ATTENDANCE_ACTION_TYPES.SET_DISABLE_SAVE_BUTTON,
340
- payload: { disabled: false },
341
- });
342
- showToast(t("messagesFormErrors"), TOAST_VARIANT.ERROR);
343
- },
344
- });
345
- }, [dispatch, updateParams, updateFetchNow, showToast, t]);
346
- // ==========================================================================
347
- // 1.4.8 HEADER & ROW ACTIONS
348
- // ==========================================================================
349
- const headerActions = useMemo(() => [
350
- {
351
- enabled: true,
352
- handleOnClick: handleMoreActions,
353
- label: t("actionsButtonMoreActions"),
354
- order: 0,
355
- },
356
- {
357
- enabled: true,
358
- handleOnClick: handleFilters,
359
- label: t("actionsButtonFilters"),
360
- order: 1,
361
- },
362
- {
363
- enabled: true,
364
- handleOnClick: handleCreate,
365
- label: t("actionsButtonAdd"),
366
- order: 2,
367
- },
368
- ], [handleCreate, handleFilters, handleMoreActions, t]);
369
- const rowActions = useMemo(() => [
370
- {
371
- enabled: true,
372
- handleOnClick: handleView,
373
- label: t("actionsButtonView"),
374
- order: 0,
375
- },
376
- {
377
- enabled: true,
378
- handleOnClick: handleEdit,
379
- label: t("actionsButtonEdit"),
380
- order: 1,
381
- },
382
- {
383
- enabled: false,
384
- handleOnClick: handleDelete,
385
- label: t("actionsButtonDelete"),
386
- order: 3,
387
- variant: "destructive",
388
- },
389
- ], [handleDelete, handleEdit, handleView, t]);
390
- const applyFilters = useCallback(() => {
391
- dispatch({
392
- type: ATTENDANCE_ACTION_TYPES.SET_CURRENT_PAGE,
393
- payload: { currentPage: 1 },
394
- });
395
- closeDrawer();
396
- }, [dispatch, closeDrawer]);
397
- // ==========================================================================
398
- // 1.4.9 EFFECTS
399
- // ==========================================================================
400
- useEffect(() => {
401
- listFetchNowRef.current = listFetchNow;
402
- }, [listFetchNow]);
403
- useEffect(() => {
404
- var _a;
405
- (_a = listFetchNowRef.current) === null || _a === void 0 ? void 0 : _a.call(listFetchNowRef);
406
- }, [listParams]);
407
- // ==========================================================================
408
- // 1.4.10 RETURN
409
- // ==========================================================================
410
- return Object.assign(Object.assign({}, context), { applyFilters,
411
- byIdLoading,
412
- clearFilters,
413
- clearSearch,
414
- closeDrawer,
415
- deleteLoading,
416
- handleChange,
417
- handleCreate,
418
- handleDelete,
419
- handleEdit,
420
- handleFilters,
421
- handleMoreActions,
422
- handlePageChange,
423
- handlePageLimitChange,
424
- handleSearch,
425
- handleSubmit,
426
- handleView,
427
- headerActions,
428
- listFetchNow,
429
- listLoading,
430
- rowActions,
431
- updateLoading });
432
- };
76
+ // Re-exported for the page/components; the implementation lives in
77
+ // `context/use-attendance-module.ts` so it stays unit-testable.
78
+ export { useAttendanceModule } from "./context/use-attendance-module";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Attendance dates are calendar days stored at UTC midnight (the API and both
3
+ * workers normalise them the same way). Formatting them with the local
4
+ * timezone shifts the day in negative-offset zones, so these helpers always use
5
+ * UTC components.
6
+ */
7
+ /** `YYYY-MM-DD` for `<input type="date">`; empty string when invalid. */
8
+ export declare const toDateInput: (value?: string | Date | null) => string;
9
+ /** Locale date without the timezone shift (e.g. `6/3/2024`). */
10
+ export declare const formatAttendanceDate: (value?: string | Date | null) => string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Attendance dates are calendar days stored at UTC midnight (the API and both
3
+ * workers normalise them the same way). Formatting them with the local
4
+ * timezone shifts the day in negative-offset zones, so these helpers always use
5
+ * UTC components.
6
+ */
7
+ /** `YYYY-MM-DD` for `<input type="date">`; empty string when invalid. */
8
+ export const toDateInput = (value) => {
9
+ if (!value)
10
+ return "";
11
+ const date = new Date(value);
12
+ if (Number.isNaN(date.getTime()))
13
+ return "";
14
+ return date.toISOString().slice(0, 10);
15
+ };
16
+ /** Locale date without the timezone shift (e.g. `6/3/2024`). */
17
+ export const formatAttendanceDate = (value) => {
18
+ const day = toDateInput(value);
19
+ if (!day)
20
+ return "—";
21
+ const [year, month, date] = day.split("-").map(Number);
22
+ return new Date(Date.UTC(year, month - 1, date)).toLocaleDateString(undefined, { timeZone: "UTC" });
23
+ };
@@ -1,23 +1,39 @@
1
1
  "use client";
2
- import { jsx as _jsx } from "react/jsx-runtime";
3
- import { useAttendanceModule } from "./context";
4
- import { EnhancedRadio } from "@appcorp/shadcn/components/enhanced-radio";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
5
3
  import { useTranslations } from "next-intl";
4
+ import { EnhancedCombobox } from "@appcorp/shadcn/components/enhanced-combobox";
5
+ import { EnhancedInput } from "@appcorp/shadcn/components/enhanced-input";
6
+ import { EnhancedRadio } from "@appcorp/shadcn/components/enhanced-radio";
7
+ import { useAttendanceModule } from "./context";
8
+ import { ATTENDANCE_STATUS_OPTIONS } from "./constants";
6
9
  export const AttendanceFilter = () => {
7
10
  const t = useTranslations("attendance");
8
11
  const { state, handleChange } = useAttendanceModule();
9
- const { filterEnabled } = state;
12
+ const { filterEnabled, filterStatus, filterStartDate, filterEndDate } = state;
13
+ const statusLabelMap = {
14
+ PRESENT: t("formOptionPresent"),
15
+ ABSENT: t("formOptionAbsent"),
16
+ LATE: t("formOptionLate"),
17
+ EXCUSED: t("formOptionExcused"),
18
+ HALF_DAY: t("formOptionHalfDay"),
19
+ };
10
20
  const filterEnabledValue = filterEnabled === undefined
11
21
  ? "undefined"
12
22
  : filterEnabled
13
23
  ? "true"
14
24
  : "false";
15
- 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: [
25
+ return (_jsxs("div", { className: "space-y-4", children: [_jsx(EnhancedCombobox, { emptyText: t("filterStatusEmpty"), id: "filterStatus", info: t("filterStatusInfo"), label: t("filterStatusLabel"), onValueChange: (value) => handleChange("filterStatus", value), options: [
26
+ { label: t("filterOptionAll"), value: "" },
27
+ ...ATTENDANCE_STATUS_OPTIONS.map((opt) => ({
28
+ value: opt.value,
29
+ label: statusLabelMap[opt.value] || opt.label,
30
+ })),
31
+ ], placeholder: t("filterStatusPlaceholder"), searchPlaceholder: t("filterStatusSearchPlaceholder"), value: filterStatus !== null && filterStatus !== void 0 ? filterStatus : "" }), _jsxs("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2", children: [_jsx(EnhancedInput, { id: "filterStartDate", info: t("filterStartDateInfo"), label: t("filterStartDateLabel"), max: filterEndDate || undefined, onChange: (e) => handleChange("filterStartDate", e.target.value), onClick: (e) => { var _a, _b; return (_b = (_a = e.currentTarget).showPicker) === null || _b === void 0 ? void 0 : _b.call(_a); }, type: "date", value: filterStartDate !== null && filterStartDate !== void 0 ? filterStartDate : "" }), _jsx(EnhancedInput, { id: "filterEndDate", info: t("filterEndDateInfo"), label: t("filterEndDateLabel"), min: filterStartDate || undefined, onChange: (e) => handleChange("filterEndDate", e.target.value), onClick: (e) => { var _a, _b; return (_b = (_a = e.currentTarget).showPicker) === null || _b === void 0 ? void 0 : _b.call(_a); }, type: "date", value: filterEndDate !== null && filterEndDate !== void 0 ? filterEndDate : "" })] }), _jsx(EnhancedRadio, { label: t("filterRecordStateLabel"), name: "filterEnabled", value: filterEnabledValue, options: [
16
32
  { label: t("filterOptionAll"), value: "undefined" },
17
33
  { label: t("filterOptionEnabled"), value: "true" },
18
34
  { label: t("filterOptionDisabled"), value: "false" },
19
35
  ], onValueChange: (next) => {
20
36
  const parsed = next === "true" ? true : next === "false" ? false : undefined;
21
37
  handleChange("filterEnabled", parsed);
22
- } }) }) }));
38
+ } })] }));
23
39
  };
@@ -1,26 +1,45 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useMemo } from "react";
4
+ import { useTranslations } from "next-intl";
3
5
  import { EnhancedCheckbox } from "@appcorp/shadcn/components/enhanced-checkbox";
6
+ import { EnhancedCombobox } from "@appcorp/shadcn/components/enhanced-combobox";
4
7
  import { useEnhancedCombobox } from "@appcorp/shadcn/hooks/use-enhanced-combobox";
5
8
  import { EnhancedInput } from "@appcorp/shadcn/components/enhanced-input";
6
9
  import { EnhancedTextarea } from "@appcorp/shadcn/components/enhanced-textarea";
7
- import { useAttendanceModule } from "./context";
8
- import { ATTENDANCE_STATUS_OPTIONS } from "./constants";
9
- import { ATTENDANCE_API_ROUTES, STUDENT_PROFILE_API_ROUTES, } from "../../constants";
10
- import { useTranslations } from "next-intl";
11
10
  import { useFetch } from "@react-pakistan/util-functions/hooks/use-fetch";
12
11
  import { API_METHODS } from "@react-pakistan/util-functions/constants/api-methods";
12
+ import { useAttendanceModule } from "./context";
13
+ import { ATTENDANCE_STATUS_OPTIONS } from "./constants";
14
+ import { STUDENT_PROFILE_API_ROUTES } from "../../constants";
13
15
  import { getCachedWorkspaceSync } from "../workspace/cache";
14
- import { useEffect } from "react";
16
+ import { getTranslatedError } from "../../utils/get-translated-error";
17
+ /**
18
+ * `Name — computerNumber` (or the student code) so two students with the same
19
+ * name are still distinguishable.
20
+ */
21
+ const formatStudent = (profile) => {
22
+ var _a, _b, _c, _d, _e;
23
+ const name = `${(_b = (_a = profile.familyMember) === null || _a === void 0 ? void 0 : _a.firstName) !== null && _b !== void 0 ? _b : ""} ${(_d = (_c = profile.familyMember) === null || _c === void 0 ? void 0 : _c.lastName) !== null && _d !== void 0 ? _d : ""}`.trim();
24
+ const rawNumber = (_e = profile.computerNumber) !== null && _e !== void 0 ? _e : "";
25
+ const number = rawNumber.split(":")[1] || rawNumber;
26
+ return [name, number].filter(Boolean).join(" — ") || profile.studentCode;
27
+ };
15
28
  export const AttendanceForm = () => {
16
29
  var _a, _b, _c;
17
30
  const workspace = getCachedWorkspaceSync();
18
31
  const { state, handleChange } = useAttendanceModule();
19
32
  const { date, enabled, errors, remarks, status, studentProfileId } = state;
20
33
  const t = useTranslations("attendance");
34
+ // First page of students for the picker; typing falls back to the remote
35
+ // search below.
21
36
  const { fetchNow, data: studentProfileData } = useFetch(STUDENT_PROFILE_API_ROUTES.UNIT, {
22
37
  method: API_METHODS.GET,
23
- params: { schoolId: (_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id },
38
+ params: {
39
+ filterEnabled: "true",
40
+ pageLimit: 100,
41
+ schoolId: (_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id,
42
+ },
24
43
  });
25
44
  useEffect(() => {
26
45
  var _a;
@@ -29,6 +48,20 @@ export const AttendanceForm = () => {
29
48
  }
30
49
  // eslint-disable-next-line react-hooks/exhaustive-deps
31
50
  }, [(_b = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _b === void 0 ? void 0 : _b.id]);
51
+ const studentOptions = useMemo(() => {
52
+ var _a;
53
+ const items = ((_a = studentProfileData === null || studentProfileData === void 0 ? void 0 : studentProfileData.items) !== null && _a !== void 0 ? _a : []);
54
+ const merged = [...items];
55
+ // The edited record's student may not be in the first page.
56
+ if (state.studentProfile &&
57
+ !merged.some((item) => { var _a; return item.id === ((_a = state.studentProfile) === null || _a === void 0 ? void 0 : _a.id); })) {
58
+ merged.unshift(state.studentProfile);
59
+ }
60
+ return merged.map((profile) => ({
61
+ value: profile.id,
62
+ label: formatStudent(profile),
63
+ }));
64
+ }, [studentProfileData, state.studentProfile]);
32
65
  const attendanceStatusLabelMap = {
33
66
  PRESENT: t("formOptionPresent"),
34
67
  ABSENT: t("formOptionAbsent"),
@@ -36,55 +69,33 @@ export const AttendanceForm = () => {
36
69
  EXCUSED: t("formOptionExcused"),
37
70
  HALF_DAY: t("formOptionHalfDay"),
38
71
  };
39
- const { enhancedComboboxElement: statusCombo } = useEnhancedCombobox({
40
- id: "status",
41
- info: t("formStatusInfo"),
42
- label: t("formStatusLabel"),
43
- onValueChange: (value) => handleChange("status", value),
44
- options: ATTENDANCE_STATUS_OPTIONS.map((opt) => ({
72
+ // Fixed enum — do not attach a remote search here (it would replace the
73
+ // statuses with attendance rows).
74
+ const statusCombo = (_jsx(EnhancedCombobox, { emptyText: t("formNoStatusEmpty"), error: getTranslatedError({ errors, key: "status", t }), id: "status", info: t("formStatusInfo"), label: t("formStatusLabel"), onValueChange: (value) => handleChange("status", value), options: ATTENDANCE_STATUS_OPTIONS.map((opt) => ({
45
75
  value: opt.value,
46
76
  label: attendanceStatusLabelMap[opt.value] || opt.label,
47
- })),
48
- placeholder: t("formStatusPlaceholder"),
49
- required: true,
50
- searchEndpoint: ATTENDANCE_API_ROUTES.UNIT,
51
- searchPlaceholder: t("formSearchStatusPlaceholder"),
52
- emptyText: t("formNoStatusEmpty"),
53
- formatSearchResult: (item) => {
54
- var _a, _b;
55
- return ({
56
- label: String((_a = item.label) !== null && _a !== void 0 ? _a : ""),
57
- value: String((_b = item.value) !== null && _b !== void 0 ? _b : ""),
58
- });
59
- },
60
- value: status,
61
- });
77
+ })), placeholder: t("formStatusPlaceholder"), required: true, searchPlaceholder: t("formSearchStatusPlaceholder"), value: status }));
62
78
  const { enhancedComboboxElement: studentProfile } = useEnhancedCombobox({
79
+ error: getTranslatedError({ errors, key: "studentProfileId", t }),
63
80
  id: "studentProfile",
64
81
  info: t("formStudentProfileInfo"),
65
82
  label: t("formStudentProfileLabel"),
66
83
  onValueChange: (value) => handleChange("studentProfileId", value),
67
- options: ((studentProfileData === null || studentProfileData === void 0 ? void 0 : studentProfileData.items) || []).map((opt) => {
68
- var _a, _b, _c;
69
- return ({
70
- value: opt.id,
71
- label: `${(_a = opt.familyMember) === null || _a === void 0 ? void 0 : _a.firstName} ${(_b = opt.familyMember) === null || _b === void 0 ? void 0 : _b.lastName} - ${((_c = opt.computerNumber) !== null && _c !== void 0 ? _c : "").split(":")[1] || opt.computerNumber || ""}`,
72
- });
73
- }),
84
+ options: studentOptions,
74
85
  placeholder: t("formStudentProfilePlaceholder"),
75
86
  required: true,
76
87
  searchEndpoint: STUDENT_PROFILE_API_ROUTES.UNIT,
77
88
  searchParams: { schoolId: (_c = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _c === void 0 ? void 0 : _c.id },
78
- searchPlaceholder: t("formSearchStatusPlaceholder"),
79
- emptyText: t("formNoStatusEmpty"),
89
+ searchPlaceholder: t("formSearchStudentProfilePlaceholder"),
90
+ emptyText: t("formNoStudentProfileEmpty"),
80
91
  formatSearchResult: (item) => {
81
- var _a, _b, _c;
82
- return ({
83
- label: `${((_a = item.familyMember) === null || _a === void 0 ? void 0 : _a.firstName) || ""} ${((_b = item.familyMember) === null || _b === void 0 ? void 0 : _b.lastName) || ""} - ${((_c = item.computerNumber) !== null && _c !== void 0 ? _c : "").split(":")[1] || item.computerNumber || ""}`,
84
- value: item.id,
85
- });
92
+ const profile = item;
93
+ return {
94
+ label: formatStudent(profile),
95
+ value: profile.id,
96
+ };
86
97
  },
87
98
  value: studentProfileId,
88
99
  });
89
- return (_jsxs("div", { className: "space-y-4", children: [_jsx(EnhancedInput, { error: errors.date, id: "date", info: t("formDateInfo"), label: t("formDateLabel"), onChange: (e) => handleChange("date", e.target.value), onClick: (e) => { var _a, _b; return (_b = (_a = e.currentTarget).showPicker) === null || _b === void 0 ? void 0 : _b.call(_a); }, placeholder: t("formDatePlaceholder"), required: true, type: "date", value: date }), statusCombo, studentProfile, _jsx(EnhancedTextarea, { error: errors.remarks, id: "remarks", info: t("formRemarksInfo"), label: t("formRemarksLabel"), onChange: (e) => handleChange("remarks", e.target.value), placeholder: t("formRemarksPlaceholder"), rows: 3, value: remarks !== null && remarks !== void 0 ? remarks : "" }), _jsx(EnhancedCheckbox, { defaultChecked: enabled, label: t("formActiveRecordLabel"), onCheckedChange: (checked) => handleChange("enabled", checked) })] }));
100
+ return (_jsxs("div", { className: "space-y-4", children: [_jsx(EnhancedInput, { error: getTranslatedError({ errors, key: "date", t }), id: "date", info: t("formDateInfo"), label: t("formDateLabel"), onChange: (e) => handleChange("date", e.target.value), onClick: (e) => { var _a, _b; return (_b = (_a = e.currentTarget).showPicker) === null || _b === void 0 ? void 0 : _b.call(_a); }, placeholder: t("formDatePlaceholder"), required: true, type: "date", value: date }), statusCombo, studentProfile, _jsx(EnhancedTextarea, { error: getTranslatedError({ errors, key: "remarks", t }), id: "remarks", info: t("formRemarksInfo"), label: t("formRemarksLabel"), onChange: (e) => handleChange("remarks", e.target.value), placeholder: t("formRemarksPlaceholder"), rows: 3, value: remarks !== null && remarks !== void 0 ? remarks : "" }), _jsx(EnhancedCheckbox, { checked: enabled, id: "enabled", label: t("formActiveRecordLabel"), onCheckedChange: (checked) => handleChange("enabled", checked) })] }));
90
101
  };