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';
24 holdMeta: HoldRequestTarget;
26 lastRequest: HoldRequest;
27 canOverride?: boolean;
32 constructor(target: number) {
33 this.holdTarget = target;
34 this.processing = false;
35 this.selectedFormats = {
36 // code => selected-boolean
42 clone(target: number): HoldContext {
43 const ctx = new HoldContext(target);
44 ctx.holdMeta = this.holdMeta;
50 templateUrl: 'hold.component.html'
52 export class HoldComponent implements OnInit {
55 holdTargets: number[];
67 activeDateStr: string;
68 activeDateYmd: string;
70 activeDateInvalid = false;
72 holdContexts: HoldContext[];
73 recordSummaries: BibRecordSummary[];
75 currentUserBarcode: string;
76 smsCarriers: ComboboxEntry[];
82 // True if mult-copy holds are active for the current receipient.
83 multiHoldsActive = false;
85 canPlaceMultiAt: number[] = [];
87 placeHoldsClicked: boolean;
88 badBarcode: string = null;
90 puLibWsFallback = false;
91 puLibWsDefault = false;
93 // Orgs which are not valid pickup locations
94 disableOrgs: number[] = [];
96 @ViewChild('patronSearch', {static: false})
97 patronSearch: PatronSearchDialogComponent;
99 @ViewChild('smsCbox', {static: false}) smsCbox: ComboboxComponent;
101 @ViewChild('activeDateAlert') private activeDateAlert: AlertDialogComponent;
104 private router: Router,
105 private route: ActivatedRoute,
106 private evt: EventService,
107 private net: NetService,
108 private org: OrgService,
109 private store: ServerStoreService,
110 private auth: AuthService,
111 private pcrud: PcrudService,
112 private bib: BibRecordService,
113 private cat: CatalogService,
114 private staffCat: StaffCatalogService,
115 private holds: HoldsService,
116 private patron: PatronService,
117 private perm: PermService
119 this.holdContexts = [];
120 this.smsCarriers = [];
125 // Respond to changes in hold type. This currently assumes hold
126 // types only toggle post-init between copy-level types (C,R,F)
127 // and no other params (e.g. target) change with it. If other
128 // types require tracking, additional data collection may be needed.
129 this.route.paramMap.subscribe(
130 (params: ParamMap) => this.holdType = params.get('type'));
132 this.holdType = this.route.snapshot.params['type'];
133 this.holdTargets = this.route.snapshot.queryParams['target'];
134 this.holdFor = this.route.snapshot.queryParams['holdFor'] || 'patron';
136 if (this.staffCat.holdForBarcode) {
137 this.holdFor = 'patron';
138 this.userBarcode = this.staffCat.holdForBarcode;
141 this.store.getItemBatch([
142 'circ.staff_placed_holds_fallback_to_ws_ou',
143 'circ.staff_placed_holds_default_to_ws_ou'
144 ]).then(settings => {
145 this.puLibWsFallback =
146 settings['circ.staff_placed_holds_fallback_to_ws_ou'] === true;
147 this.puLibWsDefault =
148 settings['circ.staff_placed_holds_default_to_ws_ou'] === true;
151 this.org.list().forEach(org => {
152 if (org.ou_type().can_have_vols() === 'f') {
153 this.disableOrgs.push(org.id());
157 this.net.request('open-ils.actor',
158 'open-ils.actor.settings.value_for_all_orgs',
159 null, 'opac.holds.org_unit_not_pickup_lib'
160 ).subscribe(resp => {
161 if (resp.summary.value) {
162 this.disableOrgs.push(Number(resp.org_unit));
166 if (!Array.isArray(this.holdTargets)) {
167 this.holdTargets = [this.holdTargets];
170 this.holdTargets = this.holdTargets.map(t => Number(t));
172 this.requestor = this.auth.user();
173 this.pickupLib = this.auth.user().ws_ou();
177 this.getRequestorSetsAndPerms()
180 // Load receipient data if we have any.
181 if (this.staffCat.holdForBarcode) {
182 this.holdFor = 'patron';
183 this.userBarcode = this.staffCat.holdForBarcode;
186 if (this.holdFor === 'staff' || this.userBarcode) {
187 this.holdForChanged();
192 const node = document.getElementById('patron-barcode');
193 if (node) { node.focus(); }
197 getRequestorSetsAndPerms(): Promise<any> {
199 return this.org.settings(
200 ['sms.enable', 'circ.holds.max_duplicate_holds'])
204 this.smsEnabled = sets['sms.enable'];
206 const max = Number(sets['circ.holds.max_duplicate_holds']);
207 if (Number(max) > 0) { this.maxMultiHolds = Number(max); }
209 if (this.smsEnabled) {
211 return this.pcrud.search(
212 'csc', {active: 't'}, {order_by: {csc: 'name'}})
213 .pipe(tap(carrier => {
214 this.smsCarriers.push({
216 label: carrier.name()
223 if (this.maxMultiHolds) {
225 // Multi-copy holds are supported. Let's see where this
226 // requestor has permission to take advantage of them.
227 return this.perm.hasWorkPermAt(
228 ['CREATE_DUPLICATE_HOLDS'], true).then(perms =>
229 this.canPlaceMultiAt = perms['CREATE_DUPLICATE_HOLDS']);
234 holdCountRange(): number[] {
235 return [...Array(this.maxMultiHolds).keys()].map(n => n + 1);
238 // Load the bib, call number, copy, etc. data associated with each target.
239 getTargetMeta(): Promise<any> {
241 return new Promise(resolve => {
242 this.holds.getHoldTargetMeta(this.holdType, this.holdTargets)
245 this.holdContexts.filter(ctx => ctx.holdTarget === meta.target)
248 this.mrFiltersToSelectors(ctx);
257 // By default, all metarecord filters options are enabled.
258 mrFiltersToSelectors(ctx: HoldContext) {
259 if (this.holdType !== 'M') { return; }
261 const meta = ctx.holdMeta;
262 if (meta.metarecord_filters) {
263 if (meta.metarecord_filters.formats) {
264 meta.metarecord_filters.formats.forEach(
265 ccvm => ctx.selectedFormats.formats[ccvm.code()] = true);
267 if (meta.metarecord_filters.langs) {
268 meta.metarecord_filters.langs.forEach(
269 ccvm => ctx.selectedFormats.langs[ccvm.code()] = true);
274 // Map the selected metarecord filters optoins to a JSON-encoded
275 // list of attr filters as required by the API.
276 // Compiles a blob of
277 // {target: JSON({"0": [{_attr: ctype, _val: code}, ...], "1": [...]})}
278 // TODO: this should live in the hold service, not in the UI code.
279 mrSelectorsToFilters(ctx: HoldContext): {[target: number]: string} {
281 const meta = ctx.holdMeta;
282 const slf = ctx.selectedFormats;
283 const result: any = {};
285 const formats = Object.keys(slf.formats)
286 .filter(code => Boolean(slf.formats[code])); // user-selected
288 const langs = Object.keys(slf.langs)
289 .filter(code => Boolean(slf.langs[code])); // user-selected
291 const compiled: any = {};
293 if (formats.length > 0) {
295 formats.forEach(code => {
296 const ccvm = meta.metarecord_filters.formats.filter(
297 format => format.code() === code)[0];
305 if (langs.length > 0) {
307 langs.forEach(code => {
308 const ccvm = meta.metarecord_filters.langs.filter(
309 format => format.code() === code)[0];
317 if (Object.keys(compiled).length > 0) {
319 res[ctx.holdTarget] = JSON.stringify(compiled);
329 if (this.holdFor === 'patron') {
330 if (this.userBarcode) {
331 this.userBarcodeChanged();
334 this.userBarcode = null;
335 this.currentUserBarcode = null;
336 this.getUser(this.requestor.id());
340 activeDateSelected(dateStr: string) {
341 this.activeDateStr = dateStr;
344 setActiveDate(date: Date) {
345 this.activeDate = date;
346 if (date && date < new Date()) {
347 this.activeDateInvalid = true;
348 this.activeDateAlert.open();
350 this.activeDateInvalid = false;
354 userBarcodeChanged() {
355 const newBc = this.userBarcode;
357 if (!newBc) { this.resetRecipient(); return; }
359 // Avoid simultaneous or duplicate lookups
360 if (newBc === this.currentUserBarcode) { return; }
362 if (newBc !== this.staffCat.holdForBarcode) {
363 // If an alternate barcode is entered, it takes us out of
364 // place-hold-for-patron-x-from-search mode.
365 this.staffCat.clearHoldPatron();
371 getUser(id?: number): Promise<any> {
373 let promise = this.resetForm(true);
374 this.currentUserBarcode = this.userBarcode;
376 const flesh = {flesh: 1, flesh_fields: {au: ['settings']}};
378 promise = promise.then(_ => {
380 this.patron.getById(id, flesh) :
381 this.patron.getByBarcode(this.userBarcode, flesh);
384 this.badBarcode = null;
385 return promise.then(user => {
388 // IDs are assumed to valid
389 this.badBarcode = this.userBarcode;
394 this.applyUserSettings();
395 this.multiHoldsActive =
396 this.canPlaceMultiAt.includes(user.home_ou());
400 resetRecipient(keepBarcode?: boolean) {
402 this.notifyEmail = true;
403 this.notifyPhone = true;
404 this.notifySms = false;
405 this.phoneValue = '';
406 this.pickupLib = this.requestor.ws_ou();
407 this.currentUserBarcode = null;
408 this.multiHoldCount = 1;
410 this.activeDate = null;
411 this.activeDateStr = null;
412 this.suspend = false;
413 if (this.smsCbox) { this.smsCbox.selectedId = null; }
415 // Avoid clearing the barcode in cases where the form is
416 // reset as the result of a barcode change.
417 if (!keepBarcode) { this.userBarcode = null; }
420 resetForm(keepBarcode?: boolean): Promise<any> {
421 this.placeHoldsClicked = false;
422 this.resetRecipient(keepBarcode);
424 this.holdContexts = this.holdTargets.map(target => {
425 const ctx = new HoldContext(target);
429 // Required after rebuilding the contexts
430 return this.getTargetMeta();
433 applyUserSettings() {
434 if (!this.user) { return; }
436 // Start with defaults.
437 this.phoneValue = this.user.day_phone() || this.user.evening_phone();
439 // Default to work org if placing holds for staff.
440 // Default to home org if placing holds for patrons unless
441 // settings default or fallback to the workstation.
442 if (this.user.id() !== this.requestor.id()) {
443 if (!this.puLibWsFallback && !this.puLibWsDefault) {
444 // This value may be superseded below by user settings.
445 this.pickupLib = this.user.home_ou();
449 if (!this.user.settings()) { return; }
451 this.user.settings().forEach(setting => {
452 const name = setting.name();
453 let value = setting.value();
455 if (value === '' || value === null) { return; }
457 // When fleshing 'settings' on the actor.usr object,
458 // we're grabbing the raw JSON values.
459 value = JSON.parse(value);
462 case 'opac.hold_notify':
463 this.notifyPhone = Boolean(value.match(/phone/));
464 this.notifyEmail = Boolean(value.match(/email/));
465 this.notifySms = Boolean(value.match(/sms/));
468 case 'opac.default_pickup_location':
469 if (!this.puLibWsDefault && value) {
470 this.pickupLib = Number(value);
474 case 'opac.default_phone':
475 this.phoneValue = value;
478 case 'opac.default_sms_carrier':
480 // timeout creates an extra window where the cbox
481 // can be rendered in cases where the hold receipient
482 // is known at page load time. This out of an
483 // abundance of caution.
485 this.smsCbox.selectedId = Number(value);
490 case 'opac.default_sms_notify':
491 this.smsValue = value;
496 if (!this.user.email()) {
497 this.notifyEmail = false;
500 if (!this.phoneValue) {
501 this.notifyPhone = false;
505 readyToPlaceHolds(): boolean {
506 if (!this.user || this.placeHoldsClicked || this.activeDateInvalid) {
509 if (this.notifySms) {
510 if (!this.smsValue.length || !this.smsCbox?.selectedId) {
517 // Attempt hold placement on all targets
518 placeHolds(idx?: number) {
521 if (this.multiHoldCount > 1) {
522 this.addMultHoldContexts();
526 if (!this.holdContexts[idx]) {
527 return this.afterPlaceHolds(idx > 0);
530 this.placeHoldsClicked = true;
532 const ctx = this.holdContexts[idx];
533 this.placeOneHold(ctx).then(() => this.placeHolds(idx + 1));
536 afterPlaceHolds(somePlaced: boolean) {
537 this.placeHoldsClicked = false;
539 if (!somePlaced) { return; }
541 // At least one hold attempted. Confirm all succeeded
542 // before resetting the recipient info in the form.
544 this.holdContexts.forEach(ctx => {
545 if (!ctx.success) { reset = false; }
548 if (reset) { this.resetRecipient(); }
551 // When placing holds on multiple copies per target, add a hold
552 // context for each instance of the request.
553 addMultHoldContexts() {
554 const newContexts = [];
556 this.holdContexts.forEach(ctx => {
557 for (let idx = 2; idx <= this.multiHoldCount; idx++) {
558 const newCtx = ctx.clone(ctx.holdTarget);
559 newContexts.push(newCtx);
563 // Group the contexts by hold target
564 this.holdContexts = this.holdContexts.concat(newContexts)
566 h1.holdTarget === h2.holdTarget ? 0 :
567 h1.holdTarget < h2.holdTarget ? -1 : 1
571 placeOneHold(ctx: HoldContext, override?: boolean): Promise<any> {
573 ctx.processing = true;
574 const selectedFormats = this.mrSelectorsToFilters(ctx);
576 let hType = this.holdType;
577 let hTarget = ctx.holdTarget;
578 if (hType === 'T' && ctx.holdMeta.part) {
579 // A Title hold morphs into a Part hold at hold placement time
580 // if a part is selected. This can happen on a per-hold basis
581 // when placing T-level holds.
583 hTarget = ctx.holdMeta.part.id();
586 console.debug(`Placing ${hType}-type hold on ${hTarget}`);
588 return this.holds.placeHold({
591 recipient: this.user.id(),
592 requestor: this.requestor.id(),
593 pickupLib: this.pickupLib,
595 notifyEmail: this.notifyEmail, // bool
596 notifyPhone: this.notifyPhone ? this.phoneValue : null,
597 notifySms: this.notifySms ? this.smsValue : null,
598 smsCarrier: this.smsCbox ? this.smsCbox.selectedId : null,
599 thawDate: this.suspend ? this.activeDateStr : null,
600 frozen: this.suspend,
601 holdableFormats: selectedFormats
605 ctx.lastRequest = request;
606 ctx.processing = false;
608 if (request.result.success) {
611 // Overrides are processed one hold at a time, so
612 // we have to invoke the post-holds logic here
613 // instead of the batch placeHolds() method. If
614 // there is ever a batch override option, this
615 // logic will have to be adjusted avoid callling
616 // afterPlaceHolds in batch mode.
617 if (override) { this.afterPlaceHolds(true); }
620 console.debug('hold failed with: ', request);
622 // If this request failed and was not already an override,
623 // see of this user has permission to override.
624 if (!request.override && request.result.evt) {
626 const txtcode = request.result.evt.textcode;
627 const perm = txtcode + '.override';
629 return this.perm.hasWorkPermHere(perm).then(
630 permResult => ctx.canOverride = permResult[perm]);
635 ctx.processing = false;
636 console.error(error);
641 override(ctx: HoldContext) {
642 this.placeOneHold(ctx, true);
645 canOverride(ctx: HoldContext): boolean {
646 return ctx.lastRequest &&
647 !ctx.lastRequest.result.success && ctx.canOverride;
650 iconFormatLabel(code: string): string {
651 return this.cat.iconFormatLabel(code);
654 // TODO: for now, only show meta filters for meta holds.
655 // Add an "advanced holds" option to display these for T hold.
656 hasMetaFilters(ctx: HoldContext): boolean {
658 this.holdType === 'M' && // TODO
659 ctx.holdMeta.metarecord_filters && (
660 ctx.holdMeta.metarecord_filters.langs.length > 1 ||
661 ctx.holdMeta.metarecord_filters.formats.length > 1
667 this.patronSearch.open({size: 'xl'}).toPromise().then(
669 if (!patrons || patrons.length === 0) { return; }
670 const user = patrons[0];
671 this.userBarcode = user.card().barcode();
672 this.userBarcodeChanged();
677 isItemHold(): boolean {
678 return this.holdType === 'C'
679 || this.holdType === 'R'
680 || this.holdType === 'F';
683 setPart(ctx: HoldContext, $event) {
684 const partId = $event.target.value;
687 ctx.holdMeta.parts.filter(p => +p.id() === +partId)[0];
689 ctx.holdMeta.part = null;
693 hasNoHistory(): boolean {
694 return history.length === 0;