@appcorp/fusion-storybook 0.2.32 → 0.2.34
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/class/more-actions.js +5 -5
- package/base-modules/enrollment/constants.d.ts +3 -0
- package/base-modules/enrollment/constants.js +3 -0
- package/base-modules/enrollment/context.js +1 -1
- package/base-modules/enrollment/more-actions.js +204 -26
- package/base-modules/section/constants.d.ts +3 -0
- package/base-modules/section/constants.js +3 -0
- package/base-modules/section/context.js +2 -2
- package/base-modules/section/more-actions.js +202 -23
- package/base-modules/subject/constants.d.ts +3 -0
- package/base-modules/subject/constants.js +3 -0
- package/base-modules/subject/context.js +2 -2
- package/base-modules/subject/more-actions.js +202 -23
- package/base-modules/teacher/more-actions.js +5 -9
- package/package.json +1 -1
- package/tsconfig.build.tsbuildinfo +1 -1
|
@@ -6,7 +6,6 @@ import { getCachedWorkspaceSync } from "../workspace/cache";
|
|
|
6
6
|
import converter from "json-2-csv";
|
|
7
7
|
import { Timeline } from "../../components/timeline";
|
|
8
8
|
import { useTranslations } from "next-intl";
|
|
9
|
-
import { CSVS } from "../../constants";
|
|
10
9
|
import { CLASS_API_ROUTES, pageLimit } from "./constants";
|
|
11
10
|
import { invalidateClassesCache } from "./cache";
|
|
12
11
|
import { CLASS_ACTION_TYPES, useClassContext } from "./context";
|
|
@@ -14,8 +13,8 @@ import { useRef, useEffect, useCallback } from "react";
|
|
|
14
13
|
const workspace = getCachedWorkspaceSync();
|
|
15
14
|
const POLL_INTERVAL_MS = 2000;
|
|
16
15
|
const POLL_TIMEOUT_MS = 300000;
|
|
17
|
-
const handleGetAllRecords = async (schoolId) => {
|
|
18
|
-
const response = await fetch(`${CLASS_API_ROUTES.UNIT}?pageLimit
|
|
16
|
+
const handleGetAllRecords = async (schoolId, pageLimit) => {
|
|
17
|
+
const response = await fetch(`${CLASS_API_ROUTES.UNIT}?pageLimit=${pageLimit}¤tPage=1&schoolId=${schoolId}`);
|
|
19
18
|
const result = await response.json();
|
|
20
19
|
const csv = await converter.json2csv(result.items || [], {});
|
|
21
20
|
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
|
@@ -210,7 +209,8 @@ export const ClassMoreActions = () => {
|
|
|
210
209
|
id: "1",
|
|
211
210
|
title: t("downloadEmptyCsvTemplate"),
|
|
212
211
|
handleOnClick: async () => {
|
|
213
|
-
|
|
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);
|
|
214
214
|
},
|
|
215
215
|
},
|
|
216
216
|
{ id: "2", title: t("addYourDataToTheCsv") },
|
|
@@ -225,7 +225,7 @@ export const ClassMoreActions = () => {
|
|
|
225
225
|
title: t("downloadPopulatedCsvTemplate"),
|
|
226
226
|
handleOnClick: async () => {
|
|
227
227
|
var _a;
|
|
228
|
-
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);
|
|
229
229
|
},
|
|
230
230
|
},
|
|
231
231
|
{ id: "2", title: t("updateYourDataInTheCsv") },
|
|
@@ -7,5 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export declare const pageLimit: number;
|
|
9
9
|
export declare const ENROLLMENT_API_ROUTES: {
|
|
10
|
+
readonly LIST: "/api/v1/enrollment";
|
|
10
11
|
readonly UNIT: "/api/v1/enrollment";
|
|
12
|
+
readonly BULK: "/api/v1/enrollment/bulk";
|
|
13
|
+
readonly BULK_STATUS: (jobId: string) => string;
|
|
11
14
|
};
|
|
@@ -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 ENROLLMENT_API_ROUTES = {
|
|
16
|
+
LIST: "/api/v1/enrollment",
|
|
16
17
|
UNIT: "/api/v1/enrollment",
|
|
18
|
+
BULK: "/api/v1/enrollment/bulk",
|
|
19
|
+
BULK_STATUS: (jobId) => `/api/v1/enrollment/bulk/${jobId}`,
|
|
17
20
|
};
|
|
@@ -349,7 +349,7 @@ export const useEnrollmentModule = () => {
|
|
|
349
349
|
// ==========================================================================
|
|
350
350
|
const headerActions = useMemo(() => [
|
|
351
351
|
{
|
|
352
|
-
enabled:
|
|
352
|
+
enabled: true,
|
|
353
353
|
handleOnClick: handleMoreActions,
|
|
354
354
|
label: t("actionsButtonMoreActions"),
|
|
355
355
|
order: 0,
|
|
@@ -1,43 +1,224 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
* Bulk create and bulk update workflows for the enrollment 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";
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
9
|
+
import { ENROLLMENT_API_ROUTES, pageLimit } from "./constants";
|
|
10
|
+
import { invalidateEnrollmentsCache } from "./cache";
|
|
11
|
+
import { ENROLLMENT_ACTION_TYPES, useEnrollmentContext } 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(`${ENROLLMENT_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, "enrollment.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(ENROLLMENT_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(ENROLLMENT_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
|
+
}
|
|
16
80
|
export const EnrollmentMoreActions = () => {
|
|
17
81
|
const t = useTranslations("enrollment");
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
82
|
+
const { dispatch } = useEnrollmentContext();
|
|
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, _h;
|
|
93
|
+
const closeDrawer = () => {
|
|
94
|
+
dispatch({
|
|
95
|
+
type: ENROLLMENT_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.studentProfileId) === null || _b === void 0 ? void 0 : _b.trim()))
|
|
120
|
+
msgs.push("studentProfileId is required");
|
|
121
|
+
if (!((_c = row.sectionId) === null || _c === void 0 ? void 0 : _c.trim()))
|
|
122
|
+
msgs.push("sectionId is required");
|
|
123
|
+
if (!((_d = row.enrollmentDate) === null || _d === void 0 ? void 0 : _d.trim()))
|
|
124
|
+
msgs.push("enrollmentDate is required");
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
if (!((_e = row.id) === null || _e === void 0 ? void 0 : _e.trim()))
|
|
128
|
+
msgs.push("id is required for update");
|
|
129
|
+
}
|
|
130
|
+
if (msgs.length > 0) {
|
|
131
|
+
validationErrors.push({ row: i + 1, messages: msgs });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (validationErrors.length > 0) {
|
|
135
|
+
const summary = validationErrors
|
|
136
|
+
.slice(0, 5)
|
|
137
|
+
.map((e) => `Row ${e.row}: ${e.messages.join("; ")}`)
|
|
138
|
+
.join("\n");
|
|
139
|
+
const remaining = validationErrors.length - 5;
|
|
140
|
+
showErrorToast(`Validation failed for ${validationErrors.length} row(s).\n${summary}${remaining > 0 ? `\n...and ${remaining} more` : ""}`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
showInfoToast(`Bulk ${label} job queued (${records.length} records). Processing...`);
|
|
145
|
+
let jobId;
|
|
146
|
+
try {
|
|
147
|
+
jobId = await submitBulkJob(text, method, signal);
|
|
148
|
+
}
|
|
149
|
+
catch (submitError) {
|
|
150
|
+
showErrorToast(`Failed to submit ${label} job: ${submitError instanceof Error ? submitError.message : "Unknown error"}`);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const status = await pollBulkJob(jobId, signal, (processed, total) => {
|
|
154
|
+
showInfoToast(`Processing ${processed}/${total} enrollments...`);
|
|
155
|
+
});
|
|
156
|
+
if (signal.aborted)
|
|
157
|
+
return;
|
|
158
|
+
if (status.status === "completed") {
|
|
159
|
+
const r = status.results;
|
|
160
|
+
if (r && ((_f = r.errors) === null || _f === void 0 ? void 0 : _f.length) > 0) {
|
|
161
|
+
const summary = formatErrorSummary(r.errors);
|
|
162
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}\n${summary}`);
|
|
163
|
+
}
|
|
164
|
+
else if (r) {
|
|
165
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}`);
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
showSuccessToast("Bulk operation completed successfully");
|
|
169
|
+
}
|
|
170
|
+
invalidateEnrollmentsCache();
|
|
171
|
+
const schoolId = ((_g = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _g === void 0 ? void 0 : _g.id) || "";
|
|
172
|
+
fetch(`${ENROLLMENT_API_ROUTES.LIST}?currentPage=1&pageLimit=${pageLimit}&schoolId=${schoolId}`, {
|
|
173
|
+
headers: {
|
|
174
|
+
"Content-Type": "application/json",
|
|
175
|
+
},
|
|
176
|
+
})
|
|
177
|
+
.then(async (res) => {
|
|
178
|
+
var _a, _b;
|
|
179
|
+
if (!res.ok)
|
|
180
|
+
return;
|
|
181
|
+
const data = await res.json();
|
|
182
|
+
dispatch({
|
|
183
|
+
type: ENROLLMENT_ACTION_TYPES.SET_ITEMS,
|
|
184
|
+
payload: {
|
|
185
|
+
items: (_a = data.items) !== null && _a !== void 0 ? _a : [],
|
|
186
|
+
count: (_b = data.count) !== null && _b !== void 0 ? _b : 0,
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
})
|
|
190
|
+
.catch(() => { });
|
|
191
|
+
closeDrawer();
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
const r = status.results;
|
|
195
|
+
const detail = ((_h = r === null || r === void 0 ? void 0 : r.errors) === null || _h === void 0 ? void 0 : _h.length)
|
|
196
|
+
? formatErrorSummary(r.errors)
|
|
197
|
+
: "Unknown error";
|
|
198
|
+
showErrorToast(`Bulk ${label} failed.\n${detail}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
if (error.message === "Polling cancelled")
|
|
203
|
+
return;
|
|
204
|
+
showErrorToast(`Bulk ${label} failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
205
|
+
}
|
|
206
|
+
}, [dispatch]);
|
|
207
|
+
const handleBulkCreate = useCallback((files) => handleBulkFlow(files, "POST"), [handleBulkFlow]);
|
|
208
|
+
const handleBulkUpdate = useCallback((files) => handleBulkFlow(files, "PUT"), [handleBulkFlow]);
|
|
26
209
|
const create = [
|
|
27
210
|
{
|
|
28
211
|
id: "1",
|
|
29
212
|
title: t("downloadEmptyCsvTemplate"),
|
|
30
213
|
handleOnClick: async () => {
|
|
31
|
-
|
|
214
|
+
var _a;
|
|
215
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1);
|
|
32
216
|
},
|
|
33
217
|
},
|
|
34
218
|
{ id: "2", title: t("addYourDataToTheCsv") },
|
|
35
219
|
{
|
|
36
220
|
id: "3",
|
|
37
221
|
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
38
|
-
handleOnClick: () => {
|
|
39
|
-
// bulk csv upload — implementation pending
|
|
40
|
-
},
|
|
41
222
|
},
|
|
42
223
|
];
|
|
43
224
|
const update = [
|
|
@@ -46,17 +227,14 @@ export const EnrollmentMoreActions = () => {
|
|
|
46
227
|
title: t("downloadPopulatedCsvTemplate"),
|
|
47
228
|
handleOnClick: async () => {
|
|
48
229
|
var _a;
|
|
49
|
-
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "");
|
|
230
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1000);
|
|
50
231
|
},
|
|
51
232
|
},
|
|
52
233
|
{ id: "2", title: t("updateYourDataInTheCsv") },
|
|
53
234
|
{
|
|
54
235
|
id: "3",
|
|
55
236
|
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
56
|
-
handleOnClick: () => {
|
|
57
|
-
// bulk csv upload — implementation pending
|
|
58
|
-
},
|
|
59
237
|
},
|
|
60
238
|
];
|
|
61
|
-
return (_jsxs("div", { className: "space-y-4", children: [_jsx(Timeline, { events: create, heading: t("bulkCreate") }), _jsx(Timeline, { events: update, heading: t("bulkUpdate") })] }));
|
|
239
|
+
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 })] }));
|
|
62
240
|
};
|
|
@@ -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 SECTION_API_ROUTES = {
|
|
16
|
+
LIST: "/api/v1/section",
|
|
16
17
|
UNIT: "/api/v1/section",
|
|
18
|
+
BULK: "/api/v1/section/bulk",
|
|
19
|
+
BULK_STATUS: (jobId) => `/api/v1/section/bulk/${jobId}`,
|
|
17
20
|
};
|
|
@@ -370,13 +370,13 @@ export const useSectionModule = () => {
|
|
|
370
370
|
// ============================================================================
|
|
371
371
|
const headerActions = useMemo(() => [
|
|
372
372
|
{
|
|
373
|
-
enabled:
|
|
373
|
+
enabled: true,
|
|
374
374
|
handleOnClick: handleMoreActions,
|
|
375
375
|
label: t("actionHeaderMoreActions"),
|
|
376
376
|
order: 0,
|
|
377
377
|
},
|
|
378
378
|
{
|
|
379
|
-
enabled:
|
|
379
|
+
enabled: true,
|
|
380
380
|
handleOnClick: handleFilters,
|
|
381
381
|
label: t("actionHeaderFilters"),
|
|
382
382
|
order: 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
|
};
|
|
@@ -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
|
};
|