LP2008252: Fix report output access when Shibboleth is enabled
[evergreen-equinox.git] / Open-ILS / src / eg2 / src / app / staff / catalog / hold / hold.component.ts
1 import {Component, OnInit, ViewChild} from '@angular/core';
2 import {Router, ActivatedRoute, ParamMap} from '@angular/router';
3 import {tap} from 'rxjs/operators';
4 import {EventService} from '@eg/core/event.service';
5 import {NetService} from '@eg/core/net.service';
6 import {AuthService} from '@eg/core/auth.service';
7 import {PcrudService} from '@eg/core/pcrud.service';
8 import {PermService} from '@eg/core/perm.service';
9 import {IdlObject} from '@eg/core/idl.service';
10 import {OrgService} from '@eg/core/org.service';
11 import {ServerStoreService} from '@eg/core/server-store.service';
12 import {BibRecordService, BibRecordSummary} from '@eg/share/catalog/bib-record.service';
13 import {CatalogService} from '@eg/share/catalog/catalog.service';
14 import {StaffCatalogService} from '../catalog.service';
15 import {HoldsService, HoldRequest,
16     HoldRequestTarget} from '@eg/staff/share/holds/holds.service';
17 import {ComboboxEntry, ComboboxComponent} from '@eg/share/combobox/combobox.component';
18 import {PatronService} from '@eg/staff/share/patron/patron.service';
19 import {PatronSearchDialogComponent
20   } from '@eg/staff/share/patron/search-dialog.component';
21 import {AlertDialogComponent} from '@eg/share/dialog/alert.component';
22 import {BarcodeSelectComponent
23     } from '@eg/staff/share/barcodes/barcode-select.component';
24 import {WorkLogService} from '@eg/staff/share/worklog/worklog.service';
25
26 class HoldContext {
27     holdMeta: HoldRequestTarget;
28     holdTarget: number;
29     lastRequest: HoldRequest;
30     canOverride?: boolean;
31     processing: boolean;
32     selectedFormats: any;
33     success = false;
34
35     constructor(target: number) {
36         this.holdTarget = target;
37         this.processing = false;
38         this.selectedFormats = {
39            // code => selected-boolean
40            formats: {},
41            langs: {}
42         };
43     }
44
45     clone(target: number): HoldContext {
46         const ctx = new HoldContext(target);
47         ctx.holdMeta = this.holdMeta;
48         return ctx;
49     }
50 }
51
52 @Component({
53   templateUrl: 'hold.component.html'
54 })
55 export class HoldComponent implements OnInit {
56
57     holdType: string;
58     holdTargets: number[];
59     user: IdlObject; //
60     userBarcode: string;
61     requestor: IdlObject;
62     holdFor: string;
63     pickupLib: number;
64     notifyEmail: boolean;
65     notifyPhone: boolean;
66     phoneValue: string;
67     notifySms: boolean;
68     smsValue: string;
69     suspend: boolean;
70     activeDateStr: string;
71     activeDateYmd: string;
72     activeDate: Date;
73     activeDateInvalid = false;
74
75     holdContexts: HoldContext[];
76     recordSummaries: BibRecordSummary[];
77
78     currentUserBarcode: string;
79     smsCarriers: ComboboxEntry[];
80     userBarcodeTimeout: number;
81
82     smsEnabled: boolean;
83
84     maxMultiHolds = 0;
85
86     // True if mult-copy holds are active for the current receipient.
87     multiHoldsActive = false;
88
89     canPlaceMultiAt: number[] = [];
90     multiHoldCount = 1;
91     placeHoldsClicked: boolean;
92     badBarcode: string = null;
93
94     puLibWsFallback = false;
95     puLibWsDefault = false;
96
97     // Orgs which are not valid pickup locations
98     disableOrgs: number[] = [];
99
100     @ViewChild('patronSearch', {static: false})
101       patronSearch: PatronSearchDialogComponent;
102
103     @ViewChild('smsCbox', {static: false}) smsCbox: ComboboxComponent;
104     @ViewChild('barcodeSelect') private barcodeSelect: BarcodeSelectComponent;
105
106     @ViewChild('activeDateAlert') private activeDateAlert: AlertDialogComponent;
107
108     constructor(
109         private router: Router,
110         private route: ActivatedRoute,
111         private evt: EventService,
112         private net: NetService,
113         private org: OrgService,
114         private store: ServerStoreService,
115         private auth: AuthService,
116         private pcrud: PcrudService,
117         private bib: BibRecordService,
118         private cat: CatalogService,
119         private staffCat: StaffCatalogService,
120         private holds: HoldsService,
121         private patron: PatronService,
122         private perm: PermService,
123         private worklog: WorkLogService
124     ) {
125         this.holdContexts = [];
126         this.smsCarriers = [];
127     }
128
129     ngOnInit() {
130
131         // Respond to changes in hold type.  This currently assumes hold
132         // types only toggle post-init between copy-level types (C,R,F)
133         // and no other params (e.g. target) change with it.  If other
134         // types require tracking, additional data collection may be needed.
135         this.route.paramMap.subscribe(
136             (params: ParamMap) => this.holdType = params.get('type'));
137
138         this.holdType = this.route.snapshot.params['type'];
139         this.holdTargets = this.route.snapshot.queryParams['target'];
140         this.holdFor = this.route.snapshot.queryParams['holdFor'] || 'patron';
141
142         if (this.staffCat.holdForBarcode) {
143             this.holdFor = 'patron';
144             this.userBarcode = this.staffCat.holdForBarcode;
145         }
146
147         this.store.getItemBatch([
148             'circ.staff_placed_holds_fallback_to_ws_ou',
149             'circ.staff_placed_holds_default_to_ws_ou'
150         ]).then(settings => {
151             this.puLibWsFallback =
152                 settings['circ.staff_placed_holds_fallback_to_ws_ou'] === true;
153             this.puLibWsDefault =
154                 settings['circ.staff_placed_holds_default_to_ws_ou'] === true;
155         }).then(_ => this.worklog.loadSettings());
156
157         this.org.list().forEach(org => {
158             if (org.ou_type().can_have_vols() === 'f') {
159                 this.disableOrgs.push(org.id());
160             }
161         });
162
163         this.net.request('open-ils.actor',
164             'open-ils.actor.settings.value_for_all_orgs',
165             null, 'opac.holds.org_unit_not_pickup_lib'
166         ).subscribe(resp => {
167             if (resp.summary.value) {
168                 this.disableOrgs.push(Number(resp.org_unit));
169             }
170         });
171
172         if (!Array.isArray(this.holdTargets)) {
173             this.holdTargets = [this.holdTargets];
174         }
175
176         this.holdTargets = this.holdTargets.map(t => Number(t));
177
178         this.requestor = this.auth.user();
179         this.pickupLib = this.auth.user().ws_ou();
180
181         this.resetForm();
182
183         this.getRequestorSetsAndPerms()
184         .then(_ => {
185
186             // Load receipient data if we have any.
187             if (this.staffCat.holdForBarcode) {
188                 this.holdFor = 'patron';
189                 this.userBarcode = this.staffCat.holdForBarcode;
190             }
191
192             if (this.holdFor === 'staff' || this.userBarcode) {
193                 this.holdForChanged();
194             }
195         });
196
197         setTimeout(() => {
198             const node = document.getElementById('patron-barcode');
199             if (node) { node.focus(); }
200         });
201     }
202
203     getRequestorSetsAndPerms(): Promise<any> {
204
205         return this.org.settings(
206             ['sms.enable', 'circ.holds.max_duplicate_holds'])
207
208         .then(sets => {
209
210             this.smsEnabled = sets['sms.enable'];
211
212             const max = Number(sets['circ.holds.max_duplicate_holds']);
213             if (Number(max) > 0) { this.maxMultiHolds = Number(max); }
214
215             if (this.smsEnabled) {
216
217                 return this.patron.getSmsCarriers().then(carriers => {
218                     carriers.forEach(carrier => {
219                         this.smsCarriers.push({
220                             id: carrier.id(),
221                             label: carrier.name()
222                         });
223                     });
224                 });
225             }
226
227         }).then(_ => {
228
229             if (this.maxMultiHolds) {
230
231                 // Multi-copy holds are supported.  Let's see where this
232                 // requestor has permission to take advantage of them.
233                 return this.perm.hasWorkPermAt(
234                     ['CREATE_DUPLICATE_HOLDS'], true).then(perms =>
235                     this.canPlaceMultiAt = perms['CREATE_DUPLICATE_HOLDS']);
236             }
237         });
238     }
239
240     holdCountRange(): number[] {
241         return [...Array(this.maxMultiHolds).keys()].map(n => n + 1);
242     }
243
244     // Load the bib, call number, copy, etc. data associated with each target.
245     getTargetMeta(): Promise<any> {
246
247         return new Promise(resolve => {
248             this.holds.getHoldTargetMeta(this.holdType, this.holdTargets, this.auth.user().ws_ou())
249             .subscribe(
250                 meta => {
251                     this.holdContexts.filter(ctx => ctx.holdTarget === meta.target)
252                     .forEach(ctx => {
253                         ctx.holdMeta = meta;
254                         this.mrFiltersToSelectors(ctx);
255                     });
256                 },
257                 err => {},
258                 () => resolve(null)
259             );
260         });
261     }
262
263     // By default, all metarecord filters options are enabled.
264     mrFiltersToSelectors(ctx: HoldContext) {
265         if (this.holdType !== 'M') { return; }
266
267         const meta = ctx.holdMeta;
268         if (meta.metarecord_filters) {
269             if (meta.metarecord_filters.formats) {
270                 meta.metarecord_filters.formats.forEach(
271                     ccvm => ctx.selectedFormats.formats[ccvm.code()] = true);
272             }
273             if (meta.metarecord_filters.langs) {
274                 meta.metarecord_filters.langs.forEach(
275                     ccvm => ctx.selectedFormats.langs[ccvm.code()] = true);
276             }
277         }
278     }
279
280     // Map the selected metarecord filters optoins to a JSON-encoded
281     // list of attr filters as required by the API.
282     // Compiles a blob of
283     // {target: JSON({"0": [{_attr: ctype, _val: code}, ...], "1": [...]})}
284     // TODO: this should live in the hold service, not in the UI code.
285     mrSelectorsToFilters(ctx: HoldContext): {[target: number]: string} {
286
287         const meta = ctx.holdMeta;
288         const slf = ctx.selectedFormats;
289         const result: any = {};
290
291         const formats = Object.keys(slf.formats)
292             .filter(code => Boolean(slf.formats[code])); // user-selected
293
294         const langs = Object.keys(slf.langs)
295             .filter(code => Boolean(slf.langs[code])); // user-selected
296
297         const compiled: any = {};
298
299         if (formats.length > 0) {
300             compiled['0'] = [];
301             formats.forEach(code => {
302                 const ccvm = meta.metarecord_filters.formats.filter(
303                     format => format.code() === code)[0];
304                 compiled['0'].push({
305                     _attr: ccvm.ctype(),
306                     _val: ccvm.code()
307                 });
308             });
309         }
310
311         if (langs.length > 0) {
312             compiled['1'] = [];
313             langs.forEach(code => {
314                 const ccvm = meta.metarecord_filters.langs.filter(
315                     format => format.code() === code)[0];
316                 compiled['1'].push({
317                     _attr: ccvm.ctype(),
318                     _val: ccvm.code()
319                 });
320             });
321         }
322
323         if (Object.keys(compiled).length > 0) {
324             const res = {};
325             res[ctx.holdTarget] = JSON.stringify(compiled);
326             return res;
327         }
328
329         return null;
330     }
331
332     holdForChanged() {
333         this.user = null;
334
335         if (this.holdFor === 'patron') {
336             if (this.userBarcode) {
337                 this.userBarcodeChanged();
338             }
339         } else {
340             this.userBarcode = null;
341             this.currentUserBarcode = null;
342             this.getUser(this.requestor.id());
343         }
344     }
345
346     activeDateSelected(dateStr: string) {
347         this.activeDateStr = dateStr;
348     }
349
350     setActiveDate(date: Date) {
351         this.activeDate = date;
352         if (date && date < new Date()) {
353             this.activeDateInvalid = true;
354             this.activeDateAlert.open();
355         } else {
356             this.activeDateInvalid = false;
357         }
358     }
359
360     // Note this is called before this.userBarcode has its latest value.
361     debounceUserBarcodeLookup(barcode: string | ClipboardEvent) {
362         clearTimeout(this.userBarcodeTimeout);
363
364         if (!barcode) {
365             this.badBarcode = null;
366             return;
367         }
368
369         const timeout =
370             (barcode && (barcode as ClipboardEvent).target) ? 0 : 500;
371
372         this.userBarcodeTimeout =
373             setTimeout(() => this.userBarcodeChanged(), timeout);
374     }
375
376     userBarcodeChanged() {
377         const newBc = this.userBarcode;
378
379         if (!newBc) { this.resetRecipient(); return; }
380
381         // Avoid simultaneous or duplicate lookups
382         if (newBc === this.currentUserBarcode) { return; }
383
384         if (newBc !== this.staffCat.holdForBarcode) {
385             // If an alternate barcode is entered, it takes us out of
386             // place-hold-for-patron-x-from-search mode.
387             this.staffCat.clearHoldPatron();
388         }
389
390         this.getUser();
391     }
392
393     getUser(id?: number): Promise<any> {
394
395         let promise = this.resetForm(true);
396         this.currentUserBarcode = this.userBarcode;
397
398         const flesh = {flesh: 1, flesh_fields: {au: ['settings']}};
399
400         promise = promise.then(_ => {
401             if (id) { return id; }
402             // Find the patron ID from the provided barcode.
403             return this.barcodeSelect.getBarcode('actor', this.userBarcode)
404                 .then(selection => selection ? selection.id : null);
405         });
406
407         promise = promise.then(matchId => {
408             if (matchId) {
409                 return this.patron.getById(matchId, flesh);
410             } else {
411                 return null;
412             }
413         });
414
415         this.badBarcode = null;
416         return promise.then(user => {
417
418             if (!user) {
419                 // IDs are assumed to valid
420                 this.badBarcode = this.userBarcode;
421                 return;
422             }
423
424             this.user = user;
425             this.applyUserSettings();
426             this.multiHoldsActive =
427                 this.canPlaceMultiAt.includes(user.home_ou());
428         });
429     }
430
431     resetRecipient(keepBarcode?: boolean) {
432         this.user = null;
433         this.notifyEmail = true;
434         this.notifyPhone = true;
435         this.notifySms = false;
436         this.phoneValue = '';
437         this.pickupLib = this.requestor.ws_ou();
438         this.currentUserBarcode = null;
439         this.multiHoldCount = 1;
440         this.smsValue = '';
441         this.activeDate = null;
442         this.activeDateStr = null;
443         this.suspend = false;
444         if (this.smsCbox) { this.smsCbox.selectedId = null; }
445
446         // Avoid clearing the barcode in cases where the form is
447         // reset as the result of a barcode change.
448         if (!keepBarcode) { this.userBarcode = null; }
449     }
450
451     resetForm(keepBarcode?: boolean): Promise<any> {
452         this.placeHoldsClicked = false;
453         this.resetRecipient(keepBarcode);
454
455         this.holdContexts = this.holdTargets.map(target => {
456             const ctx = new HoldContext(target);
457             return ctx;
458         });
459
460         // Required after rebuilding the contexts
461         return this.getTargetMeta();
462     }
463
464     applyUserSettings() {
465         if (!this.user) { return; }
466
467         // Start with defaults.
468         this.phoneValue = this.user.day_phone() || this.user.evening_phone();
469
470         // Default to work org if placing holds for staff.
471         // Default to home org if placing holds for patrons unless
472         // settings default or fallback to the workstation.
473         if (this.user.id() !== this.requestor.id()) {
474             if (!this.puLibWsFallback && !this.puLibWsDefault) {
475                 // This value may be superseded below by user settings.
476                 this.pickupLib = this.user.home_ou();
477             }
478         }
479
480         if (!this.user.settings()) { return; }
481
482         this.user.settings().forEach(setting => {
483             const name = setting.name();
484             let value = setting.value();
485
486             if (value === '' || value === null) { return; }
487
488             // When fleshing 'settings' on the actor.usr object,
489             // we're grabbing the raw JSON values.
490             value = JSON.parse(value);
491
492             switch (name) {
493                 case 'opac.hold_notify':
494                     this.notifyPhone = Boolean(value.match(/phone/));
495                     this.notifyEmail = Boolean(value.match(/email/));
496                     this.notifySms = Boolean(value.match(/sms/));
497                     break;
498
499                 case 'opac.default_pickup_location':
500                     if (!this.puLibWsDefault && value) {
501                         this.pickupLib = Number(value);
502                     }
503                     break;
504
505                 case 'opac.default_phone':
506                     this.phoneValue = value;
507                     break;
508
509                 case 'opac.default_sms_carrier':
510                     setTimeout(() => {
511                         // timeout creates an extra window where the cbox
512                         // can be rendered in cases where the hold receipient
513                         // is known at page load time.  This out of an
514                         // abundance of caution.
515                         if (this.smsCbox) {
516                             this.smsCbox.selectedId = Number(value);
517                         }
518                     });
519                     break;
520
521                 case 'opac.default_sms_notify':
522                     this.smsValue = value;
523                     break;
524             }
525         });
526
527         if (!this.user.email()) {
528             this.notifyEmail = false;
529         }
530
531         if (!this.phoneValue) {
532             this.notifyPhone = false;
533         }
534     }
535
536     readyToPlaceHolds(): boolean {
537         if (!this.user || this.placeHoldsClicked || this.activeDateInvalid) {
538             return false;
539         }
540         if (this.notifySms) {
541             if (!this.smsValue.length || !this.smsCbox?.selectedId) {
542                 return false;
543             }
544         }
545         return true;
546     }
547
548     // Attempt hold placement on all targets
549     placeHolds(idx?: number, override?: boolean) {
550         if (!idx) {
551             idx = 0;
552             if (this.multiHoldCount > 1 && !override) {
553                 this.addMultHoldContexts();
554             }
555         }
556
557         if (!this.holdContexts[idx]) {
558             return this.afterPlaceHolds(idx > 0);
559         }
560
561         this.placeHoldsClicked = true;
562
563         const ctx = this.holdContexts[idx];
564         this.placeOneHold(ctx, override).then(() =>
565             this.placeHolds(idx + 1, override)
566         );
567     }
568
569     afterPlaceHolds(somePlaced: boolean) {
570         this.placeHoldsClicked = false;
571
572         if (!somePlaced) { return; }
573
574         // At least one hold attempted.  Confirm all succeeded
575         // before resetting the recipient info in the form.
576         let reset = true;
577         this.holdContexts.forEach(ctx => {
578             if (!ctx.success) { reset = false; }
579         });
580
581         if (reset) { this.resetRecipient(); }
582     }
583
584     // When placing holds on multiple copies per target, add a hold
585     // context for each instance of the request.
586     addMultHoldContexts() {
587         const newContexts = [];
588
589         this.holdContexts.forEach(ctx => {
590             for (let idx = 2; idx <= this.multiHoldCount; idx++) {
591                 const newCtx = ctx.clone(ctx.holdTarget);
592                 newContexts.push(newCtx);
593             }
594         });
595
596         // Group the contexts by hold target
597         this.holdContexts = this.holdContexts.concat(newContexts)
598             .sort((h1, h2) =>
599                 h1.holdTarget === h2.holdTarget ? 0 :
600                     h1.holdTarget < h2.holdTarget ? -1 : 1
601             );
602     }
603
604     placeOneHold(ctx: HoldContext, override?: boolean): Promise<any> {
605
606         if (override && !this.canOverride(ctx)) {
607             return Promise.resolve();
608         }
609
610         ctx.processing = true;
611         const selectedFormats = this.mrSelectorsToFilters(ctx);
612
613         let hType = this.holdType;
614         let hTarget = ctx.holdTarget;
615
616         if (ctx.holdMeta.parts && !ctx.holdMeta.part) {
617             ctx.holdMeta.part = (ctx.holdMeta.part_required ? ctx.holdMeta.parts[0] : null);
618         }
619
620         if (hType === 'T' && ctx.holdMeta.part) {
621             // A Title hold morphs into a Part hold at hold placement time
622             // if a part is selected.  This can happen on a per-hold basis
623             // when placing T-level holds.
624             hType = 'P';
625             hTarget = ctx.holdMeta.part.id();
626         }
627
628         console.debug(`Placing ${hType}-type hold on ${hTarget}`);
629
630         return this.holds.placeHold({
631             holdTarget: hTarget,
632             holdType: hType,
633             recipient: this.user.id(),
634             requestor: this.requestor.id(),
635             pickupLib: this.pickupLib,
636             override: override,
637             notifyEmail: this.notifyEmail, // bool
638             notifyPhone: this.notifyPhone ? this.phoneValue : null,
639             notifySms: this.notifySms ? this.smsValue : null,
640             smsCarrier: this.smsCbox ? this.smsCbox.selectedId : null,
641             thawDate: this.suspend ? this.activeDateStr : null,
642             frozen: this.suspend,
643             holdableFormats: selectedFormats
644
645         }).toPromise().then(
646             request => {
647                 ctx.lastRequest = request;
648                 ctx.processing = false;
649
650                 if (request.result.success) {
651                     ctx.success = true;
652
653                     this.worklog.record({
654                         action: 'requested_hold',
655                         hold_id: request.result.holdId,
656                         patron_id: this.user.id(),
657                         user: this.user.family_name()
658                     });
659
660                 } else {
661                     console.debug('hold failed with: ', request);
662
663                     // If this request failed and was not already an override,
664                     // see of this user has permission to override.
665                     if (!request.override && request.result.evt) {
666
667                         const txtcode = request.result.evt.textcode;
668                         const perm = txtcode + '.override';
669
670                         return this.perm.hasWorkPermHere(perm).then(
671                             permResult => ctx.canOverride = permResult[perm]);
672                     }
673                 }
674             },
675             error => {
676                 ctx.processing = false;
677                 console.error(error);
678             }
679         );
680     }
681
682     override(ctx: HoldContext) {
683         this.placeOneHold(ctx, true).then(() => {
684             this.afterPlaceHolds(ctx.success);
685         });
686     }
687
688     canOverride(ctx: HoldContext): boolean {
689         return ctx.lastRequest &&
690                 !ctx.lastRequest.result.success && ctx.canOverride;
691     }
692
693     showOverrideAll(): boolean {
694         return this.holdContexts.filter(ctx =>
695             this.canOverride(ctx)
696         ).length > 1;
697     }
698
699     overrideAll(): void {
700         this.placeHolds(0, true);
701     }
702
703     iconFormatLabel(code: string): string {
704         return this.cat.iconFormatLabel(code);
705     }
706
707     // TODO: for now, only show meta filters for meta holds.
708     // Add an "advanced holds" option to display these for T hold.
709     hasMetaFilters(ctx: HoldContext): boolean {
710         return (
711             this.holdType === 'M' && // TODO
712             ctx.holdMeta.metarecord_filters && (
713                 ctx.holdMeta.metarecord_filters.langs.length > 1 ||
714                 ctx.holdMeta.metarecord_filters.formats.length > 1
715             )
716         );
717     }
718
719     searchPatrons() {
720         this.patronSearch.open({size: 'xl'}).toPromise().then(
721             patrons => {
722                 if (!patrons || patrons.length === 0) { return; }
723                 const user = patrons[0];
724                 this.userBarcode = user.card().barcode();
725                 this.userBarcodeChanged();
726             }
727         );
728     }
729
730     isItemHold(): boolean {
731         return this.holdType === 'C'
732             || this.holdType === 'R'
733             || this.holdType === 'F';
734     }
735
736     setPart(ctx: HoldContext, $event) {
737         const partId = $event.target.value;
738         if (partId) {
739             ctx.holdMeta.part =
740                 ctx.holdMeta.parts.filter(p => +p.id() === +partId)[0];
741         } else {
742             ctx.holdMeta.part = null;
743         }
744     }
745
746     hasNoHistory(): boolean {
747         return history.length === 0;
748     }
749
750     goBack() {
751         history.back();
752     }
753 }
754
755