@appcorp/fusion-storybook 0.2.33 → 0.2.36
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.
- package/base-modules/admission/context.d.ts +1 -1
- package/base-modules/attendance/context.d.ts +2 -1
- package/base-modules/campus/context.d.ts +2 -1
- package/base-modules/campus/page.js +1 -1
- package/base-modules/class/context.d.ts +2 -1
- package/base-modules/course/context.d.ts +2 -1
- package/base-modules/discount-code/context.d.ts +2 -1
- package/base-modules/enrollment/constants.d.ts +3 -0
- package/base-modules/enrollment/constants.js +3 -0
- package/base-modules/enrollment/context.d.ts +2 -1
- package/base-modules/enrollment/context.js +1 -1
- package/base-modules/enrollment/more-actions.js +204 -26
- package/base-modules/expense/context.d.ts +2 -1
- package/base-modules/family/context.d.ts +1 -1
- package/base-modules/family-member/context.d.ts +1 -1
- package/base-modules/fee-structure/context.d.ts +2 -1
- package/base-modules/rbac/context.d.ts +2 -1
- package/base-modules/school/context.d.ts +5 -1
- package/base-modules/section/constants.d.ts +3 -0
- package/base-modules/section/constants.js +3 -0
- package/base-modules/section/context.d.ts +2 -1
- package/base-modules/section/context.js +2 -2
- package/base-modules/section/more-actions.js +202 -23
- package/base-modules/student-fee/context/shared.d.ts +1 -1
- package/base-modules/student-fee/context/use-student-fee-module.d.ts +1 -0
- package/base-modules/student-profile/context/module-base.d.ts +1 -1
- package/base-modules/student-profile/context/use-student-profile-module.d.ts +1 -0
- package/base-modules/subject/constants.d.ts +3 -0
- package/base-modules/subject/constants.js +3 -0
- package/base-modules/subject/context.d.ts +2 -1
- package/base-modules/subject/context.js +2 -2
- package/base-modules/subject/more-actions.js +202 -23
- package/base-modules/teacher/context.d.ts +2 -1
- package/base-modules/user/context/use-user-module.d.ts +1 -0
- package/base-modules/user/context.d.ts +1 -1
- package/base-modules/workspace/context.d.ts +4 -1
- package/base-modules/workspace-user/context.d.ts +1 -1
- package/package.json +2 -2
- package/tsconfig.build.tsbuildinfo +1 -1
|
@@ -1,40 +1,222 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
* Provides bulk CSV import/export actions for the section module.
|
|
7
|
-
*/
|
|
8
|
-
import { API_METHODS, downloadFromUrl } from "@react-pakistan/util-functions";
|
|
3
|
+
import { downloadFromUrl } from "@react-pakistan/util-functions";
|
|
4
|
+
import { showErrorToast, showSuccessToast, showInfoToast, } from "@appcorp/shadcn/lib/toast-utils";
|
|
9
5
|
import { getCachedWorkspaceSync } from "../workspace/cache";
|
|
10
6
|
import converter from "json-2-csv";
|
|
11
7
|
import { Timeline } from "../../components/timeline";
|
|
12
8
|
import { useTranslations } from "next-intl";
|
|
9
|
+
import { SECTION_API_ROUTES, pageLimit } from "./constants";
|
|
10
|
+
import { invalidateSectionsCache } from "./cache";
|
|
11
|
+
import { SECTION_ACTION_TYPES, useSectionContext } from "./context";
|
|
12
|
+
import { useRef, useEffect, useCallback } from "react";
|
|
13
|
+
const workspace = getCachedWorkspaceSync();
|
|
14
|
+
const POLL_INTERVAL_MS = 2000;
|
|
15
|
+
const POLL_TIMEOUT_MS = 300000;
|
|
16
|
+
const handleGetAllRecords = async (schoolId, pageLimit) => {
|
|
17
|
+
const response = await fetch(`${SECTION_API_ROUTES.UNIT}?pageLimit=${pageLimit}¤tPage=1&schoolId=${schoolId}`);
|
|
18
|
+
const result = await response.json();
|
|
19
|
+
const csv = await converter.json2csv(result.items || [], {});
|
|
20
|
+
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
|
21
|
+
await downloadFromUrl(blob, "section.csv");
|
|
22
|
+
};
|
|
23
|
+
async function submitBulkJob(csvData, method, signal) {
|
|
24
|
+
var _a;
|
|
25
|
+
const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
|
|
26
|
+
if (!schoolId)
|
|
27
|
+
throw new Error("School ID not found");
|
|
28
|
+
const res = await fetch(SECTION_API_ROUTES.BULK, {
|
|
29
|
+
method,
|
|
30
|
+
headers: {
|
|
31
|
+
"Content-Type": "application/json",
|
|
32
|
+
},
|
|
33
|
+
body: JSON.stringify({ schoolId, csvData }),
|
|
34
|
+
signal,
|
|
35
|
+
});
|
|
36
|
+
if (!res.ok) {
|
|
37
|
+
const errorData = (await res.json().catch(() => ({})));
|
|
38
|
+
throw new Error(errorData.error || `Bulk operation failed with status ${res.status}`);
|
|
39
|
+
}
|
|
40
|
+
const data = (await res.json());
|
|
41
|
+
return data.jobId;
|
|
42
|
+
}
|
|
43
|
+
async function pollBulkJob(jobId, signal, onProgress) {
|
|
44
|
+
const startTime = Date.now();
|
|
45
|
+
let lastProgressToast = 0;
|
|
46
|
+
while (true) {
|
|
47
|
+
if (signal.aborted)
|
|
48
|
+
throw new Error("Polling cancelled");
|
|
49
|
+
if (Date.now() - startTime > POLL_TIMEOUT_MS) {
|
|
50
|
+
throw new Error("Bulk operation timed out");
|
|
51
|
+
}
|
|
52
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
53
|
+
if (signal.aborted)
|
|
54
|
+
throw new Error("Polling cancelled");
|
|
55
|
+
const res = await fetch(SECTION_API_ROUTES.BULK_STATUS(jobId), {
|
|
56
|
+
signal,
|
|
57
|
+
});
|
|
58
|
+
if (!res.ok)
|
|
59
|
+
continue;
|
|
60
|
+
const data = (await res.json());
|
|
61
|
+
if (data.status === "completed" || data.status === "failed") {
|
|
62
|
+
return data;
|
|
63
|
+
}
|
|
64
|
+
// Show progress toast every 10 seconds while running
|
|
65
|
+
if (data.status === "running" && Date.now() - lastProgressToast > 10000) {
|
|
66
|
+
lastProgressToast = Date.now();
|
|
67
|
+
onProgress === null || onProgress === void 0 ? void 0 : onProgress(data.processed, data.total);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function formatErrorSummary(errors) {
|
|
72
|
+
if (!(errors === null || errors === void 0 ? void 0 : errors.length))
|
|
73
|
+
return "";
|
|
74
|
+
const lines = errors.slice(0, 5).map((e) => `Row ${e.row}: ${e.error}`);
|
|
75
|
+
const remaining = errors.length - 5;
|
|
76
|
+
if (remaining > 0)
|
|
77
|
+
lines.push(`...and ${remaining} more`);
|
|
78
|
+
return lines.join("\n");
|
|
79
|
+
}
|
|
13
80
|
export const SectionMoreActions = () => {
|
|
14
81
|
const t = useTranslations("section");
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
82
|
+
const { dispatch } = useSectionContext();
|
|
83
|
+
const abortRef = useRef(null);
|
|
84
|
+
// Abort any in-flight polling on unmount
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
return () => {
|
|
87
|
+
var _a;
|
|
88
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
89
|
+
};
|
|
90
|
+
}, []);
|
|
91
|
+
const handleBulkFlow = useCallback(async (files, method) => {
|
|
92
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
93
|
+
const closeDrawer = () => {
|
|
94
|
+
dispatch({
|
|
95
|
+
type: SECTION_ACTION_TYPES.SET_DRAWER,
|
|
96
|
+
payload: { drawer: null },
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
// Cancel previous in-flight request
|
|
100
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
101
|
+
const controller = new AbortController();
|
|
102
|
+
abortRef.current = controller;
|
|
103
|
+
const { signal } = controller;
|
|
104
|
+
const label = method === "POST" ? "create" : "update";
|
|
105
|
+
// Read + parse CSV
|
|
106
|
+
const file = files[0];
|
|
107
|
+
const text = await file.text();
|
|
108
|
+
const records = converter.csv2json(text);
|
|
109
|
+
if (!Array.isArray(records) || records.length === 0) {
|
|
110
|
+
showErrorToast("CSV file is empty or invalid");
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
// Client-side validation — basic required field check
|
|
114
|
+
const validationErrors = [];
|
|
115
|
+
for (let i = 0; i < records.length; i++) {
|
|
116
|
+
const row = records[i];
|
|
117
|
+
const msgs = [];
|
|
118
|
+
if (method === "POST") {
|
|
119
|
+
if (!((_b = row.name) === null || _b === void 0 ? void 0 : _b.trim()))
|
|
120
|
+
msgs.push("name is required");
|
|
121
|
+
if (!((_c = row.classId) === null || _c === void 0 ? void 0 : _c.trim()))
|
|
122
|
+
msgs.push("classId is required");
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
if (!((_d = row.id) === null || _d === void 0 ? void 0 : _d.trim()))
|
|
126
|
+
msgs.push("id is required for update");
|
|
127
|
+
}
|
|
128
|
+
if (msgs.length > 0) {
|
|
129
|
+
validationErrors.push({ row: i + 1, messages: msgs });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (validationErrors.length > 0) {
|
|
133
|
+
const summary = validationErrors
|
|
134
|
+
.slice(0, 5)
|
|
135
|
+
.map((e) => `Row ${e.row}: ${e.messages.join("; ")}`)
|
|
136
|
+
.join("\n");
|
|
137
|
+
const remaining = validationErrors.length - 5;
|
|
138
|
+
showErrorToast(`Validation failed for ${validationErrors.length} row(s).\n${summary}${remaining > 0 ? `\n...and ${remaining} more` : ""}`);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
showInfoToast(`Bulk ${label} job queued (${records.length} records). Processing...`);
|
|
143
|
+
let jobId;
|
|
144
|
+
try {
|
|
145
|
+
jobId = await submitBulkJob(text, method, signal);
|
|
146
|
+
}
|
|
147
|
+
catch (submitError) {
|
|
148
|
+
showErrorToast(`Failed to submit ${label} job: ${submitError instanceof Error ? submitError.message : "Unknown error"}`);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const status = await pollBulkJob(jobId, signal, (processed, total) => {
|
|
152
|
+
showInfoToast(`Processing ${processed}/${total} sections...`);
|
|
153
|
+
});
|
|
154
|
+
if (signal.aborted)
|
|
155
|
+
return;
|
|
156
|
+
if (status.status === "completed") {
|
|
157
|
+
const r = status.results;
|
|
158
|
+
if (r && ((_e = r.errors) === null || _e === void 0 ? void 0 : _e.length) > 0) {
|
|
159
|
+
const summary = formatErrorSummary(r.errors);
|
|
160
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}\n${summary}`);
|
|
161
|
+
}
|
|
162
|
+
else if (r) {
|
|
163
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}`);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
showSuccessToast("Bulk operation completed successfully");
|
|
167
|
+
}
|
|
168
|
+
invalidateSectionsCache();
|
|
169
|
+
const schoolId = ((_f = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _f === void 0 ? void 0 : _f.id) || "";
|
|
170
|
+
fetch(`${SECTION_API_ROUTES.LIST}?currentPage=1&pageLimit=${pageLimit}&schoolId=${schoolId}`, {
|
|
171
|
+
headers: {
|
|
172
|
+
"Content-Type": "application/json",
|
|
173
|
+
},
|
|
174
|
+
})
|
|
175
|
+
.then(async (res) => {
|
|
176
|
+
var _a, _b;
|
|
177
|
+
if (!res.ok)
|
|
178
|
+
return;
|
|
179
|
+
const data = await res.json();
|
|
180
|
+
dispatch({
|
|
181
|
+
type: SECTION_ACTION_TYPES.SET_ITEMS,
|
|
182
|
+
payload: {
|
|
183
|
+
items: (_a = data.items) !== null && _a !== void 0 ? _a : [],
|
|
184
|
+
count: (_b = data.count) !== null && _b !== void 0 ? _b : 0,
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
})
|
|
188
|
+
.catch(() => { });
|
|
189
|
+
closeDrawer();
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const r = status.results;
|
|
193
|
+
const detail = ((_g = r === null || r === void 0 ? void 0 : r.errors) === null || _g === void 0 ? void 0 : _g.length)
|
|
194
|
+
? formatErrorSummary(r.errors)
|
|
195
|
+
: "Unknown error";
|
|
196
|
+
showErrorToast(`Bulk ${label} failed.\n${detail}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (error.message === "Polling cancelled")
|
|
201
|
+
return;
|
|
202
|
+
showErrorToast(`Bulk ${label} failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
203
|
+
}
|
|
204
|
+
}, [dispatch]);
|
|
205
|
+
const handleBulkCreate = useCallback((files) => handleBulkFlow(files, "POST"), [handleBulkFlow]);
|
|
206
|
+
const handleBulkUpdate = useCallback((files) => handleBulkFlow(files, "PUT"), [handleBulkFlow]);
|
|
23
207
|
const create = [
|
|
24
208
|
{
|
|
25
209
|
id: "1",
|
|
26
210
|
title: t("downloadEmptyCsvTemplate"),
|
|
27
211
|
handleOnClick: async () => {
|
|
28
|
-
|
|
212
|
+
var _a;
|
|
213
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1);
|
|
29
214
|
},
|
|
30
215
|
},
|
|
31
216
|
{ id: "2", title: t("addYourDataToTheCsv") },
|
|
32
217
|
{
|
|
33
218
|
id: "3",
|
|
34
219
|
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
35
|
-
handleOnClick: () => {
|
|
36
|
-
// bulk create csv upload — implementation pending
|
|
37
|
-
},
|
|
38
220
|
},
|
|
39
221
|
];
|
|
40
222
|
const update = [
|
|
@@ -43,17 +225,14 @@ export const SectionMoreActions = () => {
|
|
|
43
225
|
title: t("downloadPopulatedCsvTemplate"),
|
|
44
226
|
handleOnClick: async () => {
|
|
45
227
|
var _a;
|
|
46
|
-
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "");
|
|
228
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1000);
|
|
47
229
|
},
|
|
48
230
|
},
|
|
49
231
|
{ id: "2", title: t("updateYourDataInTheCsv") },
|
|
50
232
|
{
|
|
51
233
|
id: "3",
|
|
52
234
|
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
53
|
-
handleOnClick: () => {
|
|
54
|
-
// bulk update csv upload — implementation pending
|
|
55
|
-
},
|
|
56
235
|
},
|
|
57
236
|
];
|
|
58
|
-
return (_jsxs("div", { className: "space-y-4", children: [_jsx(Timeline, { events: create, heading: t("bulkCreate") }), _jsx(Timeline, { events: update, heading: t("bulkUpdate") })] }));
|
|
237
|
+
return (_jsxs("div", { className: "space-y-4", children: [_jsx(Timeline, { events: create, heading: t("bulkCreate"), handleOnBulkCreate: handleBulkCreate }), _jsx(Timeline, { events: update, heading: t("bulkUpdate"), handleOnBulkCreate: handleBulkUpdate })] }));
|
|
59
238
|
};
|
|
@@ -145,7 +145,7 @@ export declare const STUDENT_FEE_ACTION_TYPES: {
|
|
|
145
145
|
studentProfileId: string;
|
|
146
146
|
filterEnabled: boolean | undefined;
|
|
147
147
|
filterStatus: PAYMENT_STATUS | "";
|
|
148
|
-
}, useStudentFeeContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").
|
|
148
|
+
}, useStudentFeeContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").GenericModuleContextWithHandlers<{
|
|
149
149
|
items: StudentFeeBE[];
|
|
150
150
|
count: number;
|
|
151
151
|
currentPage: number;
|
|
@@ -151,7 +151,7 @@ export declare const STUDENT_PROFILE_ACTION_TYPES: {
|
|
|
151
151
|
filterEnabled: boolean | undefined;
|
|
152
152
|
filterGender: string | undefined;
|
|
153
153
|
filterStatus: string | undefined;
|
|
154
|
-
}, useStudentProfileContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").
|
|
154
|
+
}, useStudentProfileContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").GenericModuleContextWithHandlers<{
|
|
155
155
|
items: StudentProfileBE[];
|
|
156
156
|
count: number;
|
|
157
157
|
currentPage: number;
|
|
@@ -13,5 +13,8 @@ export const pageLimit = Number(process.env.NEXT_PUBLIC_PAGE_LIMIT) || 10;
|
|
|
13
13
|
// API ROUTES
|
|
14
14
|
// ============================================================================
|
|
15
15
|
export const SUBJECT_API_ROUTES = {
|
|
16
|
+
LIST: "/api/v1/subject",
|
|
16
17
|
UNIT: "/api/v1/subject",
|
|
18
|
+
BULK: "/api/v1/subject/bulk",
|
|
19
|
+
BULK_STATUS: (jobId) => `/api/v1/subject/bulk/${jobId}`,
|
|
17
20
|
};
|
|
@@ -84,7 +84,7 @@ export declare const SUBJECT_ACTION_TYPES: {
|
|
|
84
84
|
id: string;
|
|
85
85
|
name: string;
|
|
86
86
|
schoolId: string;
|
|
87
|
-
}, useSubjectContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").
|
|
87
|
+
}, useSubjectContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").GenericModuleContextWithHandlers<{
|
|
88
88
|
items: SubjectBE[];
|
|
89
89
|
count: number;
|
|
90
90
|
currentPage: number;
|
|
@@ -129,6 +129,7 @@ export declare const useSubjectModule: () => {
|
|
|
129
129
|
listLoading: boolean;
|
|
130
130
|
rowActions: RowAction[];
|
|
131
131
|
updateLoading: boolean;
|
|
132
|
+
handleCloseDrawer?: () => void;
|
|
132
133
|
state: {
|
|
133
134
|
items: SubjectBE[];
|
|
134
135
|
count: number;
|
|
@@ -353,10 +353,10 @@ export const useSubjectModule = () => {
|
|
|
353
353
|
// ============================================================================
|
|
354
354
|
const headerActions = useMemo(() => [
|
|
355
355
|
{
|
|
356
|
-
enabled:
|
|
356
|
+
enabled: true,
|
|
357
357
|
handleOnClick: handleMoreActions,
|
|
358
358
|
label: t("actionHeaderMoreActions"),
|
|
359
|
-
order:
|
|
359
|
+
order: 0,
|
|
360
360
|
icon: MoreHorizontal,
|
|
361
361
|
},
|
|
362
362
|
{
|
|
@@ -1,40 +1,222 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
* Provides bulk CSV import/export actions for the subject module.
|
|
7
|
-
*/
|
|
8
|
-
import { API_METHODS, downloadFromUrl } from "@react-pakistan/util-functions";
|
|
3
|
+
import { downloadFromUrl } from "@react-pakistan/util-functions";
|
|
4
|
+
import { showErrorToast, showSuccessToast, showInfoToast, } from "@appcorp/shadcn/lib/toast-utils";
|
|
9
5
|
import { getCachedWorkspaceSync } from "../workspace/cache";
|
|
10
6
|
import converter from "json-2-csv";
|
|
11
7
|
import { Timeline } from "../../components/timeline";
|
|
12
8
|
import { useTranslations } from "next-intl";
|
|
9
|
+
import { SUBJECT_API_ROUTES, pageLimit } from "./constants";
|
|
10
|
+
import { invalidateSubjectsCache } from "./cache";
|
|
11
|
+
import { SUBJECT_ACTION_TYPES, useSubjectContext } from "./context";
|
|
12
|
+
import { useRef, useEffect, useCallback } from "react";
|
|
13
|
+
const workspace = getCachedWorkspaceSync();
|
|
14
|
+
const POLL_INTERVAL_MS = 2000;
|
|
15
|
+
const POLL_TIMEOUT_MS = 300000;
|
|
16
|
+
const handleGetAllRecords = async (schoolId, pageLimit) => {
|
|
17
|
+
const response = await fetch(`${SUBJECT_API_ROUTES.UNIT}?pageLimit=${pageLimit}¤tPage=1&schoolId=${schoolId}`);
|
|
18
|
+
const result = await response.json();
|
|
19
|
+
const csv = await converter.json2csv(result.items || [], {});
|
|
20
|
+
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
|
21
|
+
await downloadFromUrl(blob, "subject.csv");
|
|
22
|
+
};
|
|
23
|
+
async function submitBulkJob(csvData, method, signal) {
|
|
24
|
+
var _a;
|
|
25
|
+
const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
|
|
26
|
+
if (!schoolId)
|
|
27
|
+
throw new Error("School ID not found");
|
|
28
|
+
const res = await fetch(SUBJECT_API_ROUTES.BULK, {
|
|
29
|
+
method,
|
|
30
|
+
headers: {
|
|
31
|
+
"Content-Type": "application/json",
|
|
32
|
+
},
|
|
33
|
+
body: JSON.stringify({ schoolId, csvData }),
|
|
34
|
+
signal,
|
|
35
|
+
});
|
|
36
|
+
if (!res.ok) {
|
|
37
|
+
const errorData = (await res.json().catch(() => ({})));
|
|
38
|
+
throw new Error(errorData.error || `Bulk operation failed with status ${res.status}`);
|
|
39
|
+
}
|
|
40
|
+
const data = (await res.json());
|
|
41
|
+
return data.jobId;
|
|
42
|
+
}
|
|
43
|
+
async function pollBulkJob(jobId, signal, onProgress) {
|
|
44
|
+
const startTime = Date.now();
|
|
45
|
+
let lastProgressToast = 0;
|
|
46
|
+
while (true) {
|
|
47
|
+
if (signal.aborted)
|
|
48
|
+
throw new Error("Polling cancelled");
|
|
49
|
+
if (Date.now() - startTime > POLL_TIMEOUT_MS) {
|
|
50
|
+
throw new Error("Bulk operation timed out");
|
|
51
|
+
}
|
|
52
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
53
|
+
if (signal.aborted)
|
|
54
|
+
throw new Error("Polling cancelled");
|
|
55
|
+
const res = await fetch(SUBJECT_API_ROUTES.BULK_STATUS(jobId), {
|
|
56
|
+
signal,
|
|
57
|
+
});
|
|
58
|
+
if (!res.ok)
|
|
59
|
+
continue;
|
|
60
|
+
const data = (await res.json());
|
|
61
|
+
if (data.status === "completed" || data.status === "failed") {
|
|
62
|
+
return data;
|
|
63
|
+
}
|
|
64
|
+
// Show progress toast every 10 seconds while running
|
|
65
|
+
if (data.status === "running" && Date.now() - lastProgressToast > 10000) {
|
|
66
|
+
lastProgressToast = Date.now();
|
|
67
|
+
onProgress === null || onProgress === void 0 ? void 0 : onProgress(data.processed, data.total);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function formatErrorSummary(errors) {
|
|
72
|
+
if (!(errors === null || errors === void 0 ? void 0 : errors.length))
|
|
73
|
+
return "";
|
|
74
|
+
const lines = errors.slice(0, 5).map((e) => `Row ${e.row}: ${e.error}`);
|
|
75
|
+
const remaining = errors.length - 5;
|
|
76
|
+
if (remaining > 0)
|
|
77
|
+
lines.push(`...and ${remaining} more`);
|
|
78
|
+
return lines.join("\n");
|
|
79
|
+
}
|
|
13
80
|
export const SubjectMoreActions = () => {
|
|
14
81
|
const t = useTranslations("subject");
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
82
|
+
const { dispatch } = useSubjectContext();
|
|
83
|
+
const abortRef = useRef(null);
|
|
84
|
+
// Abort any in-flight polling on unmount
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
return () => {
|
|
87
|
+
var _a;
|
|
88
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
89
|
+
};
|
|
90
|
+
}, []);
|
|
91
|
+
const handleBulkFlow = useCallback(async (files, method) => {
|
|
92
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
93
|
+
const closeDrawer = () => {
|
|
94
|
+
dispatch({
|
|
95
|
+
type: SUBJECT_ACTION_TYPES.SET_DRAWER,
|
|
96
|
+
payload: { drawer: null },
|
|
97
|
+
});
|
|
98
|
+
};
|
|
99
|
+
// Cancel previous in-flight request
|
|
100
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
101
|
+
const controller = new AbortController();
|
|
102
|
+
abortRef.current = controller;
|
|
103
|
+
const { signal } = controller;
|
|
104
|
+
const label = method === "POST" ? "create" : "update";
|
|
105
|
+
// Read + parse CSV
|
|
106
|
+
const file = files[0];
|
|
107
|
+
const text = await file.text();
|
|
108
|
+
const records = converter.csv2json(text);
|
|
109
|
+
if (!Array.isArray(records) || records.length === 0) {
|
|
110
|
+
showErrorToast("CSV file is empty or invalid");
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
// Client-side validation — basic required field check
|
|
114
|
+
const validationErrors = [];
|
|
115
|
+
for (let i = 0; i < records.length; i++) {
|
|
116
|
+
const row = records[i];
|
|
117
|
+
const msgs = [];
|
|
118
|
+
if (method === "POST") {
|
|
119
|
+
if (!((_b = row.code) === null || _b === void 0 ? void 0 : _b.trim()))
|
|
120
|
+
msgs.push("code is required");
|
|
121
|
+
if (!((_c = row.name) === null || _c === void 0 ? void 0 : _c.trim()))
|
|
122
|
+
msgs.push("name is required");
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
if (!((_d = row.id) === null || _d === void 0 ? void 0 : _d.trim()))
|
|
126
|
+
msgs.push("id is required for update");
|
|
127
|
+
}
|
|
128
|
+
if (msgs.length > 0) {
|
|
129
|
+
validationErrors.push({ row: i + 1, messages: msgs });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (validationErrors.length > 0) {
|
|
133
|
+
const summary = validationErrors
|
|
134
|
+
.slice(0, 5)
|
|
135
|
+
.map((e) => `Row ${e.row}: ${e.messages.join("; ")}`)
|
|
136
|
+
.join("\n");
|
|
137
|
+
const remaining = validationErrors.length - 5;
|
|
138
|
+
showErrorToast(`Validation failed for ${validationErrors.length} row(s).\n${summary}${remaining > 0 ? `\n...and ${remaining} more` : ""}`);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
showInfoToast(`Bulk ${label} job queued (${records.length} records). Processing...`);
|
|
143
|
+
let jobId;
|
|
144
|
+
try {
|
|
145
|
+
jobId = await submitBulkJob(text, method, signal);
|
|
146
|
+
}
|
|
147
|
+
catch (submitError) {
|
|
148
|
+
showErrorToast(`Failed to submit ${label} job: ${submitError instanceof Error ? submitError.message : "Unknown error"}`);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const status = await pollBulkJob(jobId, signal, (processed, total) => {
|
|
152
|
+
showInfoToast(`Processing ${processed}/${total} subjects...`);
|
|
153
|
+
});
|
|
154
|
+
if (signal.aborted)
|
|
155
|
+
return;
|
|
156
|
+
if (status.status === "completed") {
|
|
157
|
+
const r = status.results;
|
|
158
|
+
if (r && ((_e = r.errors) === null || _e === void 0 ? void 0 : _e.length) > 0) {
|
|
159
|
+
const summary = formatErrorSummary(r.errors);
|
|
160
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}\n${summary}`);
|
|
161
|
+
}
|
|
162
|
+
else if (r) {
|
|
163
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}`);
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
showSuccessToast("Bulk operation completed successfully");
|
|
167
|
+
}
|
|
168
|
+
invalidateSubjectsCache();
|
|
169
|
+
const schoolId = ((_f = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _f === void 0 ? void 0 : _f.id) || "";
|
|
170
|
+
fetch(`${SUBJECT_API_ROUTES.LIST}?currentPage=1&pageLimit=${pageLimit}&schoolId=${schoolId}`, {
|
|
171
|
+
headers: {
|
|
172
|
+
"Content-Type": "application/json",
|
|
173
|
+
},
|
|
174
|
+
})
|
|
175
|
+
.then(async (res) => {
|
|
176
|
+
var _a, _b;
|
|
177
|
+
if (!res.ok)
|
|
178
|
+
return;
|
|
179
|
+
const data = await res.json();
|
|
180
|
+
dispatch({
|
|
181
|
+
type: SUBJECT_ACTION_TYPES.SET_ITEMS,
|
|
182
|
+
payload: {
|
|
183
|
+
items: (_a = data.items) !== null && _a !== void 0 ? _a : [],
|
|
184
|
+
count: (_b = data.count) !== null && _b !== void 0 ? _b : 0,
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
})
|
|
188
|
+
.catch(() => { });
|
|
189
|
+
closeDrawer();
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const r = status.results;
|
|
193
|
+
const detail = ((_g = r === null || r === void 0 ? void 0 : r.errors) === null || _g === void 0 ? void 0 : _g.length)
|
|
194
|
+
? formatErrorSummary(r.errors)
|
|
195
|
+
: "Unknown error";
|
|
196
|
+
showErrorToast(`Bulk ${label} failed.\n${detail}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (error.message === "Polling cancelled")
|
|
201
|
+
return;
|
|
202
|
+
showErrorToast(`Bulk ${label} failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
203
|
+
}
|
|
204
|
+
}, [dispatch]);
|
|
205
|
+
const handleBulkCreate = useCallback((files) => handleBulkFlow(files, "POST"), [handleBulkFlow]);
|
|
206
|
+
const handleBulkUpdate = useCallback((files) => handleBulkFlow(files, "PUT"), [handleBulkFlow]);
|
|
23
207
|
const create = [
|
|
24
208
|
{
|
|
25
209
|
id: "1",
|
|
26
210
|
title: t("downloadEmptyCsvTemplate"),
|
|
27
211
|
handleOnClick: async () => {
|
|
28
|
-
|
|
212
|
+
var _a;
|
|
213
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1);
|
|
29
214
|
},
|
|
30
215
|
},
|
|
31
216
|
{ id: "2", title: t("addYourDataToTheCsv") },
|
|
32
217
|
{
|
|
33
218
|
id: "3",
|
|
34
219
|
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
35
|
-
handleOnClick: () => {
|
|
36
|
-
// bulk create csv upload — implementation pending
|
|
37
|
-
},
|
|
38
220
|
},
|
|
39
221
|
];
|
|
40
222
|
const update = [
|
|
@@ -43,17 +225,14 @@ export const SubjectMoreActions = () => {
|
|
|
43
225
|
title: t("downloadPopulatedCsvTemplate"),
|
|
44
226
|
handleOnClick: async () => {
|
|
45
227
|
var _a;
|
|
46
|
-
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "");
|
|
228
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1000);
|
|
47
229
|
},
|
|
48
230
|
},
|
|
49
231
|
{ id: "2", title: t("updateYourDataInTheCsv") },
|
|
50
232
|
{
|
|
51
233
|
id: "3",
|
|
52
234
|
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
53
|
-
handleOnClick: () => {
|
|
54
|
-
// bulk update csv upload — implementation pending
|
|
55
|
-
},
|
|
56
235
|
},
|
|
57
236
|
];
|
|
58
|
-
return (_jsxs("div", { className: "space-y-4", children: [_jsx(Timeline, { events: create, heading: t("bulkCreate") }), _jsx(Timeline, { events: update, heading: t("bulkUpdate") })] }));
|
|
237
|
+
return (_jsxs("div", { className: "space-y-4", children: [_jsx(Timeline, { events: create, heading: t("bulkCreate"), handleOnBulkCreate: handleBulkCreate }), _jsx(Timeline, { events: update, heading: t("bulkUpdate"), handleOnBulkCreate: handleBulkUpdate })] }));
|
|
59
238
|
};
|
|
@@ -152,7 +152,7 @@ export declare const TEACHER_ACTION_TYPES: {
|
|
|
152
152
|
teacherCode: string;
|
|
153
153
|
userId: string | null;
|
|
154
154
|
filterEnabled: boolean | undefined;
|
|
155
|
-
}, useTeacherContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").
|
|
155
|
+
}, useTeacherContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").GenericModuleContextWithHandlers<{
|
|
156
156
|
items: TeacherBE[];
|
|
157
157
|
count: number;
|
|
158
158
|
currentPage: number;
|
|
@@ -217,6 +217,7 @@ export declare const useTeacherModule: () => {
|
|
|
217
217
|
rowActions: RowAction[];
|
|
218
218
|
toggleStatus: (row?: TableRow) => void;
|
|
219
219
|
updateLoading: boolean;
|
|
220
|
+
handleCloseDrawer?: () => void;
|
|
220
221
|
state: {
|
|
221
222
|
items: TeacherBE[];
|
|
222
223
|
count: number;
|
|
@@ -91,7 +91,7 @@ export declare const USER_ACTION_TYPES: {
|
|
|
91
91
|
enabled: boolean;
|
|
92
92
|
userRole: USER_ROLE | null;
|
|
93
93
|
filterEnabled: boolean | undefined;
|
|
94
|
-
}, useUserContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").
|
|
94
|
+
}, useUserContext: () => import("@react-pakistan/util-functions/factory/generic-module-factory").GenericModuleContextWithHandlers<{
|
|
95
95
|
items: UserBE[];
|
|
96
96
|
count: number;
|
|
97
97
|
currentPage: number;
|