-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathRecord.jsx
More file actions
308 lines (287 loc) · 11.4 KB
/
Record.jsx
File metadata and controls
308 lines (287 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import * as XLSX from 'xlsx';
export default function Record() {
const [form, setForm] = useState({
name: "",
position: "",
level: "",
});
const [isNew, setIsNew] = useState(true);
const params = useParams();
const navigate = useNavigate();
useEffect(() => {
async function fetchData() {
const id = params.id?.toString() || undefined;
if (!id) return;
setIsNew(false);
const response = await fetch(
`http://localhost:5050/record/${id}`
);
if (!response.ok) {
const message = `An error has occurred: ${response.statusText}`;
console.error(message);
return;
}
const record = await response.json();
if (!record) {
console.warn(`Record with id ${id} not found`);
navigate("/");
return;
}
setForm(record);
}
fetchData();
return;
}, [params.id, navigate]);
// These methods will update the state properties.
function updateForm(value) {
return setForm((prev) => {
return { ...prev, ...value };
});
}
// This function will handle the submission.
async function onSubmit(e) {
e.preventDefault();
const person = { ...form };
try {
let response;
if (isNew) {
response = await fetch("http://localhost:5050/record", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(person),
});
} else {
response = await fetch(`http://localhost:5050/record/${params.id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(person),
});
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch (error) {
console.error('A problem occurred adding or updating a record: ', error);
} finally {
setForm({ name: "", position: "", level: "" });
navigate("/");
}
}
const ExcelUpload = () => {
const [tableData, setTableData] = useState(null); // Store parsed Excel data
// Function to handle the file upload
const handleFileUpload = (e) => {
const file = e.target.files[0]; // Get the uploaded file
const reader = new FileReader();
reader.onload = (event) => {
const data = new Uint8Array(event.target.result);
const workbook = XLSX.read(data, { type: "array" });
const sheetName = workbook.SheetNames[0]; // Get the first sheet
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet); // Convert sheet to JSON
setTableData(jsonData); // Save parsed data to state for display and uploading
};
reader.readAsArrayBuffer(file);
};
// Function to handle uploading the parsed data to MongoDB
const handleDataUpload = async () => {
if (!tableData) {
alert("No data to upload");
return;
}
try {
const response = await fetch(`http://localhost:5050/record/upload`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(tableData), // Send JSON data to backend
});
if (response.ok) {
alert("Data uploaded successfully");
window.location.href = "/";
} else {
console.log(response)
alert("Failed to upload data");
}
} catch (error) {
console.error("Error uploading data:", error);
alert("Error occurred while uploading");
}
};
return (
<div>
{/* File Input */}
<input
type="file"
accept=".xlsx, .xls"
onChange={handleFileUpload}
className="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-violet-50 file:text-violet-700 hover:file:bg-violet-100"
/>
{/* Show table data if available */}
{tableData && (
<div>
<button
onClick={handleDataUpload}
className="inline-flex items-center justify-center whitespace-nowrap text-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-slate-100 hover:text-accent-foreground h-9 rounded-md px-3 cursor-pointer mt-4"
>
Upload to MongoDB
</button>
{/* Display the parsed data in a table */}
<table className="min-w-full mt-4 border border-gray-200">
<thead>
<tr>
{Object.keys(tableData[0]).map((key) => (
<th key={key} className="border p-2">{key}</th>
))}
</tr>
</thead>
<tbody>
{tableData.map((row, rowIndex) => (
<tr key={rowIndex}>
{Object.values(row).map((value, cellIndex) => (
<td key={cellIndex} className="border p-2">{value}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
};
return (
<>
<h3 className="text-lg font-semibold p-4">Create/Update Employee Record</h3>
<form onSubmit={onSubmit} className="border rounded-lg overflow-hidden p-4">
<div className="grid grid-cols-1 gap-x-8 gap-y-10 border-b border-slate-900/10 pb-12 md:grid-cols-2">
<div>
<h2 className="text-base font-semibold leading-7 text-slate-900">
Employee Info
</h2>
<p className="mt-1 text-sm leading-6 text-slate-600">
This information will be displayed publicly so be careful what you share.
</p>
</div>
<div className="grid max-w-2xl grid-cols-1 gap-x-6 gap-y-8 ">
<div className="sm:col-span-4">
<label
htmlFor="name"
className="block text-sm font-medium leading-6 text-slate-900"
>
Name
</label>
<div className="mt-2">
<div className="flex rounded-md shadow-sm ring-1 ring-inset ring-slate-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600 sm:max-w-md">
<input
type="text"
name="name"
id="name"
className="block flex-1 border-0 bg-transparent py-1.5 pl-1 text-slate-900 placeholder:text-slate-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="First Last"
value={form.name}
onChange={(e) => updateForm({ name: e.target.value })}
/>
</div>
</div>
</div>
<div className="sm:col-span-4">
<label
htmlFor="position"
className="block text-sm font-medium leading-6 text-slate-900"
>
Position
</label>
<div className="mt-2">
<div className="flex rounded-md shadow-sm ring-1 ring-inset ring-slate-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600 sm:max-w-md">
<input
type="text"
name="position"
id="position"
className="block flex-1 border-0 bg-transparent py-1.5 pl-1 text-slate-900 placeholder:text-slate-400 focus:ring-0 sm:text-sm sm:leading-6"
placeholder="Developer Advocate"
value={form.position}
onChange={(e) => updateForm({ position: e.target.value })}
/>
</div>
</div>
</div>
<div>
<fieldset className="mt-4">
<legend className="sr-only">Position Options</legend>
<div className="space-y-4 sm:flex sm:items-center sm:space-x-10 sm:space-y-0">
<div className="flex items-center">
<input
id="positionIntern"
name="positionOptions"
type="radio"
value="Intern"
className="h-4 w-4 border-slate-300 text-slate-600 focus:ring-slate-600 cursor-pointer"
checked={form.level === "Intern"}
onChange={(e) => updateForm({ level: e.target.value })}
/>
<label
htmlFor="positionIntern"
className="ml-3 block text-sm font-medium leading-6 text-slate-900 mr-4"
>
Intern
</label>
<input
id="positionJunior"
name="positionOptions"
type="radio"
value="Junior"
className="h-4 w-4 border-slate-300 text-slate-600 focus:ring-slate-600 cursor-pointer"
checked={form.level === "Junior"}
onChange={(e) => updateForm({ level: e.target.value })}
/>
<label
htmlFor="positionJunior"
className="ml-3 block text-sm font-medium leading-6 text-slate-900 mr-4"
>
Junior
</label>
<input
id="positionSenior"
name="positionOptions"
type="radio"
value="Senior"
className="h-4 w-4 border-slate-300 text-slate-600 focus:ring-slate-600 cursor-pointer"
checked={form.level === "Senior"}
onChange={(e) => updateForm({ level: e.target.value })}
/>
<label
htmlFor="positionSenior"
className="ml-3 block text-sm font-medium leading-6 text-slate-900 mr-4"
>
Senior
</label>
</div>
</div>
</fieldset>
</div>
</div>
</div>
<input
type="submit"
value="Save Employee Record"
className="inline-flex items-center justify-center whitespace-nowrap text-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-slate-100 hover:text-accent-foreground h-9 rounded-md px-3 cursor-pointer mt-4"
/>
</form>
<h3 className="text-lg font-semibold p-4">
Create Employee Records by uploading a file
</h3>
<form className="border rounded-lg overflow-hidden p-4" onSubmit={(e) => e.preventDefault()}>
<h2 className="text-base font-semibold leading-7 text-slate-900">Upload a File</h2>
<ExcelUpload />
</form>
</>
);
}