]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/cat/vandelay/import.component.ts
cd51da658d4380869773227f6e154502da83312f
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / staff / cat / vandelay / import.component.ts
1 import {Component, OnInit, AfterViewInit, Input, ViewChild, OnDestroy} from '@angular/core';
2 import {tap} from 'rxjs/operators/tap';
3 import {IdlObject} from '@eg/core/idl.service';
4 import {NetService} from '@eg/core/net.service';
5 import {EventService} from '@eg/core/event.service';
6 import {OrgService} from '@eg/core/org.service';
7 import {AuthService} from '@eg/core/auth.service';
8 import {ToastService} from '@eg/share/toast/toast.service';
9 import {ComboboxComponent, 
10     ComboboxEntry} from '@eg/share/combobox/combobox.component';
11 import {VandelayService, VandelayImportSelection,
12   VANDELAY_UPLOAD_PATH} from './vandelay.service';
13 import {HttpClient, HttpRequest, HttpEventType} from '@angular/common/http';
14 import {HttpResponse, HttpErrorResponse} from '@angular/common/http';
15 import {ProgressInlineComponent} from '@eg/share/dialog/progress-inline.component';
16 import {Subject} from 'rxjs/Subject';
17 import {ServerStoreService} from '@eg/core/server-store.service';
18
19 const TEMPLATE_SETTING_NAME = 'eg.cat.vandelay.import.templates';
20
21 const TEMPLATE_ATTRS = [
22     'recordType',
23     'selectedBibSource',
24     'selectedMatchSet',
25     'mergeOnExact',
26     'importNonMatch',
27     'mergeOnBestMatch',
28     'mergeOnSingleMatch',
29     'autoOverlayAcqCopies',
30     'selectedHoldingsProfile',
31     'selectedMergeProfile',
32     'selectedFallThruMergeProfile',
33     'selectedTrashGroups',
34     'minQualityRatio'
35 ];
36
37 interface ImportOptions {
38     session_key: string;
39     overlay_map?: {[qrId: number]: /* breId */ number};
40     import_no_match?: boolean;
41     auto_overlay_exact?: boolean;
42     auto_overlay_best_match?: boolean;
43     auto_overlay_1match?: boolean;
44     opp_acq_copy_overlay?: boolean;
45     merge_profile?: any;
46     fall_through_merge_profile?: any;
47     strip_field_groups?: number[];
48     match_quality_ratio: number,
49     exit_early: boolean;
50 }
51
52 @Component({
53   templateUrl: 'import.component.html'
54 })
55 export class ImportComponent implements OnInit, AfterViewInit, OnDestroy {
56
57     recordType: string;
58     selectedQueue: ComboboxEntry; // freetext enabled
59
60     // used for applying a default queue ID value when we have
61     // a load-time queue before the queue combobox entries exist.
62     startQueueId: number; 
63
64     bibTrashGroups: IdlObject[];
65     selectedTrashGroups: number[];
66
67     activeQueueId: number;
68     selectedBucket: number;
69     selectedBibSource: number;
70     selectedMatchSet: number;
71     selectedHoldingsProfile: number;
72     selectedMergeProfile: number;
73     selectedFallThruMergeProfile: number;
74     selectedFile: File;
75
76     defaultMatchSet: string;
77
78     importNonMatching: boolean;
79     mergeOnExact: boolean;
80     mergeOnSingleMatch: boolean;
81     mergeOnBestMatch: boolean;
82     minQualityRatio: number;
83     autoOverlayAcqCopies: boolean;
84
85     // True after the first upload, then remains true.
86     showProgress: boolean;
87
88     // Upload in progress.
89     isUploading: boolean;
90
91     // True only after successful upload
92     uploadComplete: boolean;
93
94     // Upload / processsing session key
95     // Generated by the server
96     sessionKey: string;
97
98     // Optional enqueue/import tracker session name.
99     sessionName: string;
100
101     selectedTemplate: string;
102     formTemplates: {[name: string]: any};
103     newTemplateName: string;
104
105     @ViewChild('fileSelector') private fileSelector;
106     @ViewChild('uploadProgress') 
107         private uploadProgress: ProgressInlineComponent;
108     @ViewChild('enqueueProgress') 
109         private enqueueProgress: ProgressInlineComponent;
110     @ViewChild('importProgress') 
111         private importProgress: ProgressInlineComponent;
112
113     // Need these refs so values can be applied via external stimuli
114     @ViewChild('formTemplateSelector') 
115         private formTemplateSelector: ComboboxComponent;
116     @ViewChild('recordTypeSelector')
117         private recordTypeSelector: ComboboxComponent;
118     @ViewChild('bibSourceSelector')
119         private bibSourceSelector: ComboboxComponent;
120     @ViewChild('matchSetSelector')
121         private matchSetSelector: ComboboxComponent;
122     @ViewChild('holdingsProfileSelector')
123         private holdingsProfileSelector: ComboboxComponent;
124     @ViewChild('mergeProfileSelector')
125         private mergeProfileSelector: ComboboxComponent;
126     @ViewChild('fallThruMergeProfileSelector')
127         private fallThruMergeProfileSelector: ComboboxComponent;
128
129     constructor(
130         private http: HttpClient,
131         private toast: ToastService,
132         private evt: EventService,
133         private net: NetService,
134         private auth: AuthService,
135         private org: OrgService,
136         private store: ServerStoreService,
137         private vandelay: VandelayService
138     ) {
139         this.applyDefaults();
140     }
141
142     applyDefaults() {
143         this.minQualityRatio = 0;
144         this.selectedBibSource = 1; // default to system local
145         this.recordType = 'bib';
146         this.bibTrashGroups = [];
147         this.formTemplates = {};
148
149         if (this.vandelay.importSelection) {
150
151             if (!this.vandelay.importSelection.queue) {
152                 // Incomplete import selection, clear it.
153                 this.vandelay.importSelection = null;
154                 return;
155             }
156
157             const queue = this.vandelay.importSelection.queue;
158             this.recordType = queue.queue_type();
159             this.selectedMatchSet = queue.match_set();
160
161             // This will be propagated to selectedQueue as a combobox
162             // entry via the combobox
163             this.startQueueId = queue.id();
164
165             if (this.recordType === 'bib') {
166                 this.selectedBucket = queue.match_bucket();
167                 this.selectedHoldingsProfile = queue.item_attr_def();
168             }
169         }
170     }
171
172     ngOnInit() {}
173
174     ngAfterViewInit() {
175         this.loadStartupData();
176     }
177
178     ngOnDestroy() {
179         // If we successfully completed the most recent 
180         // upload/import assume the importSelection can be cleared.
181         if (this.uploadComplete) {
182             this.clearSelection();
183         }
184     }
185
186     importSelection(): VandelayImportSelection {
187         return this.vandelay.importSelection;
188     }
189
190     loadStartupData(): Promise<any> {
191         // Note displaying and manipulating a progress dialog inside
192         // the AfterViewInit cycle leads to errors because the child
193         // component is modifed after dirty checking.
194
195         const promises = [
196             this.vandelay.getMergeProfiles(),
197             this.vandelay.getAllQueues('bib'),
198             this.vandelay.getAllQueues('authority'),
199             this.vandelay.getMatchSets('bib'),
200             this.vandelay.getMatchSets('authority'),
201             this.vandelay.getBibBuckets(),
202             this.vandelay.getBibSources(),
203             this.vandelay.getItemImportDefs(),
204             this.vandelay.getBibTrashGroups().then(
205                 groups => this.bibTrashGroups = groups),
206             this.org.settings(['vandelay.default_match_set']).then(
207                 s => this.defaultMatchSet = s['vandelay.default_match_set']),
208             this.loadTemplates()
209         ];
210
211         return Promise.all(promises);
212     }
213
214     loadTemplates() {
215         this.store.getItem(TEMPLATE_SETTING_NAME).then(
216             templates => {
217                 this.formTemplates = templates || {};
218
219                 Object.keys(this.formTemplates).forEach(name => {
220                     if (this.formTemplates[name].default) {
221                         this.selectedTemplate = name;
222                     }
223                 });
224             }
225         );
226     }
227
228     formatTemplateEntries(): ComboboxEntry[] {
229         const entries = [];
230
231         Object.keys(this.formTemplates || {}).forEach(
232             name => entries.push({id: name, label: name}));
233
234         return entries;
235     }
236
237     // Format typeahead data sets
238     formatEntries(etype: string): ComboboxEntry[] {
239         const rtype = this.recordType;
240         let list;
241
242         switch (etype) {
243             case 'bibSources':
244                 return (this.vandelay.bibSources || []).map(
245                     s => { return {id: s.id(), label: s.source()}; });
246
247             case 'bibBuckets':
248                 list = this.vandelay.bibBuckets;
249                 break;
250
251             case 'allQueues':
252                 list = this.vandelay.allQueues[rtype];
253                 break;
254
255             case 'matchSets':
256                 list = this.vandelay.matchSets[rtype];
257                 break;
258
259             case 'importItemDefs':
260                 list = this.vandelay.importItemAttrDefs;
261                 break;
262
263             case 'mergeProfiles':
264                 list = this.vandelay.mergeProfiles;
265                 break;
266         }
267
268         return (list || []).map(item => {
269             return {id: item.id(), label: item.name()};
270         });
271     }
272
273     selectEntry($event: ComboboxEntry, etype: string) {
274         const id = $event ? $event.id : null;
275
276         switch (etype) {
277             case 'recordType':
278                 this.recordType = id;
279               
280             case 'bibSources':
281                 this.selectedBibSource = id;
282                 break;
283
284             case 'bibBuckets':
285                 this.selectedBucket = id;
286                 break;
287
288             case 'matchSets':
289                 this.selectedMatchSet = id;
290                 break;
291
292             case 'importItemDefs':
293                 this.selectedHoldingsProfile = id;
294                 break;
295
296             case 'mergeProfiles':
297                 this.selectedMergeProfile = id;
298                 break;
299
300             case 'FallThruMergeProfile':
301                 this.selectedFallThruMergeProfile = id;
302                 break;
303         }
304     }
305
306     fileSelected($event) {
307        this.selectedFile = $event.target.files[0]; 
308     }
309
310     // Required form data varies depending on context.
311     hasNeededData(): boolean {
312         if (this.vandelay.importSelection) {
313             return this.importActionSelected();
314         } else {
315             return this.selectedQueue 
316                 && Boolean(this.recordType) && Boolean(this.selectedFile)
317         }
318     }
319
320     importActionSelected(): boolean {
321         return this.importNonMatching
322             || this.mergeOnExact
323             || this.mergeOnSingleMatch
324             || this.mergeOnBestMatch;
325     }
326
327     // 1. create queue if necessary
328     // 2. upload MARC file
329     // 3. Enqueue MARC records
330     // 4. Import records
331     upload() {
332         this.sessionKey = null;
333         this.showProgress = true;
334         this.isUploading = true;
335         this.uploadComplete = false;
336         this.resetProgressBars();
337
338         this.resolveQueue()
339         .then(
340             queueId => {
341                 this.activeQueueId = queueId;
342                 return this.uploadFile();
343             },
344             err => Promise.reject('queue create failed')
345         ).then(
346             ok => this.processSpool(),
347             err => Promise.reject('process spool failed')
348         ).then(
349             ok => this.importRecords(),
350             err => Promise.reject('import records failed')
351         ).then(
352             ok => {
353                 this.isUploading = false;
354                 this.uploadComplete = true;
355             },
356             err => {
357                 console.log('file upload failed: ', err);
358                 this.isUploading = false;
359                 this.resetProgressBars();
360
361             }
362         );
363     }
364
365     resetProgressBars() {
366         this.uploadProgress.update({value: 0, max: 1});
367         this.enqueueProgress.update({value: 0, max: 1});
368         this.importProgress.update({value: 0, max: 1});
369     }
370
371     // Extract selected queue ID or create a new queue when requested.
372     resolveQueue(): Promise<number> {
373
374         if (this.selectedQueue && this.selectedQueue.freetext) {
375             // Free text queue selector means create a new entry.
376             // TODO: first check for name dupes
377
378             return this.vandelay.createQueue(
379                 this.selectedQueue.label,
380                 this.recordType,
381                 this.selectedHoldingsProfile,
382                 this.selectedMatchSet,
383                 this.selectedBucket
384             );
385
386         } else {
387             var queue_id = this.startQueueId;
388             if (this.selectedQueue) queue_id = this.selectedQueue.id;
389             return Promise.resolve(queue_id);
390         }
391     }
392
393     uploadFile(): Promise<any> {
394
395         if (this.vandelay.importSelection) {
396             // Nothing to upload when processing pre-queued records.
397             return Promise.resolve();
398         }
399         
400         const formData: FormData = new FormData();
401
402         formData.append('ses', this.auth.token());
403         formData.append('marc_upload', 
404             this.selectedFile, this.selectedFile.name);
405
406         if (this.selectedBibSource) {
407             formData.append('bib_source', ''+this.selectedBibSource);
408         }
409
410         const req = new HttpRequest('POST', VANDELAY_UPLOAD_PATH, formData, 
411             {reportProgress: true, responseType: 'text'});
412
413         return this.http.request(req).pipe(tap(
414             evt => {
415                 if (evt.type === HttpEventType.UploadProgress) {
416                     this.uploadProgress.update(
417                         {value: evt.loaded, max: evt.total});
418
419                 } else if (evt instanceof HttpResponse) {
420                     this.sessionKey = evt.body as string;
421                     console.log(
422                         'Vandelay file uploaded OK with key '+this.sessionKey);
423                 }
424             },
425
426             (err: HttpErrorResponse) => {
427                 console.error(err);
428                 this.toast.danger(err.error);
429             }
430         )).toPromise();
431     }
432
433     processSpool():  Promise<any> {
434
435         if (this.vandelay.importSelection) {
436             // Nothing to enqueue when processing pre-queued records
437             return Promise.resolve();
438         }
439         var spoolType = this.recordType;
440         if (this.recordType == 'authority') spoolType = 'auth'
441
442         const method = `open-ils.vandelay.${spoolType}.process_spool`;
443
444         return new Promise((resolve, reject) => {
445             this.net.request(
446                 'open-ils.vandelay', method, 
447                 this.auth.token(), this.sessionKey, this.activeQueueId,
448                 null, null, this.selectedBibSource, 
449                 (this.sessionName || null), true
450             ).subscribe(
451                 tracker => {
452                     const e = this.evt.parse(tracker);
453                     if (e) { console.error(e); return reject(); }
454
455                     // Spooling is in progress, track the results.
456                     this.vandelay.pollSessionTracker(tracker.id())
457                     .subscribe(
458                         trkr => {
459                             this.enqueueProgress.update({
460                                 // enqueue API only tracks actions performed
461                                 max: null, 
462                                 value: trkr.actions_performed()
463                             });
464                         },
465                         err => { console.log(err); reject(); },
466                         () => {
467                             this.enqueueProgress.update({max: 1, value: 1});
468                             resolve();
469                         }
470                     );
471                 }
472             );
473         });
474     }
475
476     importRecords(): Promise<any> {
477
478         if (!this.importActionSelected()) {
479             return Promise.resolve();
480         }
481
482         const selection = this.vandelay.importSelection;
483
484         if (selection && !selection.importQueue) {
485             return this.importRecordQueue(selection.recordIds);
486         } else {
487             return this.importRecordQueue();
488         }
489     }
490
491     importRecordQueue(recIds?: number[]): Promise<any> {
492         const rtype = this.recordType === 'bib' ? 'bib' : 'auth';
493
494         let method = `open-ils.vandelay.${rtype}_queue.import`;
495         const options: ImportOptions = this.compileImportOptions();
496
497         let target: number | number[] = this.activeQueueId;
498         if (recIds && recIds.length) {
499             method = `open-ils.vandelay.${rtype}_record.list.import`;
500             target = recIds;
501         }
502
503         return new Promise((resolve, reject) => {
504             this.net.request('open-ils.vandelay', 
505                 method, this.auth.token(), target, options)
506             .subscribe(
507                 tracker => {
508                     const e = this.evt.parse(tracker);
509                     if (e) { console.error(e); return reject(); }
510
511                     // Spooling is in progress, track the results.
512                     this.vandelay.pollSessionTracker(tracker.id())
513                     .subscribe(
514                         trkr => {
515                             this.importProgress.update({
516                                 max: trkr.total_actions(),
517                                 value: trkr.actions_performed()
518                             });
519                         },
520                         err => { console.log(err); reject(); },
521                         () => {
522                             this.importProgress.update({max: 1, value: 1});
523                             resolve();
524                         }
525                     );
526                 }
527             );
528         });
529     }
530
531     compileImportOptions(): ImportOptions {
532
533         const options: ImportOptions = {
534             session_key: this.sessionKey,
535             import_no_match: this.importNonMatching,
536             auto_overlay_exact: this.mergeOnExact,
537             auto_overlay_best_match: this.mergeOnBestMatch,
538             auto_overlay_1match: this.mergeOnSingleMatch,
539             opp_acq_copy_overlay: this.autoOverlayAcqCopies,
540             merge_profile: this.selectedMergeProfile,
541             fall_through_merge_profile: this.selectedFallThruMergeProfile,
542             strip_field_groups: this.selectedTrashGroups,
543             match_quality_ratio: this.minQualityRatio,
544             exit_early: true
545         };
546
547         if (this.vandelay.importSelection) {
548             options.overlay_map = this.vandelay.importSelection.overlayMap;
549         }
550
551         return options;
552     }
553
554     clearSelection() {
555         this.vandelay.importSelection = null;
556         this.startQueueId = null;
557     }
558
559     openQueue() {
560         console.log('opening queue ' + this.activeQueueId);
561     }
562
563     saveTemplate() {
564
565         const template = {};
566         TEMPLATE_ATTRS.forEach(key => template[key] = this[key]);
567
568         console.debug("Saving import profile", template);
569
570         this.formTemplates[this.selectedTemplate] = template;
571         return this.store.setItem(TEMPLATE_SETTING_NAME, this.formTemplates);
572     }
573
574     markTemplateDefault() {
575         
576         Object.keys(this.formTemplates).forEach(
577             name => delete this.formTemplates.default
578         );
579
580         this.formTemplates[this.selectedTemplate].default = true;
581
582         return this.store.setItem(TEMPLATE_SETTING_NAME, this.formTemplates);
583     }
584
585     templateSelectorChange(entry: ComboboxEntry) {
586
587         if (!entry) {
588             this.selectedTemplate = '';
589             return;
590         }
591
592         this.selectedTemplate = entry.label; // label == name
593
594         if (entry.freetext) {
595             // User is entering a new template name.
596             // Nothing to apply.
597             return;
598         }
599
600         // User selected an existing template, apply it to the form.
601
602         const template = this.formTemplates[entry.id];
603
604         // Copy the template values into "this"
605         TEMPLATE_ATTRS.forEach(key => this[key] = template[key]);
606
607         // Some values must be manually passed to the combobox'es
608
609         this.recordTypeSelector.applyEntryId(this.recordType);
610         this.bibSourceSelector.applyEntryId(this.selectedBibSource);
611         this.matchSetSelector.applyEntryId(this.selectedMatchSet);
612         this.holdingsProfileSelector
613             .applyEntryId(this.selectedHoldingsProfile);
614         this.mergeProfileSelector.applyEntryId(this.selectedMergeProfile);
615         this.fallThruMergeProfileSelector
616             .applyEntryId(this.selectedFallThruMergeProfile);
617     }
618
619     deleteTemplate() {
620         delete this.formTemplates[this.selectedTemplate];
621         this.formTemplateSelector.selected = null;
622         return this.store.setItem(TEMPLATE_SETTING_NAME, this.formTemplates);
623     }
624 }
625