@appcorp/fusion-storybook 0.2.36 → 0.2.37
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.
|
@@ -9,7 +9,10 @@
|
|
|
9
9
|
import { FEE_TYPE } from "../../type";
|
|
10
10
|
export declare const pageLimit: number;
|
|
11
11
|
export declare const FEE_STRUCTURE_API_ROUTES: {
|
|
12
|
+
readonly LIST: "/api/v1/fee-structure";
|
|
12
13
|
readonly UNIT: "/api/v1/fee-structure";
|
|
14
|
+
readonly BULK: "/api/v1/fee-structure/bulk";
|
|
15
|
+
readonly BULK_STATUS: (jobId: string) => string;
|
|
13
16
|
};
|
|
14
17
|
export declare const FEE_TYPE_OPTIONS: {
|
|
15
18
|
label: string;
|
|
@@ -15,7 +15,10 @@ export const pageLimit = Number(process.env.NEXT_PUBLIC_PAGE_LIMIT) || 10;
|
|
|
15
15
|
// API ROUTES
|
|
16
16
|
// ============================================================================
|
|
17
17
|
export const FEE_STRUCTURE_API_ROUTES = {
|
|
18
|
+
LIST: "/api/v1/fee-structure",
|
|
18
19
|
UNIT: "/api/v1/fee-structure",
|
|
20
|
+
BULK: "/api/v1/fee-structure/bulk",
|
|
21
|
+
BULK_STATUS: (jobId) => `/api/v1/fee-structure/bulk/${jobId}`,
|
|
19
22
|
};
|
|
20
23
|
// ============================================================================
|
|
21
24
|
// FEE TYPE OPTIONS
|
|
@@ -1,27 +1,212 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
import {
|
|
3
|
+
import { downloadFromUrl } from "@react-pakistan/util-functions";
|
|
4
|
+
import { showErrorToast, showSuccessToast, showInfoToast, } from "@appcorp/shadcn/lib/toast-utils";
|
|
5
|
+
import { getCachedWorkspaceSync } from "../workspace/cache";
|
|
4
6
|
import converter from "json-2-csv";
|
|
5
7
|
import { Timeline } from "../../components/timeline";
|
|
6
|
-
import { downloadFromUrl } from "@react-pakistan/util-functions";
|
|
7
8
|
import { useTranslations } from "next-intl";
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
import { feeStructureFormValidation } from "./validate";
|
|
10
|
+
import { FEE_STRUCTURE_API_ROUTES, pageLimit } from "./constants";
|
|
11
|
+
import { invalidateFeeStructuresCache } from "./cache";
|
|
12
|
+
import { FEE_STRUCTURE_ACTION_TYPES, useFeeStructureContext } from "./context";
|
|
13
|
+
import { useRef, useEffect, useCallback } from "react";
|
|
14
|
+
const workspace = getCachedWorkspaceSync();
|
|
15
|
+
const POLL_INTERVAL_MS = 2000;
|
|
16
|
+
const POLL_TIMEOUT_MS = 300000;
|
|
17
|
+
const handleGetAllRecords = async (schoolId, pageLimit) => {
|
|
18
|
+
const response = await fetch(`${FEE_STRUCTURE_API_ROUTES.UNIT}?pageLimit=${pageLimit}¤tPage=1&schoolId=${schoolId}`);
|
|
11
19
|
const result = await response.json();
|
|
12
20
|
const csv = await converter.json2csv(result.items || [], {});
|
|
13
21
|
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
|
14
22
|
await downloadFromUrl(blob, "fee-structure.csv");
|
|
15
23
|
};
|
|
24
|
+
async function submitBulkJob(csvData, method, signal) {
|
|
25
|
+
var _a;
|
|
26
|
+
const schoolId = ((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "";
|
|
27
|
+
if (!schoolId)
|
|
28
|
+
throw new Error("School ID not found");
|
|
29
|
+
const res = await fetch(FEE_STRUCTURE_API_ROUTES.BULK, {
|
|
30
|
+
method,
|
|
31
|
+
headers: {
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
},
|
|
34
|
+
body: JSON.stringify({ schoolId, csvData }),
|
|
35
|
+
signal,
|
|
36
|
+
});
|
|
37
|
+
if (!res.ok) {
|
|
38
|
+
const errorData = (await res.json().catch(() => ({})));
|
|
39
|
+
throw new Error(errorData.error || `Bulk operation failed with status ${res.status}`);
|
|
40
|
+
}
|
|
41
|
+
const data = (await res.json());
|
|
42
|
+
return data.jobId;
|
|
43
|
+
}
|
|
44
|
+
async function pollBulkJob(jobId, signal, onProgress) {
|
|
45
|
+
const startTime = Date.now();
|
|
46
|
+
let lastProgressToast = 0;
|
|
47
|
+
while (true) {
|
|
48
|
+
if (signal.aborted)
|
|
49
|
+
throw new Error("Polling cancelled");
|
|
50
|
+
if (Date.now() - startTime > POLL_TIMEOUT_MS) {
|
|
51
|
+
throw new Error("Bulk operation timed out");
|
|
52
|
+
}
|
|
53
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
54
|
+
if (signal.aborted)
|
|
55
|
+
throw new Error("Polling cancelled");
|
|
56
|
+
const res = await fetch(FEE_STRUCTURE_API_ROUTES.BULK_STATUS(jobId), {
|
|
57
|
+
signal,
|
|
58
|
+
});
|
|
59
|
+
if (!res.ok)
|
|
60
|
+
continue;
|
|
61
|
+
const data = (await res.json());
|
|
62
|
+
if (data.status === "completed" || data.status === "failed") {
|
|
63
|
+
return data;
|
|
64
|
+
}
|
|
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 FeeStructureMoreActions = () => {
|
|
17
81
|
const t = useTranslations("feeStructure");
|
|
18
|
-
const
|
|
82
|
+
const { dispatch } = useFeeStructureContext();
|
|
83
|
+
const abortRef = useRef(null);
|
|
84
|
+
useEffect(() => {
|
|
85
|
+
return () => {
|
|
86
|
+
var _a;
|
|
87
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
88
|
+
};
|
|
89
|
+
}, []);
|
|
90
|
+
const handleBulkFlow = useCallback(async (files, method) => {
|
|
91
|
+
var _a, _b, _c, _d, _e;
|
|
92
|
+
const closeDrawer = () => {
|
|
93
|
+
dispatch({
|
|
94
|
+
type: FEE_STRUCTURE_ACTION_TYPES.SET_DRAWER,
|
|
95
|
+
payload: { drawer: null },
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
99
|
+
const controller = new AbortController();
|
|
100
|
+
abortRef.current = controller;
|
|
101
|
+
const { signal } = controller;
|
|
102
|
+
const label = method === "POST" ? "create" : "update";
|
|
103
|
+
const file = files[0];
|
|
104
|
+
const text = await file.text();
|
|
105
|
+
const records = converter.csv2json(text);
|
|
106
|
+
if (!Array.isArray(records) || records.length === 0) {
|
|
107
|
+
showErrorToast("CSV file is empty or invalid");
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const validationErrors = [];
|
|
111
|
+
for (let i = 0; i < records.length; i++) {
|
|
112
|
+
const row = records[i];
|
|
113
|
+
const msgs = [];
|
|
114
|
+
if (method === "POST") {
|
|
115
|
+
const result = feeStructureFormValidation.safeParse(Object.assign(Object.assign({}, row), { amount: Number(row.amount) }));
|
|
116
|
+
if (!result.success) {
|
|
117
|
+
msgs.push(...result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
if (!((_b = row.id) === null || _b === void 0 ? void 0 : _b.trim()))
|
|
122
|
+
msgs.push("id is required for update");
|
|
123
|
+
}
|
|
124
|
+
if (msgs.length > 0) {
|
|
125
|
+
validationErrors.push({ row: i + 1, messages: msgs });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (validationErrors.length > 0) {
|
|
129
|
+
const summary = validationErrors
|
|
130
|
+
.slice(0, 5)
|
|
131
|
+
.map((e) => `Row ${e.row}: ${e.messages.join("; ")}`)
|
|
132
|
+
.join("\n");
|
|
133
|
+
const remaining = validationErrors.length - 5;
|
|
134
|
+
showErrorToast(`Validation failed for ${validationErrors.length} row(s).\n${summary}${remaining > 0 ? `\n...and ${remaining} more` : ""}`);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
showInfoToast(`Bulk ${label} job queued (${records.length} records). Processing...`);
|
|
139
|
+
let jobId;
|
|
140
|
+
try {
|
|
141
|
+
jobId = await submitBulkJob(text, method, signal);
|
|
142
|
+
}
|
|
143
|
+
catch (submitError) {
|
|
144
|
+
showErrorToast(`Failed to submit ${label} job: ${submitError instanceof Error ? submitError.message : "Unknown error"}`);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
const status = await pollBulkJob(jobId, signal, (processed, total) => {
|
|
148
|
+
showInfoToast(`Processing ${processed}/${total} fee structures...`);
|
|
149
|
+
});
|
|
150
|
+
if (signal.aborted)
|
|
151
|
+
return;
|
|
152
|
+
if (status.status === "completed") {
|
|
153
|
+
const r = status.results;
|
|
154
|
+
if (r && ((_c = r.errors) === null || _c === void 0 ? void 0 : _c.length) > 0) {
|
|
155
|
+
const summary = formatErrorSummary(r.errors);
|
|
156
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}\n${summary}`);
|
|
157
|
+
}
|
|
158
|
+
else if (r) {
|
|
159
|
+
showSuccessToast(`Created ${r.created} | Updated ${r.updated} | Skipped ${r.skipped}`);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
showSuccessToast("Bulk operation completed successfully");
|
|
163
|
+
}
|
|
164
|
+
invalidateFeeStructuresCache();
|
|
165
|
+
const schoolId = ((_d = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _d === void 0 ? void 0 : _d.id) || "";
|
|
166
|
+
fetch(`${FEE_STRUCTURE_API_ROUTES.LIST}?currentPage=1&pageLimit=${pageLimit}&schoolId=${schoolId}`, {
|
|
167
|
+
headers: {
|
|
168
|
+
"Content-Type": "application/json",
|
|
169
|
+
},
|
|
170
|
+
})
|
|
171
|
+
.then(async (res) => {
|
|
172
|
+
var _a, _b;
|
|
173
|
+
if (!res.ok)
|
|
174
|
+
return;
|
|
175
|
+
const data = await res.json();
|
|
176
|
+
dispatch({
|
|
177
|
+
type: FEE_STRUCTURE_ACTION_TYPES.SET_ITEMS,
|
|
178
|
+
payload: {
|
|
179
|
+
items: (_a = data.items) !== null && _a !== void 0 ? _a : [],
|
|
180
|
+
count: (_b = data.count) !== null && _b !== void 0 ? _b : 0,
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
})
|
|
184
|
+
.catch(() => { });
|
|
185
|
+
closeDrawer();
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
const r = status.results;
|
|
189
|
+
const detail = ((_e = r === null || r === void 0 ? void 0 : r.errors) === null || _e === void 0 ? void 0 : _e.length)
|
|
190
|
+
? formatErrorSummary(r.errors)
|
|
191
|
+
: "Unknown error";
|
|
192
|
+
showErrorToast(`Bulk ${label} failed.\n${detail}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
if (error.message === "Polling cancelled")
|
|
197
|
+
return;
|
|
198
|
+
showErrorToast(`Bulk ${label} failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
199
|
+
}
|
|
200
|
+
}, [dispatch]);
|
|
201
|
+
const handleBulkCreate = useCallback((files) => handleBulkFlow(files, "POST"), [handleBulkFlow]);
|
|
202
|
+
const handleBulkUpdate = useCallback((files) => handleBulkFlow(files, "PUT"), [handleBulkFlow]);
|
|
19
203
|
const create = [
|
|
20
204
|
{
|
|
21
205
|
id: "1",
|
|
22
206
|
title: t("downloadEmptyCsvTemplate"),
|
|
23
207
|
handleOnClick: async () => {
|
|
24
|
-
|
|
208
|
+
var _a;
|
|
209
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1);
|
|
25
210
|
},
|
|
26
211
|
},
|
|
27
212
|
{ id: "2", title: t("addYourDataToTheCsv") },
|
|
@@ -36,11 +221,14 @@ export const FeeStructureMoreActions = () => {
|
|
|
36
221
|
title: t("downloadPopulatedCsvTemplate"),
|
|
37
222
|
handleOnClick: async () => {
|
|
38
223
|
var _a;
|
|
39
|
-
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "");
|
|
224
|
+
await handleGetAllRecords(((_a = workspace === null || workspace === void 0 ? void 0 : workspace.school) === null || _a === void 0 ? void 0 : _a.id) || "", 1000);
|
|
40
225
|
},
|
|
41
226
|
},
|
|
42
227
|
{ id: "2", title: t("updateYourDataInTheCsv") },
|
|
43
|
-
{
|
|
228
|
+
{
|
|
229
|
+
id: "3",
|
|
230
|
+
title: t("uploadTheCompletedCsvToTheSystem"),
|
|
231
|
+
},
|
|
44
232
|
];
|
|
45
|
-
return (_jsxs("div", { className: "space-y-4", children: [_jsx(Timeline, { events: create, heading: t("bulkCreate") }), _jsx(Timeline, { events: update, heading: t("bulkUpdate") })] }));
|
|
233
|
+
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 })] }));
|
|
46
234
|
};
|