-
Notifications
You must be signed in to change notification settings - Fork 12
/
UserForm.jsx
293 lines (272 loc) · 10.4 KB
/
UserForm.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
import React from 'react';
import { withTranslation } from 'react-i18next';
import alertifyjs from 'alertifyjs';
import {
TextField, Button, IconButton, FormControlLabel, Checkbox
} from '@mui/material';
import { Add as AddIcon } from '@mui/icons-material';
import {
set, get, isEmpty, cloneDeep, merge, map, pullAt, isEqual, uniq, without, includes,
} from 'lodash';
import APIService from '../../services/APIService';
import { arrayToObject, isAdminUser, getCurrentUserUsername, recordGAUpsertEvent } from '../../common/utils';
import { AUTH_GROUPS } from '../../common/constants';
import ExtrasForm from '../common/ExtrasForm';
const EXTRAS_MODEL = {key: '', value: ''}
class UserForm extends React.Component {
constructor(props) {
super(props);
this.state = {
isAdminUser: isAdminUser(),
isUserEditingSelf: false,
fieldErrors: {},
fields: {
username: '',
first_name: '',
last_name: '',
email: '',
company: '',
location: '',
extras: [cloneDeep(EXTRAS_MODEL)],
auth_groups: [],
}
}
}
componentDidMount() {
if(this.props.edit && this.props.user)
this.setFieldsForEdit()
}
setFieldsForEdit() {
const { user } = this.props;
const attrs = ['username', 'first_name', 'last_name', 'email', 'company', 'location', 'auth_groups']
const newState = {...this.state}
attrs.forEach(attr => set(newState.fields, attr, get(user, attr, '') || ''))
if(newState.fields.first_name === '-')
newState.fields.first_name = ''
if(newState.fields.last_name === '-')
newState.fields.last_name = ''
newState.fields.extras = isEmpty(user.extras) ? newState.fields.extras : map(user.extras, (v, k) => ({key: k, value: v}))
newState.isUserEditingSelf = getCurrentUserUsername() === user.username
this.setState(newState);
}
onTextFieldChange = event => this.setFieldValue(event.target.id, event.target.value)
onAuthGroupChange = event => {
const group = event.target.id
const applied = event.target.checked
let groups = cloneDeep(this.state.fields.auth_groups)
if(applied)
groups = uniq([...groups, group])
else
groups = without(groups, group)
this.setFieldValue('fields.auth_groups', groups)
}
setFieldValue(id, value) {
const newState = {...this.state}
set(newState, id, value)
const fieldName = get(id.split('fields.'), '1')
if(fieldName && !isEmpty(value) && get(newState.fieldErrors, fieldName))
newState.fieldErrors[fieldName] = null
this.setState(newState)
}
onAddExtras = () => {
this.setFieldValue('fields.extras', [...this.state.fields.extras, cloneDeep(EXTRAS_MODEL)])
}
onDeleteExtras = index => {
const newState = {...this.state}
pullAt(newState.fields.extras, index)
this.setState(newState)
}
onExtrasChange = (index, key, value) => {
const newState = {...this.state}
if(key !== '__')
newState.fields.extras[index].key = key
if(value !== '__')
newState.fields.extras[index].value = value
this.setState(newState)
}
canEditAuthGroups = () => this.state.isAdminUser && !this.state.isUserEditingSelf
onSubmit = event => {
event.preventDefault();
event.stopPropagation();
const { edit, user } = this.props
let fields = cloneDeep(this.state.fields);
const form = document.getElementsByTagName('form')[0];
form.reportValidity()
const isFormValid = form.checkValidity()
if(isFormValid) {
recordGAUpsertEvent('User', edit)
fields.extras = arrayToObject(fields.extras)
if(!this.canEditAuthGroups() || (edit && isEqual(user.auth_groups, fields.auth_groups)))
delete fields.auth_groups;
if(edit) {
APIService.users(fields.username).put(fields, null, null, {includeAuthGroups: true, includeSubscribedOrgs: true}).then(response => this.handleSubmitResponse(response))
} else {
APIService.users().post(fields, null, null, {includeAuthGroups: true, includeSubscribedOrgs: true}).then(response => this.handleSubmitResponse(response))
}
}
}
handleSubmitResponse(response) {
const { edit, reloadOnSuccess, onCancel, loggedIn, t } = this.props
if(response.status === 201 || response.status === 200) { // success
if(loggedIn) this.updateCachedUserInfo(response.data)
const successMsg = edit ? t('user.home.profile.update_success_message') : t('user.home.profile.create_success_message');
const message = reloadOnSuccess ? successMsg + `. t('common.reloading')...` : successMsg;
onCancel();
alertifyjs.success(message, 1, () => {
if(reloadOnSuccess)
window.location.reload()
})
} else { // error
const genericError = get(response, '__all__')
if(genericError) {
alertifyjs.error(genericError.join('<br />'))
} else {
this.setState(
{fieldErrors: response || {}},
() => alertifyjs.error(t('common.fill_mandatory_fields'))
)
}
}
}
updateCachedUserInfo(updatedUser) {
localStorage.setItem(
'user',
JSON.stringify(merge(JSON.parse(localStorage.user), updatedUser))
)
}
render() {
const { fields, fieldErrors } = this.state;
const { onCancel, edit, t } = this.props;
const userTranslation = t('resources.user')
const editTranslation = t('common.edit')
const newTranslation = t('common.new')
const header = edit ? `${editTranslation} ${userTranslation}: ${fields.username}` : `${newTranslation} ${userTranslation}`;
return (
<div className='col-md-12' style={{marginBottom: '30px'}}>
<div className='col-md-12 no-side-padding'>
<h2>{header}</h2>
</div>
<div className='col-md-12 no-side-padding'>
<form>
{
!edit &&
<div className='col-md-12 no-side-padding'>
<TextField
error={Boolean(fieldErrors.username)}
id="fields.username"
label={t('user.auth.username')}
variant="outlined"
fullWidth
onChange={this.onTextFieldChange}
value={fields.username}
disabled={edit}
required
/>
</div>
}
<div className='col-md-12 no-side-padding' style={{marginTop: '15px', width: '100%'}}>
<TextField
id="fields.first_name"
label={t('user.home.profile.first_name')}
variant="outlined"
fullWidth
onChange={this.onTextFieldChange}
value={fields.first_name}
required
/>
</div>
<div className='col-md-12 no-side-padding' style={{marginTop: '15px', width: '100%'}}>
<TextField
id="fields.last_name"
label={t('user.home.profile.last_name')}
variant="outlined"
fullWidth
onChange={this.onTextFieldChange}
value={fields.last_name}
required
/>
</div>
<div className='col-md-12 no-side-padding' style={{marginTop: '15px', width: '100%'}}>
<TextField
id="fields.email"
label={t('common.email')}
variant="outlined"
fullWidth
onChange={this.onTextFieldChange}
value={fields.email}
required
type='email'
/>
</div>
<div className='col-md-12 no-side-padding' style={{marginTop: '15px', width: '100%'}}>
<TextField
id="fields.company"
label={t('common.company')}
variant="outlined"
fullWidth
onChange={this.onTextFieldChange}
value={fields.company}
/>
</div>
<div className='col-md-12 no-side-padding' style={{marginTop: '15px', width: '100%'}}>
<TextField
id="fields.location"
label={t('common.location')}
variant="outlined"
fullWidth
onChange={this.onTextFieldChange}
value={fields.location}
/>
</div>
{
this.canEditAuthGroups() &&
<div className='col-md-12' style={{marginTop: '15px', width: '100%'}}>
{
map(AUTH_GROUPS, group => (
<div className='col-md-4 no-side-padding' key={group.id}>
<FormControlLabel
control={<Checkbox checked={includes(fields.auth_groups, group.id)} onChange={this.onAuthGroupChange} id={group.id} name="fields.auth_groups" />}
label={group.name}
/>
</div>
))
}
</div>
}
<div className='col-md-12 no-side-padding' style={{marginTop: '15px', width: '100%'}}>
<div className='col-md-8'>
<h3>{t('common.custom_attributes')}</h3>
</div>
<div className='col-md-4' style={{textAlign: 'right'}}>
<IconButton color='primary' onClick={this.onAddExtras} size="large">
<AddIcon />
</IconButton>
</div>
{
map(fields.extras, (extra, index) => (
<div className='col-md-12 no-side-padding' key={index} style={index > 0 ? {marginTop: '5px', width: '100%'} : {width: '100%'}}>
<ExtrasForm
extra={extra}
index={index}
onChange={this.onExtrasChange}
onDelete={this.onDeleteExtras}
/>
</div>
))
}
</div>
<div className='col-md-12' style={{textAlign: 'center', margin: '15px 0'}}>
<Button style={{margin: '0 10px'}} color='primary' variant='outlined' type='submit' onClick={this.onSubmit}>
{edit ? t('common.update') : t('common.create')}
</Button>
<Button style={{margin: '0 10px'}} variant='outlined' onClick={onCancel}>
{t('common.cancel')}
</Button>
</div>
</form>
</div>
</div>
);
}
}
export default withTranslation('translations')(UserForm);