]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/staff/cat/vandelay/import.component.ts
LP#1800481 Vandelay import form templates
[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.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             return Promise.resolve(this.selectedQueue.id);
388         }
389     }
390
391     uploadFile(): Promise<any> {
392
393         if (this.vandelay.importSelection) {
394             // Nothing to upload when processing pre-queued records.
395             return Promise.resolve();
396         }
397         
398         const formData: FormData = new FormData();
399
400         formData.append('ses', this.auth.token());
401         formData.append('marc_upload', 
402             this.selectedFile, this.selectedFile.name);
403
404         if (this.selectedBibSource) {
405             formData.append('bib_source', ''+this.selectedBibSource);
406         }
407
408         const req = new HttpRequest('POST', VANDELAY_UPLOAD_PATH, formData, 
409             {reportProgress: true, responseType: 'text'});
410
411         return this.http.request(req).pipe(tap(
412             evt => {
413                 if (evt.type === HttpEventType.UploadProgress) {
414                     this.uploadProgress.update(
415                         {value: evt.loaded, max: evt.total});
416
417                 } else if (evt instanceof HttpResponse) {
418                     this.sessionKey = evt.body as string;
419                     console.log(
420                         'Vandelay file uploaded OK with key '+this.sessionKey);
421                 }
422             },
423
424             (err: HttpErrorResponse) => {
425                 console.error(err);
426                 this.toast.danger(err.error);
427             }
428         )).toPromise();
429     }
430
431     processSpool():  Promise<any> {
432
433         if (this.vandelay.importSelection) {
434             // Nothing to enqueue when processing pre-queued records
435             return Promise.resolve();
436         }
437
438         const method = `open-ils.vandelay.${this.recordType}.process_spool`;
439
440         return new Promise((resolve, reject) => {
441             this.net.request(
442                 'open-ils.vandelay', method, 
443                 this.auth.token(), this.sessionKey, this.activeQueueId,
444                 null, null, this.selectedBibSource, 
445                 (this.sessionName || null), true
446             ).subscribe(
447                 tracker => {
448                     const e = this.evt.parse(tracker);
449                     if (e) { console.error(e); return reject(); }
450
451                     // Spooling is in progress, track the results.
452                     this.vandelay.pollSessionTracker(tracker.id())
453                     .subscribe(
454                         trkr => {
455                             this.enqueueProgress.update({
456                                 // enqueue API only tracks actions performed
457                                 max: null, 
458                                 value: trkr.actions_performed()
459                             });
460                         },
461                         err => { console.log(err); reject(); },
462                         () => {
463                             this.enqueueProgress.update({max: 1, value: 1});
464                             resolve();
465                         }
466                     );
467                 }
468             );
469         });
470     }
471
472     importRecords(): Promise<any> {
473
474         if (!this.importActionSelected()) {
475             return Promise.resolve();
476         }
477
478         const selection = this.vandelay.importSelection;
479
480         if (selection && !selection.importQueue) {
481             return this.importRecordQueue(selection.recordIds);
482         } else {
483             return this.importRecordQueue();
484         }
485     }
486
487     importRecordQueue(recIds?: number[]): Promise<any> {
488         const rtype = this.recordType === 'bib' ? 'bib' : 'auth';
489
490         let method = `open-ils.vandelay.${rtype}_queue.import`;
491         const options: ImportOptions = this.compileImportOptions();
492
493         let target: number | number[] = this.activeQueueId;
494         if (recIds && recIds.length) {
495             method = `open-ils.vandelay.${rtype}_record.list.import`;
496             target = recIds;
497         }
498
499         return new Promise((resolve, reject) => {
500             this.net.request('open-ils.vandelay', 
501                 method, this.auth.token(), target, options)
502             .subscribe(
503                 tracker => {
504                     const e = this.evt.parse(tracker);
505                     if (e) { console.error(e); return reject(); }
506
507                     // Spooling is in progress, track the results.
508                     this.vandelay.pollSessionTracker(tracker.id())
509                     .subscribe(
510                         trkr => {
511                             this.importProgress.update({
512                                 max: trkr.total_actions(),
513                                 value: trkr.actions_performed()
514                             });
515                         },
516                         err => { console.log(err); reject(); },
517                         () => {
518                             this.importProgress.update({max: 1, value: 1});
519                             resolve();
520                         }
521                     );
522                 }
523             );
524         });
525     }
526
527     compileImportOptions(): ImportOptions {
528
529         const options: ImportOptions = {
530             session_key: this.sessionKey,
531             import_no_match: this.importNonMatching,
532             auto_overlay_exact: this.mergeOnExact,
533             auto_overlay_best_match: this.mergeOnBestMatch,
534             auto_overlay_1match: this.mergeOnSingleMatch,
535             opp_acq_copy_overlay: this.autoOverlayAcqCopies,
536             merge_profile: this.selectedMergeProfile,
537             fall_through_merge_profile: this.selectedFallThruMergeProfile,
538             strip_field_groups: this.selectedTrashGroups,
539             match_quality_ratio: this.minQualityRatio,
540             exit_early: true
541         };
542
543         if (this.vandelay.importSelection) {
544             options.overlay_map = this.vandelay.importSelection.overlayMap;
545         }
546
547         return options;
548     }
549
550     clearSelection() {
551         this.vandelay.importSelection = null;
552         this.startQueueId = null;
553     }
554
555     openQueue() {
556         console.log('opening queue ' + this.activeQueueId);
557     }
558
559     saveTemplate() {
560
561         const template = {};
562         TEMPLATE_ATTRS.forEach(key => template[key] = this[key]);
563
564         console.debug("Saving import profile", template);
565
566         this.formTemplates[this.selectedTemplate] = template;
567         return this.store.setItem(TEMPLATE_SETTING_NAME, this.formTemplates);
568     }
569
570     markTemplateDefault() {
571         
572         Object.keys(this.formTemplates).forEach(
573             name => delete this.formTemplates.default
574         );
575
576         this.formTemplates[this.selectedTemplate].default = true;
577
578         return this.store.setItem(TEMPLATE_SETTING_NAME, this.formTemplates);
579     }
580
581     templateSelectorChange(entry: ComboboxEntry) {
582
583         if (!entry) {
584             this.selectedTemplate = '';
585             return;
586         }
587
588         this.selectedTemplate = entry.label; // label == name
589
590         if (entry.freetext) {
591             // User is entering a new template name.
592             // Nothing to apply.
593             return;
594         }
595
596         // User selected an existing template, apply it to the form.
597
598         const template = this.formTemplates[entry.id];
599
600         // Copy the template values into "this"
601         TEMPLATE_ATTRS.forEach(key => this[key] = template[key]);
602
603         // Some values must be manually passed to the combobox'es
604
605         this.recordTypeSelector.applyEntryId(this.recordType);
606         this.bibSourceSelector.applyEntryId(this.selectedBibSource);
607         this.matchSetSelector.applyEntryId(this.selectedMatchSet);
608         this.holdingsProfileSelector
609             .applyEntryId(this.selectedHoldingsProfile);
610         this.mergeProfileSelector.applyEntryId(this.selectedMergeProfile);
611         this.fallThruMergeProfileSelector
612             .applyEntryId(this.selectedFallThruMergeProfile);
613     }
614
615     deleteTemplate() {
616         delete this.formTemplates[this.selectedTemplate];
617         this.formTemplateSelector.selected = null;
618         return this.store.setItem(TEMPLATE_SETTING_NAME, this.formTemplates);
619     }
620 }
621