-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocument-upload-dialog.component.ts
More file actions
460 lines (392 loc) · 14.4 KB
/
document-upload-dialog.component.ts
File metadata and controls
460 lines (392 loc) · 14.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
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
import { HttpErrorResponse } from '@angular/common/http';
import { Component, EventEmitter, Inject, OnDestroy, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ToastService } from '../../services/toast/toast.service';
import { DEFAULT_DOCUMENT_SOURCES, DOCUMENT_SOURCE, DOCUMENT_TYPE, DocumentTypeDto } from '../document/document.dto';
import { FileHandle } from '../drag-drop-file/drag-drop-file.directive';
import { splitExtension } from '../utils/file';
import {
CreateDocumentDto,
SelectableOwnerDto,
SelectableParcelDto,
UpdateDocumentDto,
} from './document-upload-dialog.dto';
import { Subject } from 'rxjs';
import { DocumentUploadDialogData } from './document-upload-dialog.interface';
export enum VisibilityGroup {
INTERNAL = 'Internal',
PUBLIC = 'Public',
}
@Component({
selector: 'app-document-upload-dialog',
templateUrl: './document-upload-dialog.component.html',
styleUrls: ['./document-upload-dialog.component.scss'],
standalone: false
})
export class DocumentUploadDialogComponent implements OnInit, OnDestroy {
$destroy = new Subject<void>();
DOCUMENT_TYPE = DOCUMENT_TYPE;
title = 'Add';
isDirty = false;
isSaving = false;
allowsFileEdit = true;
@Output() uploadFiles: EventEmitter<FileHandle> = new EventEmitter();
name = new FormControl<string>('', [Validators.required]);
type = new FormControl<string | undefined>(undefined, [Validators.required]);
source = new FormControl<string>('', [Validators.required]);
parcelId = new FormControl<string | null>(null);
ownerId = new FormControl<string | null>(null);
visibleToInternal = new FormControl<boolean>(false, [Validators.required]);
visibleToPublic = new FormControl<boolean>(false, [Validators.required]);
documentTypes: DocumentTypeDto[] = [];
documentSources: DOCUMENT_SOURCE[] = [];
form = new FormGroup({
name: this.name,
type: this.type,
source: this.source,
visibleToInternal: this.visibleToInternal,
visibleToPublic: this.visibleToPublic,
parcelId: this.parcelId,
ownerId: this.ownerId,
});
pendingFile: File | undefined;
existingFile: { name: string; size: number } | undefined;
showSupersededWarning = false;
showHasVirusError = false;
showVirusScanFailedError = false;
extension = '';
internalVisibilityLabel = '';
selectableParcels: SelectableParcelDto[] = [];
selectableOwners: SelectableOwnerDto[] = [];
constructor(
@Inject(MAT_DIALOG_DATA)
public data: DocumentUploadDialogData,
protected dialog: MatDialogRef<any>,
private toastService: ToastService,
) {}
ngOnInit(): void {
this.loadDocumentTypes();
this.internalVisibilityLabel = this.buildInternalVisibilityLabel();
this.documentSources = this.data.allowedDocumentSources ?? DEFAULT_DOCUMENT_SOURCES;
if (this.data.defaultDocumentSource && this.documentSources.includes(this.data.defaultDocumentSource)) {
this.source.setValue(this.data.defaultDocumentSource);
} else if (this.documentSources.length === 1) {
this.source.setValue(this.documentSources[0]);
}
if (this.data.existingDocument) {
const document = this.data.existingDocument;
this.title = 'Edit';
this.allowsFileEdit = this.data.allowsFileEdit ?? this.allowsFileEdit;
if (document.type && this.data.documentTypeOverrides && this.data.documentTypeOverrides[document.type.code]) {
this.allowsFileEdit = !!this.data.documentTypeOverrides[document.type.code]?.allowsFileEdit;
}
if (document.type?.code === DOCUMENT_TYPE.CERTIFICATE_OF_TITLE) {
this.prepareCertificateOfTitleUpload(document.uuid);
}
if (document.type?.code === DOCUMENT_TYPE.CORPORATE_SUMMARY) {
this.prepareCorporateSummaryUpload(document.uuid);
}
const { fileName, extension } = splitExtension(document.fileName);
this.extension = extension;
this.form.patchValue({
name: fileName,
source: document.source,
visibleToInternal: !!(
document.visibilityFlags?.includes('A') ||
document.visibilityFlags?.includes('C') ||
document.visibilityFlags?.includes('G')
),
visibleToPublic: !!document.visibilityFlags?.includes('P'),
});
this.existingFile = { name: document.fileName, size: 0 };
if (this.data.documentService) {
this.type.setValue(document.type!.code);
}
}
if (this.data.decisionService) {
this.type.disable();
this.source.disable();
this.visibleToInternal.disable();
this.visibleToPublic.disable();
this.type.setValue(DOCUMENT_TYPE.DECISION_DOCUMENT);
this.source.setValue(DOCUMENT_SOURCE.ALC);
this.visibleToInternal.setValue(true);
this.visibleToPublic.setValue(true);
}
}
buildInternalVisibilityLabel(): string {
const ordinalsByWord = {
Applicant: 0,
'L/FNG': 1,
Commissioner: 2,
};
type Word = keyof typeof ordinalsByWord;
const wordsByFlag: {
A: Word;
G: Word;
C: Word;
} = {
A: 'Applicant',
G: 'L/FNG',
C: 'Commissioner',
};
const words = (
this.data.allowedVisibilityFlags?.reduce((words, flag) => {
if (flag !== 'P') {
words.push(wordsByFlag[flag]);
}
return words;
}, [] as Word[]) ?? []
).sort((word1, word2) => ordinalsByWord[word1] - ordinalsByWord[word2]);
if (words.length === 0) {
return '';
}
if (words.length === 1) {
return words[0];
}
if (words.length === 2) {
return `${words[0]} and ${words[1]}`;
}
return `${words.slice(0, -1).join(', ')}, and ${words[words.length - 1]}`;
}
async onSubmit() {
const file = this.pendingFile;
const visibilityFlags: ('A' | 'C' | 'G' | 'P')[] = [];
if (this.visibleToInternal.getRawValue()) {
for (const flag of this.data.allowedVisibilityFlags ?? []) {
if (flag !== 'P') {
visibilityFlags.push(flag);
}
}
}
if (this.visibleToPublic.getRawValue() && this.data.allowedVisibilityFlags?.includes('P')) {
visibilityFlags.push('P');
}
const dto: UpdateDocumentDto = {
fileName: this.name.value! + this.extension,
source: this.source.value as DOCUMENT_SOURCE,
typeCode: this.type.value as DOCUMENT_TYPE,
visibilityFlags,
ownerUuid: this.ownerId.value ?? undefined,
section: this.data.section ?? undefined,
chronologyEntryUuid: this.data.chronologyEntryUuid ?? undefined,
parcelUuid: this.parcelId.value ?? undefined,
};
if (file) {
const renamedFile = new File([file], this.name.value! + this.extension, { type: file.type });
this.isSaving = true;
if (this.data.existingDocument) {
if (this.data.decisionService && this.data.decisionUuid) {
await this.data.decisionService.deleteFile(this.data.decisionUuid, this.data.existingDocument.uuid);
} else if (this.data.documentService) {
await this.data.documentService.delete(this.data.existingDocument.uuid);
}
}
try {
if (this.data.decisionService && this.data.decisionUuid) {
await this.data.decisionService.uploadFile(this.data.decisionUuid, renamedFile);
} else if (this.data.documentService) {
await this.data.documentService.upload(this.data.fileId, { ...dto, file } as CreateDocumentDto);
}
} catch (err) {
this.toastService.showErrorToast('Document upload failed');
if (err instanceof HttpErrorResponse) {
if (err.status === 400) {
this.showHasVirusError = true;
} else if (err.status === 500) {
this.showVirusScanFailedError = true;
}
this.isSaving = false;
this.pendingFile = undefined;
return;
}
}
this.dialog.close(true);
this.isSaving = false;
} else if (this.data.existingDocument) {
this.isSaving = true;
if (this.data.decisionService && this.data.decisionUuid) {
await this.data.decisionService.updateFile(
this.data.decisionUuid,
this.data.existingDocument.uuid,
this.name.value! + this.extension,
);
} else if (this.data.documentService) {
await this.data.documentService.update(this.data.existingDocument.uuid, dto);
}
this.dialog.close(true);
this.isSaving = false;
}
}
async prepareCertificateOfTitleUpload(uuid?: string) {
this.source.setValue(DOCUMENT_SOURCE.APPLICANT);
// If fixedParcel is provided, use it and don't require validation
if (this.data.fixedParcel) {
this.parcelId.setValue(this.data.fixedParcel.uuid);
this.parcelId.clearValidators();
this.parcelId.updateValueAndValidity();
return;
}
if (!this.data.parcelService) {
// No parcel service, so no parcels, we will not require it
this.parcelId.clearValidators();
this.parcelId.updateValueAndValidity();
return;
}
this.selectableParcels = await this.data.parcelService.fetchParcels(this.data.fileId);
if (this.selectableParcels.length < 1) {
// No parcels available, we will not require it
this.parcelId.clearValidators();
this.parcelId.updateValueAndValidity();
return;
}
// We have parcels to select from now, so we will require it here
this.parcelId.setValidators([Validators.required]);
this.parcelId.updateValueAndValidity();
const selectedParcel = this.selectableParcels.find((parcel) => parcel.certificateOfTitleUuid === uuid);
if (selectedParcel) {
this.parcelId.setValue(selectedParcel.uuid);
} else if (uuid) {
this.showSupersededWarning = true;
}
}
async prepareCorporateSummaryUpload(uuid?: string) {
this.source.setValue(DOCUMENT_SOURCE.APPLICANT);
this.ownerId.setValidators([Validators.required]);
this.ownerId.updateValueAndValidity();
if (!this.data.submissionService) {
return;
}
const submission = await this.data.submissionService.fetchSubmission(this.data.fileId);
this.selectableOwners = submission.owners
.filter((owner) => owner.type.code === 'ORGZ')
.map((owner) => ({
...owner,
label: owner.organizationName ?? owner.displayName,
}));
if (this.selectableOwners.length < 1) {
return;
}
const selectedOwner = this.selectableOwners.find((owner) => owner.corporateSummaryUuid === uuid);
if (selectedOwner) {
this.ownerId.setValue(selectedOwner.uuid);
} else if (uuid) {
this.showSupersededWarning = true;
}
}
async onDocTypeSelected($event?: DocumentTypeDto) {
if (!$event) {
this.selectableParcels = [];
return;
}
if (this.data.documentTypeOverrides && this.data.documentTypeOverrides[$event.code]) {
for (const visibilityGroup of this.data.documentTypeOverrides[$event.code]?.visibilityGroups ?? []) {
if (visibilityGroup === VisibilityGroup.INTERNAL) {
this.visibleToInternal.setValue(true);
}
if (visibilityGroup === VisibilityGroup.PUBLIC) {
this.visibleToPublic.setValue(true);
}
}
}
if ($event.code === DOCUMENT_TYPE.CERTIFICATE_OF_TITLE) {
await this.prepareCertificateOfTitleUpload();
} else {
this.parcelId.setValue(null);
this.parcelId.setValidators([]);
this.parcelId.updateValueAndValidity();
this.selectableParcels = [];
}
if ($event.code === DOCUMENT_TYPE.CORPORATE_SUMMARY) {
await this.prepareCorporateSummaryUpload();
} else {
this.ownerId.setValue(null);
this.ownerId.setValidators([]);
this.ownerId.updateValueAndValidity();
}
}
filterDocumentTypes(term: string, item: DocumentTypeDto) {
const termLower = term.toLocaleLowerCase();
return (
item.label.toLocaleLowerCase().indexOf(termLower) > -1 ||
item.oatsCode.toLocaleLowerCase().indexOf(termLower) > -1
);
}
uploadFile(event: Event) {
const element = event.target as HTMLInputElement;
const selectedFiles = element.files;
if (selectedFiles && selectedFiles[0]) {
this.pendingFile = selectedFiles[0];
const { fileName, extension } = splitExtension(selectedFiles[0].name);
this.name.setValue(fileName);
this.extension = extension;
this.showHasVirusError = false;
this.showVirusScanFailedError = false;
}
}
onRemoveFile() {
this.pendingFile = undefined;
this.existingFile = undefined;
this.extension = '';
this.name.setValue('');
}
openFile() {
if (this.pendingFile) {
const fileURL = URL.createObjectURL(this.pendingFile);
window.open(fileURL, '_blank');
}
}
async openExistingFile() {
if (this.data.existingDocument) {
if (this.data.decisionService && this.data.decisionUuid) {
await this.data.decisionService.downloadFile(
this.data.decisionUuid,
this.data.existingDocument.uuid,
this.data.existingDocument.fileName,
true,
);
} else if (this.data.documentService) {
await this.data.documentService.download(
this.data.existingDocument.uuid,
this.data.existingDocument.fileName,
true,
);
}
}
}
filesDropped($event: FileHandle) {
this.pendingFile = $event.file;
const { fileName, extension } = splitExtension(this.pendingFile.name);
this.extension = extension;
this.name.setValue(fileName);
this.showHasVirusError = false;
this.showVirusScanFailedError = false;
this.uploadFiles.emit($event);
}
private async loadDocumentTypes() {
if (this.data.documentService) {
const docTypes = await this.data.documentService.fetchTypes(this.data.allowedDocumentTypes);
docTypes.sort((a, b) => (a.label > b.label ? 1 : -1));
this.documentTypes = docTypes.filter((type) => type.code !== DOCUMENT_TYPE.ORIGINAL_APPLICATION);
if (this.type.value === null && this.data.defaultDocumentType) {
this.type.setValue(this.data.defaultDocumentType);
} else if (this.documentTypes.length === 1) {
this.type.setValue(this.documentTypes[0].code);
}
} else if (this.data.decisionService) {
this.documentTypes = [
{
code: DOCUMENT_TYPE.DECISION_DOCUMENT,
label: 'Decision Package',
description: '',
oatsCode: '',
},
];
}
}
ngOnDestroy(): void {
this.$destroy.next();
this.$destroy.complete();
}
}