-
Notifications
You must be signed in to change notification settings - Fork 6
/
add-user.component.ts
339 lines (296 loc) · 9.62 KB
/
add-user.component.ts
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Inject,
Input,
OnInit,
Output,
} from '@angular/core';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import {
ApiResponseData,
ApiResponseError,
KnoraApiConnection,
ReadUser,
UserResponse,
UsersResponse,
} from '@dasch-swiss/dsp-js';
import { DspApiConnectionToken } from '@dasch-swiss/vre/shared/app-config';
import { AppErrorHandler } from '@dasch-swiss/vre/shared/app-error-handler';
import { ProjectService } from '@dasch-swiss/vre/shared/app-helper-services';
import { ProjectsSelectors } from '@dasch-swiss/vre/shared/app-state';
import { DialogComponent } from '@dsp-app/src/app/main/dialog/dialog.component';
import { existingNamesValidator } from '@dsp-app/src/app/main/directive/existing-name/existing-name.directive';
import { AutocompleteItem } from '@dsp-app/src/app/workspace/search/operator';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-add-user',
templateUrl: './add-user.component.html',
styleUrls: ['./add-user.component.scss'],
})
export class AddUserComponent implements OnInit {
/**
* project uuid to get existing team members
* or to know where to add selected user
*/
@Input() projectUuid: string;
/**
* event emitter, when the selected user will be added to the list
*/
@Output() refreshParent: EventEmitter<any> = new EventEmitter<any>();
/**
* status for the progress indicator
*/
loading = true;
/**
* form group
*/
selectUserForm: UntypedFormGroup;
/**
* form errors
*/
selectUserErrors = {
username: '',
};
/**
* form error hints
*/
validationMessages = {
username: {
existingName: "This user is already a member of the project. You can't add him / her.",
},
};
/**
* list of all users
*/
users: AutocompleteItem[] = [];
/**
* filter users while typing (autocomplete)
*/
filteredUsers: Observable<AutocompleteItem[]>;
/**
* list of usernames to prevent duplicate entries
*/
existingUsernames: [RegExp] = [new RegExp('anEmptyRegularExpressionWasntPossible')];
/**
* list of usernames of project members to prevent duplicate entries
*/
existingUsernameInProject: [RegExp] = [new RegExp('anEmptyRegularExpressionWasntPossible')];
/**
* list of emails to prevent duplicate entries
*/
existingEmails: [RegExp] = [new RegExp('anEmptyRegularExpressionWasntPossible')];
/**
* list of emails of project members to prevent duplicate entries
*/
existingEmailInProject: [RegExp] = [new RegExp('anEmptyRegularExpressionWasntPossible')];
/**
* selected user object
*/
selectedUser: ReadUser;
/**
* member status of selected user
*/
isAlreadyMember = false;
/**
* iri of the project; used for API requests
*/
projectIri: string;
constructor(
@Inject(DspApiConnectionToken)
private _dspApiConnection: KnoraApiConnection,
private _dialog: MatDialog,
private _errorHandler: AppErrorHandler,
private _formBuilder: UntypedFormBuilder,
private _projectService: ProjectService,
private _store: Store,
private _cd: ChangeDetectorRef
) {}
ngOnInit() {
this.projectIri = this._projectService.uuidToIri(this.projectUuid);
// build the form
this.buildForm();
}
buildForm(): void {
// clean autocomplete list
this.users = [];
// get all users
this._dspApiConnection.admin.usersEndpoint.getUsers().subscribe(
(response: ApiResponseData<UsersResponse>) => {
// if a user is already member of the team, mark it in the list
const members: string[] = [];
// get all members of this project
const projectMembers = this._store.selectSnapshot(ProjectsSelectors.projectMembers);
if (projectMembers[this.projectIri]) {
for (const m of projectMembers[this.projectIri].value) {
members.push(m.id);
// if the user is already member of the project
// add the email to the list of existing
this.existingEmailInProject.push(new RegExp(`(?:^|W)${m.email.toLowerCase()}(?:$|W)`));
// add username to the list of existing
this.existingUsernameInProject.push(new RegExp(`(?:^|W)${m.username.toLowerCase()}(?:$|W)`));
}
}
let i = 0;
for (const u of response.body.users) {
// if the user is already member of the project
// add the email to the list of existing
this.existingEmails.push(new RegExp(`(?:^|W)${u.email.toLowerCase()}(?:$|W)`));
// add username to the list of existing
this.existingUsernames.push(new RegExp(`(?:^|W)${u.username.toLowerCase()}(?:$|W)`));
let existsInProject = '';
if (members && members.indexOf(u.id) > -1) {
existsInProject = '* ';
}
this.users[i] = {
iri: u.id,
name: u.username,
label: `${existsInProject + u.username} | ${u.email} | ${u.givenName} ${u.familyName}`,
};
i++;
}
this.users.sort((u1: AutocompleteItem, u2: AutocompleteItem) => {
if (u1.label < u2.label) {
return -1;
} else if (u1.label > u2.label) {
return 1;
} else {
return 0;
}
});
this.loading = false;
this._cd.markForCheck();
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
this.selectUserForm = this._formBuilder.group({
username: new UntypedFormControl(
{
value: '',
disabled: false,
},
[
existingNamesValidator(this.existingUsernames),
existingNamesValidator(this.existingUsernameInProject),
existingNamesValidator(this.existingEmails),
existingNamesValidator(this.existingEmailInProject),
]
),
});
this.filteredUsers = this.selectUserForm.controls['username'].valueChanges.pipe(
startWith(''),
map(user => (user.length >= 2 ? this.filter(this.users, user) : []))
);
this.selectUserForm.valueChanges.subscribe(() => this.onValueChanged());
this.onValueChanged(); // (re)set validation messages now
}
/**
* filter a list while typing in auto complete input field
* @param list List of options
* @param name Value to filter by
* @returns Filtered list of options
*/
filter(list: AutocompleteItem[], name: string) {
return list.filter(user => user.label.toLowerCase().includes(name.toLowerCase()));
}
/**
* set the error messages on value changed
*/
onValueChanged() {
if (!this.selectUserForm) {
return;
}
// reset selected user
this.selectedUser = undefined;
// check if the form is valid
Object.keys(this.selectUserErrors).forEach(field => {
this.selectUserErrors[field] = '';
const control = this.selectUserForm.get(field);
if (control.value.length >= 2) {
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
Object.keys(control.errors).forEach(key => {
this.selectUserErrors[field] += `${messages[key]} `;
});
}
}
});
}
/**
* add user to the project
*
* @param val The value can be e-mail address or username
*/
addUser(val: string) {
// --> TODO add getUserByEmail
// you can type username or email. We have to check, what we have now
this._dspApiConnection.admin.usersEndpoint.getUserByUsername(val).subscribe(
(response: ApiResponseData<UserResponse>) => {
// case b) result if the user exists
this.selectedUser = response.body.user;
// the following request should never start
this.isAlreadyMember = !!response.body.user.projects.find(p => p.id === this.projectIri);
if (!this.isAlreadyMember) {
this.loading = true;
// add user to project
this._dspApiConnection.admin.usersEndpoint
.addUserToProjectMembership(this.selectedUser.id, this.projectIri)
.subscribe(
() => {
// successful post
// reload the component
this.buildForm();
this.refreshParent.emit();
this.loading = false;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
},
(error: ApiResponseError) => {
if (error.status === 404) {
// case c) user doesn't exist
// create new user user-profile
this.selectedUser = new ReadUser();
this.selectedUser.email = val;
} else {
// api error
this._errorHandler.showMessage(error);
}
}
);
}
openDialog(mode: string): void {
const dialogConfig: MatDialogConfig = {
width: '560px',
maxHeight: '80vh',
position: {
top: '112px',
},
data: {
project: this.projectUuid,
name: this.selectUserForm.controls['username'].value,
mode,
},
};
const dialogRef = this._dialog.open(DialogComponent, dialogConfig);
dialogRef.afterClosed().subscribe(() => {
// update the view
this.refreshParent.emit();
});
}
resetInput(ev: Event) {
ev.preventDefault();
this.selectUserForm.controls['username'].reset('');
}
}