generated from hack4impact-uiuc/mern-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProfile.jsx
314 lines (284 loc) · 10.3 KB
/
Profile.jsx
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
309
310
311
312
313
314
// @flow
import React, { useState, useEffect } from 'react';
import { Link, useParams, Redirect } from 'react-router-dom';
import { Form, Message, Icon, Button, Card } from 'semantic-ui-react';
import _ from 'lodash';
import Page from '../components/layout/Page';
import TextAttribute from '../components/EditableAttribute/TextAttribute';
import EnumAttribute from '../components/EditableAttribute/EnumAttribute';
import BooleanAttribute from '../components/EditableAttribute/BooleanAttribute';
import DateAttribute from '../components/EditableAttribute/DateAttribute';
import '../css/Profile.css';
import {
getMemberByID,
getMemberEnumOptions,
getMemberPermissionsByID,
getMemberSchemaTypes,
updateMember,
createMember,
} from '../utils/apiWrapper';
import { requiredFields } from '../utils/consts';
/**
* @constant
* @type {number}
*/
const SUCCESS_MESSAGE_POPUP_TIME_MS = 4000;
/**
* Checks if the given API responses were successful
* @param {...any} responses Any amount of response objects
*/
const areResponsesSuccessful = (...responses) => {
let success = true;
responses.forEach((response) => {
if (response == null || response.data == null || !response.data.success)
success = false;
});
return success;
};
const Profile = () => {
const { memberID } = useParams();
const newUser = memberID === 'new';
const [newUserID, setNewUserID] = useState(false);
// Upstream user is the DB version. Local user captures local changes made to the user.
const [upstreamUser, setUpstreamUser] = useState({});
const [localUser, setLocalUser] = useState({});
const [errorMessage, setErrorMessage] = useState(null);
const [successMessage, setSuccessMessage] = useState(null);
const [enumOptions, setEnumOptions] = useState({});
const [schemaTypes, setSchemaTypes] = useState({});
const [userPermissions, setUserPermissions] = useState({
view: [],
edit: [],
});
useEffect(() => {
async function getUserData() {
if (memberID == null) return;
const responses = [];
let memberDataResponse = null;
if (!newUser) {
memberDataResponse = await getMemberByID(memberID);
responses.push(memberDataResponse);
}
const memberPermissionResponse = await getMemberPermissionsByID(memberID);
const memberSchemaResponse = await getMemberSchemaTypes();
const enumOptionsResponse = await getMemberEnumOptions();
responses.push(
enumOptionsResponse,
memberSchemaResponse,
memberPermissionResponse,
);
if (!areResponsesSuccessful(...responses)) {
setErrorMessage('An error occurred while retrieving member data.');
return;
}
if (!newUser && memberDataResponse !== null) {
setUpstreamUser(memberDataResponse.data.result);
setLocalUser(memberDataResponse.data.result);
}
setUserPermissions(memberPermissionResponse.data.result);
setSchemaTypes(memberSchemaResponse.data.result);
setEnumOptions(enumOptionsResponse.data.result);
setErrorMessage(null);
}
getUserData();
}, [memberID, newUser]);
// Returns true if the member attribute is of the given type.
// Type is a string defined by mongoose. See https://mongoosejs.com/docs/schematypes.html
const isOfType = (attribute, type) => {
if (!schemaTypes || !type || !schemaTypes[type]) return false;
return schemaTypes[type].includes(attribute);
};
const onAttributeChange = (value, attributeLabel) => {
setLocalUser({
...localUser,
[attributeLabel]: value,
});
};
const createUpdatedUser = () => {
const updatedUser = {};
userPermissions.edit.forEach((field) => {
updatedUser[field] = localUser[field];
});
return updatedUser;
};
const setTemporarySuccessMessage = (contents) => {
setSuccessMessage(contents);
setTimeout(() => setSuccessMessage(null), SUCCESS_MESSAGE_POPUP_TIME_MS);
};
const submitChanges = async () => {
let missingFields = false;
requiredFields.forEach((field) => {
if (!localUser[field]) {
missingFields = true;
}
});
if (missingFields) return;
const result = newUser
? await createMember(createUpdatedUser())
: await updateMember(createUpdatedUser(), upstreamUser._id);
if (!areResponsesSuccessful(result)) {
setErrorMessage(
`An error occured${
result &&
result.error &&
result.error.response &&
result.error.response.data
? `: ${result.error.response.data.message}`
: '.'
}`,
);
setSuccessMessage(null);
} else {
setTemporarySuccessMessage(newUser ? 'User Created' : 'User updated');
setErrorMessage(null);
setUpstreamUser(result.data.result);
if (newUser) setNewUserID(result.data.result._id);
}
};
return (
<Page
title={
<>
<Link to="/">Members</Link> / {upstreamUser.firstName}{' '}
{upstreamUser.lastName}
</>
}
>
{/* Redirects to the new member page immediately after creating and getting a success response */}
{newUserID && <Redirect to={`/member/${newUserID}`} />}
<Card fluid>
<Card.Content>
<Card.Header>Profile</Card.Header>
<Form fluid className="profile-form" onSubmit={submitChanges}>
<div className="form-grid">
{
// Main content
userPermissions.view.map((attribute) => {
if (isOfType(attribute, 'Number')) {
return (
<TextAttribute
type="number"
value={localUser[attribute]}
key={attribute}
attributeLabel={attribute}
className="attribute"
onChange={onAttributeChange}
isDisabled={!userPermissions.edit.includes(attribute)}
isRequired={requiredFields.includes(attribute)}
/>
);
}
if (isOfType(attribute, 'Enum')) {
return (
<EnumAttribute
value={localUser[attribute]}
valueOptions={enumOptions[attribute]}
key={attribute}
attributeLabel={attribute}
className="attribute"
onChange={onAttributeChange}
isDisabled={!userPermissions.edit.includes(attribute)}
/>
);
}
if (isOfType(attribute, 'Boolean')) {
return (
<BooleanAttribute
value={localUser[attribute]}
key={attribute}
attributeLabel={attribute}
className="attribute"
onChange={onAttributeChange}
isDisabled={!userPermissions.edit.includes(attribute)}
/>
);
}
if (isOfType(attribute, 'Date')) {
return (
<DateAttribute
value={Date.parse(localUser[attribute])}
key={attribute}
attributeLabel={attribute}
onChange={onAttributeChange}
className="attribute"
isDisabled={!userPermissions.edit.includes(attribute)}
isRequired={requiredFields.includes(attribute)}
/>
);
}
if (isOfType(attribute, 'String')) {
return (
<TextAttribute
type="text"
value={localUser[attribute]}
attributeLabel={attribute}
className="attribute"
key={attribute}
onChange={onAttributeChange}
isDisabled={!userPermissions.edit.includes(attribute)}
isRequired={requiredFields.includes(attribute)}
/>
);
}
return <div key={attribute} />;
})
}
</div>
{
// Message displayed upon successfully updating member
successMessage ? (
<div className="profile-alert">
<Message icon big positive>
<Icon name="thumbs up" />
<Message.Content>
<Message.Header>
{newUser ? 'Create User' : 'Update'} Succeeded!
</Message.Header>
{successMessage}
</Message.Content>
</Message>
</div>
) : (
<div />
)
}
{
// Message displayed upon receiving an error response
errorMessage !== null && errorMessage !== undefined ? (
<div className="profile-alert">
<Message className="profile-alert" icon big negative>
<Icon name="warning circle" />
<Message.Content>
<Message.Header>
{newUser ? 'Create User' : 'Update'} Failed!
</Message.Header>
{errorMessage}
</Message.Content>
</Message>
</div>
) : (
<div />
)
}
{userPermissions.edit.length > 0 ? (
<>
<Button
size="big"
id="submit-button"
disabled={_.isEqual(upstreamUser, localUser)}
type="large"
onClick={submitChanges}
>
{newUser ? 'Create User' : 'Update'}
</Button>
</>
) : (
<div />
)}
</Form>
</Card.Content>
</Card>
</Page>
);
};
export default Profile;