-
Notifications
You must be signed in to change notification settings - Fork 567
Expand file tree
/
Copy pathsection-upload-file-edit.component.ts
More file actions
577 lines (518 loc) · 21.2 KB
/
Copy pathsection-upload-file-edit.component.ts
File metadata and controls
577 lines (518 loc) · 21.2 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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import {
ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
ViewChild,
} from '@angular/core';
import { UntypedFormControl } from '@angular/forms';
import { AccessConditionOption } from '@dspace/core/config/models/config-access-condition-option.model';
import { SubmissionFormsModel } from '@dspace/core/config/models/config-submission-forms.model';
import { JsonPatchOperationPathCombiner } from '@dspace/core/json-patch/builder/json-patch-operation-path-combiner';
import { JsonPatchOperationsBuilder } from '@dspace/core/json-patch/builder/json-patch-operations-builder';
import { FormFieldModel } from '@dspace/core/shared/form/models/form-field.model';
import { SubmissionObject } from '@dspace/core/submission/models/submission-object.model';
import { WorkspaceitemSectionUploadObject } from '@dspace/core/submission/models/workspaceitem-section-upload.model';
import { WorkspaceitemSectionUploadFileObject } from '@dspace/core/submission/models/workspaceitem-section-upload-file.model';
import { SubmissionJsonPatchOperationsService } from '@dspace/core/submission/submission-json-patch-operations.service';
import { dateToISOFormat } from '@dspace/shared/utils/date.util';
import {
hasNoValue,
hasValue,
isNotEmpty,
isNotNull,
} from '@dspace/shared/utils/empty.util';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import {
DYNAMIC_FORM_CONTROL_TYPE_DATEPICKER,
DynamicDateControlValue,
DynamicDatePickerModel,
DynamicFormArrayModel,
DynamicFormControlCondition,
DynamicFormControlEvent,
DynamicFormControlModel,
DynamicFormGroupModel,
DynamicSelectModel,
MATCH_ENABLED,
OR_OPERATOR,
} from '@ng-dynamic-forms/core';
import { TranslateModule } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import {
filter,
mergeMap,
take,
} from 'rxjs/operators';
import { MetadataValue } from 'src/app/core/shared/metadata.models';
import { DynamicCustomSwitchModel } from 'src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.model';
import { BtnDisabledDirective } from '../../../../../shared/btn-disabled.directive';
import { FormBuilderService } from '../../../../../shared/form/builder/form-builder.service';
import { FormComponent } from '../../../../../shared/form/form.component';
import { FormService } from '../../../../../shared/form/form.service';
import { SubmissionService } from '../../../../submission.service';
import { SectionUploadService } from '../../section-upload.service';
import {
ALTERNATIVE_CONTENT_TAG,
POLICY_DEFAULT_WITH_LIST,
} from '../../section-upload-constants';
import {
BITSTREAM_ACCESS_CONDITION_GROUP_CONFIG,
BITSTREAM_ACCESS_CONDITION_GROUP_LAYOUT,
BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_CONFIG,
BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_LAYOUT,
BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_CONFIG,
BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_LAYOUT,
BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_CONFIG,
BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_LAYOUT,
BITSTREAM_FORM_ACCESS_CONDITION_TYPE_CONFIG,
BITSTREAM_FORM_ACCESS_CONDITION_TYPE_LAYOUT,
BITSTREAM_FORM_ALTERNATIVE_CONTENT,
BITSTREAM_FORM_ALTERNATIVE_CONTENT_LAYOUT,
BITSTREAM_FORM_PRIMARY,
BITSTREAM_FORM_PRIMARY_LAYOUT,
BITSTREAM_METADATA_FORM_GROUP_CONFIG,
BITSTREAM_METADATA_FORM_GROUP_LAYOUT,
} from './section-upload-file-edit.model';
/**
* This component represents the edit form for bitstream
*/
@Component({
selector: 'ds-submission-section-upload-file-edit',
styleUrls: ['./section-upload-file-edit.component.scss'],
templateUrl: './section-upload-file-edit.component.html',
imports: [
BtnDisabledDirective,
FormComponent,
TranslateModule,
],
})
export class SubmissionSectionUploadFileEditComponent
implements OnInit, OnDestroy {
/**
* The FormComponent reference
*/
@ViewChild('formRef') public formRef: FormComponent;
/**
* The indicator is the primary bitstream
* it will be null if no primary bitstream is set for the ORIGINAL bundle
* @type {boolean, null}
*/
isPrimary: boolean;
/**
* The indicator if is alternative content bitstream
* @type {boolean, null}
*/
isAlternativeContent: boolean;
/**
* The list of available access condition
* @type {Array}
*/
public availableAccessConditionOptions: any[];
/**
* The submission id
* @type {string}
*/
public collectionId: string;
/**
* Define if collection access conditions policy type :
* POLICY_DEFAULT_NO_LIST : is not possible to define additional access group/s for the single file
* POLICY_DEFAULT_WITH_LIST : is possible to define additional access group/s for the single file
* @type {number}
*/
public collectionPolicyType: number;
/**
* The configuration for the bitstream's metadata form
* @type {SubmissionFormsModel}
*/
public configMetadataForm: SubmissionFormsModel;
/**
* The bitstream's metadata data
* @type {WorkspaceitemSectionUploadFileObject}
*/
public fileData: WorkspaceitemSectionUploadFileObject;
/**
* The bitstream id
* @type {string}
*/
public fileId: string;
/**
* The bitstream array key
* @type {string}
*/
public fileIndex: string;
/**
* The form id
* @type {string}
*/
public formId: string;
/**
* The section id
* @type {string}
*/
public sectionId: string;
/**
* The submission id
* @type {string}
*/
public submissionId: string;
/**
* The list of all available metadata
*/
formMetadata: string[] = [];
/**
* The form model
* @type {DynamicFormControlModel[]}
*/
formModel: DynamicFormControlModel[];
/**
* When `true` form controls are deactivated
*/
isSaving = false;
/**
* The [JsonPatchOperationPathCombiner] object
* @type {JsonPatchOperationPathCombiner}
*/
protected pathCombiner: JsonPatchOperationPathCombiner;
protected subscriptions: Subscription[] = [];
/**
* Initialize instance variables
*
* @param activeModal
* @param {ChangeDetectorRef} cdr
* @param {FormBuilderService} formBuilderService
* @param {FormService} formService
* @param {SubmissionService} submissionService
* @param {JsonPatchOperationsBuilder} operationsBuilder
* @param {SubmissionJsonPatchOperationsService} operationsService
* @param {SectionUploadService} uploadService
*/
constructor(
protected activeModal: NgbActiveModal,
private cdr: ChangeDetectorRef,
private formBuilderService: FormBuilderService,
private formService: FormService,
private submissionService: SubmissionService,
private operationsBuilder: JsonPatchOperationsBuilder,
private operationsService: SubmissionJsonPatchOperationsService,
private uploadService: SectionUploadService,
) {
}
/**
* Initialize form model values
*
* @param formModel
* The form model
*/
public initModelData(formModel: DynamicFormControlModel[]) {
const primaryBitstreamModel: any = this.formBuilderService.findById('primary', formModel, this.fileIndex);
primaryBitstreamModel.value = this.isPrimary || false;
const alternativeContentBitstreamModel: any = this.formBuilderService.findById('alternativeContent', formModel, this.fileIndex);
alternativeContentBitstreamModel.value = this.isAlternativeContent || false;
this.fileData.accessConditions.forEach((accessCondition, index) => {
Array.of('name', 'startDate', 'endDate')
.filter((key) => accessCondition.hasOwnProperty(key) && isNotEmpty(accessCondition[key]))
.forEach((key) => {
const metadataModel: any = this.formBuilderService.findById(key, formModel, index);
if (metadataModel) {
if (metadataModel.type === DYNAMIC_FORM_CONTROL_TYPE_DATEPICKER) {
const date = new Date(accessCondition[key]);
metadataModel.value = {
year: date.getUTCFullYear(),
month: date.getUTCMonth() + 1,
day: date.getUTCDate(),
};
} else {
metadataModel.value = accessCondition[key];
}
}
});
});
}
/**
* Dispatch form model update when changing an access condition
*
* @param event
* The event emitted
*/
onChange(event: DynamicFormControlEvent) {
if (event.model.id === 'name') {
this.setOptions(event.model, event.control);
}
}
onModalClose() {
this.activeModal.dismiss();
}
onSubmit() {
this.isSaving = true;
this.saveBitstreamData();
}
/**
* Update `startDate`, 'groupUUID' and 'endDate' model
*
* @param model
* The [[DynamicFormControlModel]] object
* @param control
* The [[FormControl]] object
*/
public setOptions(model: DynamicFormControlModel, control: UntypedFormControl) {
let accessCondition: AccessConditionOption = null;
this.availableAccessConditionOptions.filter((element) => element.name === control.value)
.forEach((element) => accessCondition = element );
if (isNotEmpty(accessCondition)) {
const startDateControl: UntypedFormControl = control.parent.get('startDate') as UntypedFormControl;
const endDateControl: UntypedFormControl = control.parent.get('endDate') as UntypedFormControl;
// Clear previous state
startDateControl?.markAsUntouched();
endDateControl?.markAsUntouched();
startDateControl?.setValue(null);
control.parent.markAsDirty();
endDateControl?.setValue(null);
}
}
/**
* Dispatch form model init
*/
ngOnInit() {
if (this.fileData && this.formId) {
this.formModel = this.buildFileEditForm();
this.cdr.detectChanges();
}
}
ngOnDestroy(): void {
this.unsubscribeAll();
}
protected retrieveValueFromField(field: any) {
const temp = Array.isArray(field) ? field[0] : field;
return (temp) ? temp.value : undefined;
}
/**
* Initialize form model
*/
protected buildFileEditForm() {
const configDescr: FormFieldModel = Object.assign({}, this.configMetadataForm.rows[0].fields[0]);
configDescr.repeatable = false;
const configForm = Object.assign({}, this.configMetadataForm, {
fields: Object.assign([], this.configMetadataForm.rows[0].fields[0], [
this.configMetadataForm.rows[0].fields[0],
configDescr,
]),
});
configForm.rows = configForm.rows.filter((row: any) => row.fields[0].selectableMetadata[0].metadata !== 'dc.type');
const formModel: DynamicFormControlModel[] = [];
formModel.push(new DynamicCustomSwitchModel(BITSTREAM_FORM_PRIMARY, BITSTREAM_FORM_PRIMARY_LAYOUT));
formModel.push(new DynamicCustomSwitchModel(BITSTREAM_FORM_ALTERNATIVE_CONTENT, BITSTREAM_FORM_ALTERNATIVE_CONTENT_LAYOUT));
const metadataGroupModelConfig = Object.assign({}, BITSTREAM_METADATA_FORM_GROUP_CONFIG);
metadataGroupModelConfig.group = this.formBuilderService.modelFromConfiguration(
this.submissionId,
configForm,
this.collectionId,
this.fileData.metadata,
this.submissionService.getSubmissionScope(),
);
formModel.push(new DynamicFormGroupModel(metadataGroupModelConfig, BITSTREAM_METADATA_FORM_GROUP_LAYOUT));
const accessConditionTypeModelConfig = Object.assign({}, BITSTREAM_FORM_ACCESS_CONDITION_TYPE_CONFIG);
const accessConditionsArrayConfig = Object.assign({}, BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_CONFIG);
const accessConditionTypeOptions = [];
if (this.collectionPolicyType === POLICY_DEFAULT_WITH_LIST) {
for (const accessCondition of this.availableAccessConditionOptions) {
accessConditionTypeOptions.push(
{
label: accessCondition.name,
value: accessCondition.name,
},
);
}
accessConditionTypeModelConfig.options = accessConditionTypeOptions;
// Dynamically assign of relation in config. For startDate and endDate.
const startDateCondition: DynamicFormControlCondition[] = [];
const endDateCondition: DynamicFormControlCondition[] = [];
let maxStartDate: DynamicDateControlValue;
let maxEndDate: DynamicDateControlValue;
this.availableAccessConditionOptions.forEach((condition) => {
if (condition.hasStartDate) {
startDateCondition.push({ id: 'name', value: condition.name });
if (condition.maxStartDate) {
const min = new Date(condition.maxStartDate);
maxStartDate = {
year: min.getUTCFullYear(),
month: min.getUTCMonth() + 1,
day: min.getUTCDate(),
};
}
}
if (condition.hasEndDate) {
endDateCondition.push({ id: 'name', value: condition.name });
if (condition.maxEndDate) {
const max = new Date(condition.maxEndDate);
maxEndDate = {
year: max.getUTCFullYear(),
month: max.getUTCMonth() + 1,
day: max.getUTCDate(),
};
}
}
});
const confStart = { relations: [{ match: MATCH_ENABLED, operator: OR_OPERATOR, when: startDateCondition }] };
const confEnd = { relations: [{ match: MATCH_ENABLED, operator: OR_OPERATOR, when: endDateCondition }] };
const hasStartDate = startDateCondition.length > 0;
const hasEndDate = endDateCondition.length > 0;
accessConditionsArrayConfig.groupFactory = () => {
const type = new DynamicSelectModel(accessConditionTypeModelConfig, BITSTREAM_FORM_ACCESS_CONDITION_TYPE_LAYOUT);
const startDateConfig = Object.assign({}, BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_CONFIG, confStart);
if (maxStartDate) {
startDateConfig.max = maxStartDate;
}
const endDateConfig = Object.assign({}, BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_CONFIG, confEnd);
if (maxEndDate) {
endDateConfig.max = maxEndDate;
}
const startDate = new DynamicDatePickerModel(startDateConfig, BITSTREAM_FORM_ACCESS_CONDITION_START_DATE_LAYOUT);
const endDate = new DynamicDatePickerModel(endDateConfig, BITSTREAM_FORM_ACCESS_CONDITION_END_DATE_LAYOUT);
const accessConditionGroupConfig = Object.assign({}, BITSTREAM_ACCESS_CONDITION_GROUP_CONFIG);
accessConditionGroupConfig.group = [type];
if (hasStartDate) {
accessConditionGroupConfig.group.push(startDate);
}
if (hasEndDate) {
accessConditionGroupConfig.group.push(endDate);
}
return [new DynamicFormGroupModel(accessConditionGroupConfig, BITSTREAM_ACCESS_CONDITION_GROUP_LAYOUT)];
};
// Number of access conditions blocks in form
accessConditionsArrayConfig.initialCount = isNotEmpty(this.fileData.accessConditions) ? this.fileData.accessConditions.length : 1;
formModel.push(
new DynamicFormArrayModel(accessConditionsArrayConfig, BITSTREAM_ACCESS_CONDITIONS_FORM_ARRAY_LAYOUT),
);
}
this.initModelData(formModel);
return formModel;
}
/**
* Save bitstream metadata
*/
saveBitstreamData() {
const pathFragment = ['files', this.fileIndex];
// validate form
this.formService.validateAllFormFields(this.formRef.formGroup);
const saveBitstreamDataSubscription = this.formService.isValid(this.formId).pipe(
take(1),
filter((isValid) => isValid),
mergeMap(() => this.formService.getFormData(this.formId)),
take(1),
mergeMap((formData: any) => {
this.uploadService.updatePrimaryBitstreamOperation(this.pathCombiner.getPath('primary'), this.isPrimary, formData.primary[0], this.fileId);
//Set operations to bitstream alternative content flag
const alternativeContentPath = 'metadata/dspace.bitstream.type';
if (formData.alternativeContent[0]) {
const metadata = Object.assign(new MetadataValue(), {
language: null,
value: ALTERNATIVE_CONTENT_TAG,
authority: null,
place: 0,
});
this.operationsBuilder.add(this.pathCombiner.getPath([...pathFragment, alternativeContentPath]), metadata, true);
} else {
this.operationsBuilder.remove(this.pathCombiner.getPath([...pathFragment, alternativeContentPath]));
}
// collect bitstream metadata
Object.keys((formData.metadata))
.filter((key) => isNotEmpty(formData.metadata[key]))
.forEach((key) => {
const metadataKey = key.replace(/_/g, '.');
if (metadataKey !== 'dc.type') {
const path = `metadata/${metadataKey}`;
this.operationsBuilder.add(this.pathCombiner.getPath([...pathFragment, path]), formData.metadata[key], true);
}
});
Object.keys((this.fileData.metadata))
.filter((key) => isNotEmpty(this.fileData.metadata[key]))
.filter((key) => hasNoValue(formData.metadata[key]))
.filter((key) => this.formMetadata.includes(key))
.forEach((key) => {
const metadataKey = key.replace(/_/g, '.');
if (metadataKey !== 'dc.type') {
const path = `metadata/${metadataKey}`;
this.operationsBuilder.remove(this.pathCombiner.getPath([...pathFragment, path]));
}
});
const accessConditionsToSave = [];
if (formData.hasOwnProperty('accessConditions')) {
formData.accessConditions
.filter((accessConditions) => isNotNull(accessConditions))
.map((accessConditions) => accessConditions.accessConditionGroup)
.filter((accessCondition) => isNotEmpty(accessCondition))
.forEach((accessCondition) => {
let accessConditionOpt;
this.availableAccessConditionOptions
.filter((element) => isNotNull(accessCondition.name) && element.name === accessCondition.name[0].value)
.forEach((element) => accessConditionOpt = element);
if (accessConditionOpt) {
const currentAccessCondition = Object.assign({}, accessCondition);
currentAccessCondition.name = this.retrieveValueFromField(accessCondition.name);
/* When start and end date fields are deactivated, their values may be still present in formData,
therefore it is necessary to delete them if they're not allowed by the current access condition option. */
if (!accessConditionOpt.hasStartDate) {
delete currentAccessCondition.startDate;
} else if (accessCondition.startDate) {
const startDate = this.retrieveValueFromField(accessCondition.startDate);
// Clamp the start date to the maximum, if any, since the
// datepicker sometimes exceeds it.
let startDateDate = new Date(startDate);
if (accessConditionOpt.maxStartDate) {
const maxStartDateDate = new Date(accessConditionOpt.maxStartDate);
if (startDateDate > maxStartDateDate) {
startDateDate = maxStartDateDate;
}
}
currentAccessCondition.startDate = dateToISOFormat(startDateDate);
}
if (!accessConditionOpt.hasEndDate) {
delete currentAccessCondition.endDate;
} else if (accessCondition.endDate) {
const endDate = this.retrieveValueFromField(accessCondition.endDate);
// Clamp the end date to the maximum, if any, since the
// datepicker sometimes exceeds it.
let endDateDate = new Date(endDate);
if (accessConditionOpt.maxEndDate) {
const maxEndDateDate = new Date(accessConditionOpt.maxEndDate);
if (endDateDate > maxEndDateDate) {
endDateDate = maxEndDateDate;
}
}
currentAccessCondition.endDate = dateToISOFormat(endDateDate);
}
accessConditionsToSave.push(currentAccessCondition);
}
});
}
if (isNotEmpty(accessConditionsToSave)) {
this.operationsBuilder.add(this.pathCombiner.getPath([...pathFragment, 'accessConditions']), accessConditionsToSave, true);
}
// dispatch a PATCH request to save metadata
return this.operationsService.jsonPatchByResourceID(
this.submissionService.getSubmissionObjectLinkName(),
this.submissionId,
this.pathCombiner.rootElement,
this.pathCombiner.subRootElement);
}),
).subscribe((result: SubmissionObject[]) => {
const section = result[0].sections[this.sectionId];
if (!section) {
return;
}
const uploadSection = (section as WorkspaceitemSectionUploadObject);
this.uploadService.updateFilePrimaryBitstream(this.submissionId, this.sectionId, uploadSection.primary);
Object.keys(uploadSection.files)
.filter((key) => uploadSection.files[key].uuid === this.fileId)
.forEach((key) => this.uploadService.updateFileData(
this.submissionId, this.sectionId, this.fileId, uploadSection.files[key]),
);
this.isSaving = false;
this.activeModal.close();
});
this.subscriptions.push(saveBitstreamDataSubscription);
}
private unsubscribeAll() {
this.subscriptions.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe());
}
}