1 import {Component, OnInit, Input, 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';
23 holdMeta: HoldRequestTarget;
25 lastRequest: HoldRequest;
26 canOverride?: boolean;
31 constructor(target: number) {
32 this.holdTarget = target;
33 this.processing = false;
34 this.selectedFormats = {
35 // code => selected-boolean
41 clone(target: number): HoldContext {
42 const ctx = new HoldContext(target);
43 ctx.holdMeta = this.holdMeta;
49 templateUrl: 'hold.component.html'
51 export class HoldComponent implements OnInit {
54 holdTargets: number[];
66 activeDateStr: string;
69 holdContexts: HoldContext[];
70 recordSummaries: BibRecordSummary[];
72 currentUserBarcode: string;
73 smsCarriers: ComboboxEntry[];
79 // True if mult-copy holds are active for the current receipient.
80 multiHoldsActive = false;
82 canPlaceMultiAt: number[] = [];
84 placeHoldsClicked: boolean;
85 badBarcode: string = null;
87 puLibWsFallback = false;
89 @ViewChild('patronSearch', {static: false})
90 patronSearch: PatronSearchDialogComponent;
92 @ViewChild('smsCbox', {static: false}) smsCbox: ComboboxComponent;
95 private router: Router,
96 private route: ActivatedRoute,
97 private evt: EventService,
98 private net: NetService,
99 private org: OrgService,
100 private store: ServerStoreService,
101 private auth: AuthService,
102 private pcrud: PcrudService,
103 private bib: BibRecordService,
104 private cat: CatalogService,
105 private staffCat: StaffCatalogService,
106 private holds: HoldsService,
107 private patron: PatronService,
108 private perm: PermService
110 this.holdContexts = [];
111 this.smsCarriers = [];
116 // Respond to changes in hold type. This currently assumes hold
117 // types only toggle post-init between copy-level types (C,R,F)
118 // and no other params (e.g. target) change with it. If other
119 // types require tracking, additional data collection may be needed.
120 this.route.paramMap.subscribe(
121 (params: ParamMap) => this.holdType = params.get('type'));
123 this.holdType = this.route.snapshot.params['type'];
124 this.holdTargets = this.route.snapshot.queryParams['target'];
125 this.holdFor = this.route.snapshot.queryParams['holdFor'] || 'patron';
127 if (this.staffCat.holdForBarcode) {
128 this.holdFor = 'patron';
129 this.userBarcode = this.staffCat.holdForBarcode;
132 this.store.getItem('circ.staff_placed_holds_fallback_to_ws_ou')
133 .then(setting => this.puLibWsFallback = setting === true);
135 if (!Array.isArray(this.holdTargets)) {
136 this.holdTargets = [this.holdTargets];
139 this.holdTargets = this.holdTargets.map(t => Number(t));
141 this.requestor = this.auth.user();
142 this.pickupLib = this.auth.user().ws_ou();
146 this.getRequestorSetsAndPerms()
149 // Load receipient data if we have any.
150 if (this.staffCat.holdForBarcode) {
151 this.holdFor = 'patron';
152 this.userBarcode = this.staffCat.holdForBarcode;
155 if (this.holdFor === 'staff' || this.userBarcode) {
156 this.holdForChanged();
161 const node = document.getElementById('patron-barcode');
162 if (node) { node.focus(); }
166 getRequestorSetsAndPerms(): Promise<any> {
168 return this.org.settings(
169 ['sms.enable', 'circ.holds.max_duplicate_holds'])
173 this.smsEnabled = sets['sms.enable'];
175 const max = Number(sets['circ.holds.max_duplicate_holds']);
176 if (Number(max) > 0) { this.maxMultiHolds = Number(max); }
178 if (this.smsEnabled) {
180 return this.pcrud.search(
181 'csc', {active: 't'}, {order_by: {csc: 'name'}})
182 .pipe(tap(carrier => {
183 this.smsCarriers.push({
185 label: carrier.name()
192 if (this.maxMultiHolds) {
194 // Multi-copy holds are supported. Let's see where this
195 // requestor has permission to take advantage of them.
196 return this.perm.hasWorkPermAt(
197 ['CREATE_DUPLICATE_HOLDS'], true).then(perms =>
198 this.canPlaceMultiAt = perms['CREATE_DUPLICATE_HOLDS']);
203 holdCountRange(): number[] {
204 return [...Array(this.maxMultiHolds).keys()].map(n => n + 1);
207 // Load the bib, call number, copy, etc. data associated with each target.
208 getTargetMeta(): Promise<any> {
210 return new Promise(resolve => {
211 this.holds.getHoldTargetMeta(this.holdType, this.holdTargets)
214 this.holdContexts.filter(ctx => ctx.holdTarget === meta.target)
217 this.mrFiltersToSelectors(ctx);
226 // By default, all metarecord filters options are enabled.
227 mrFiltersToSelectors(ctx: HoldContext) {
228 if (this.holdType !== 'M') { return; }
230 const meta = ctx.holdMeta;
231 if (meta.metarecord_filters) {
232 if (meta.metarecord_filters.formats) {
233 meta.metarecord_filters.formats.forEach(
234 ccvm => ctx.selectedFormats.formats[ccvm.code()] = true);
236 if (meta.metarecord_filters.langs) {
237 meta.metarecord_filters.langs.forEach(
238 ccvm => ctx.selectedFormats.langs[ccvm.code()] = true);
243 // Map the selected metarecord filters optoins to a JSON-encoded
244 // list of attr filters as required by the API.
245 // Compiles a blob of
246 // {target: JSON({"0": [{_attr: ctype, _val: code}, ...], "1": [...]})}
247 // TODO: this should live in the hold service, not in the UI code.
248 mrSelectorsToFilters(ctx: HoldContext): {[target: number]: string} {
250 const meta = ctx.holdMeta;
251 const slf = ctx.selectedFormats;
252 const result: any = {};
254 const formats = Object.keys(slf.formats)
255 .filter(code => Boolean(slf.formats[code])); // user-selected
257 const langs = Object.keys(slf.langs)
258 .filter(code => Boolean(slf.langs[code])); // user-selected
260 const compiled: any = {};
262 if (formats.length > 0) {
264 formats.forEach(code => {
265 const ccvm = meta.metarecord_filters.formats.filter(
266 format => format.code() === code)[0];
274 if (langs.length > 0) {
276 langs.forEach(code => {
277 const ccvm = meta.metarecord_filters.langs.filter(
278 format => format.code() === code)[0];
286 if (Object.keys(compiled).length > 0) {
288 res[ctx.holdTarget] = JSON.stringify(compiled);
298 if (this.holdFor === 'patron') {
299 if (this.userBarcode) {
300 this.userBarcodeChanged();
303 this.userBarcode = null;
304 this.currentUserBarcode = null;
305 this.getUser(this.requestor.id());
309 activeDateSelected(dateStr: string) {
310 this.activeDateStr = dateStr;
313 userBarcodeChanged() {
314 const newBc = this.userBarcode;
316 if (!newBc) { this.resetRecipient(); return; }
318 // Avoid simultaneous or duplicate lookups
319 if (newBc === this.currentUserBarcode) { return; }
321 if (newBc !== this.staffCat.holdForBarcode) {
322 // If an alternate barcode is entered, it takes us out of
323 // place-hold-for-patron-x-from-search mode.
324 this.staffCat.clearHoldPatron();
330 getUser(id?: number): Promise<any> {
332 let promise = this.resetForm(true);
333 this.currentUserBarcode = this.userBarcode;
335 const flesh = {flesh: 1, flesh_fields: {au: ['settings']}};
337 promise = promise.then(_ => {
339 this.patron.getById(id, flesh) :
340 this.patron.getByBarcode(this.userBarcode, flesh);
343 this.badBarcode = null;
344 return promise.then(user => {
347 // IDs are assumed to valid
348 this.badBarcode = this.userBarcode;
353 this.applyUserSettings();
354 this.multiHoldsActive =
355 this.canPlaceMultiAt.includes(user.home_ou());
359 resetRecipient(keepBarcode?: boolean) {
361 this.notifyEmail = true;
362 this.notifyPhone = true;
363 this.notifySms = false;
364 this.phoneValue = '';
365 this.pickupLib = this.requestor.ws_ou();
366 this.currentUserBarcode = null;
367 this.multiHoldCount = 1;
369 this.activeDate = null;
370 this.activeDateStr = null;
371 this.suspend = false;
372 if (this.smsCbox) { this.smsCbox.selectedId = null; }
374 // Avoid clearing the barcode in cases where the form is
375 // reset as the result of a barcode change.
376 if (!keepBarcode) { this.userBarcode = null; }
379 resetForm(keepBarcode?: boolean): Promise<any> {
380 this.placeHoldsClicked = false;
381 this.resetRecipient(keepBarcode);
383 this.holdContexts = this.holdTargets.map(target => {
384 const ctx = new HoldContext(target);
388 // Required after rebuilding the contexts
389 return this.getTargetMeta();
392 applyUserSettings() {
393 if (!this.user) { return; }
395 // Start with defaults.
396 this.phoneValue = this.user.day_phone() || this.user.evening_phone();
398 // Default to work org if placing holds for staff.
399 if (this.user.id() !== this.requestor.id() && !this.puLibWsFallback) {
400 // This value may be superseded below by user settings.
401 this.pickupLib = this.user.home_ou();
404 if (!this.user.settings()) { return; }
406 this.user.settings().forEach(setting => {
407 const name = setting.name();
408 let value = setting.value();
410 if (value === '' || value === null) { return; }
412 // When fleshing 'settings' on the actor.usr object,
413 // we're grabbing the raw JSON values.
414 value = JSON.parse(value);
417 case 'opac.hold_notify':
418 this.notifyPhone = Boolean(value.match(/phone/));
419 this.notifyEmail = Boolean(value.match(/email/));
420 this.notifySms = Boolean(value.match(/sms/));
423 case 'opac.default_pickup_location':
424 this.pickupLib = Number(value);
427 case 'opac.default_phone':
428 this.phoneValue = value;
431 case 'opac.default_sms_carrier':
433 // timeout creates an extra window where the cbox
434 // can be rendered in cases where the hold receipient
435 // is known at page load time. This out of an
436 // abundance of caution.
438 this.smsCbox.selectedId = Number(value);
443 case 'opac.default_sms_notify':
444 this.smsValue = value;
449 if (!this.user.email()) {
450 this.notifyEmail = false;
453 if (!this.phoneValue) {
454 this.notifyPhone = false;
458 // Attempt hold placement on all targets
459 placeHolds(idx?: number) {
462 if (this.multiHoldCount > 1) {
463 this.addMultHoldContexts();
467 if (!this.holdContexts[idx]) {
468 return this.afterPlaceHolds(idx > 0);
471 this.placeHoldsClicked = true;
473 const ctx = this.holdContexts[idx];
474 this.placeOneHold(ctx).then(() => this.placeHolds(idx + 1));
477 afterPlaceHolds(somePlaced: boolean) {
478 this.placeHoldsClicked = false;
480 if (!somePlaced) { return; }
482 // At least one hold attempted. Confirm all succeeded
483 // before resetting the recipient info in the form.
485 this.holdContexts.forEach(ctx => {
486 if (!ctx.success) { reset = false; }
489 if (reset) { this.resetRecipient(); }
492 // When placing holds on multiple copies per target, add a hold
493 // context for each instance of the request.
494 addMultHoldContexts() {
495 const newContexts = [];
497 this.holdContexts.forEach(ctx => {
498 for (let idx = 2; idx <= this.multiHoldCount; idx++) {
499 const newCtx = ctx.clone(ctx.holdTarget);
500 newContexts.push(newCtx);
504 // Group the contexts by hold target
505 this.holdContexts = this.holdContexts.concat(newContexts)
507 h1.holdTarget === h2.holdTarget ? 0 :
508 h1.holdTarget < h2.holdTarget ? -1 : 1
512 placeOneHold(ctx: HoldContext, override?: boolean): Promise<any> {
514 ctx.processing = true;
515 const selectedFormats = this.mrSelectorsToFilters(ctx);
517 let hType = this.holdType;
518 let hTarget = ctx.holdTarget;
519 if (hType === 'T' && ctx.holdMeta.part) {
520 // A Title hold morphs into a Part hold at hold placement time
521 // if a part is selected. This can happen on a per-hold basis
522 // when placing T-level holds.
524 hTarget = ctx.holdMeta.part.id();
527 console.debug(`Placing ${hType}-type hold on ${hTarget}`);
529 return this.holds.placeHold({
532 recipient: this.user.id(),
533 requestor: this.requestor.id(),
534 pickupLib: this.pickupLib,
536 notifyEmail: this.notifyEmail, // bool
537 notifyPhone: this.notifyPhone ? this.phoneValue : null,
538 notifySms: this.notifySms ? this.smsValue : null,
539 smsCarrier: this.smsCbox ? this.smsCbox.selectedId : null,
540 thawDate: this.suspend ? this.activeDateStr : null,
541 frozen: this.suspend,
542 holdableFormats: selectedFormats
546 ctx.lastRequest = request;
547 ctx.processing = false;
549 if (request.result.success) {
552 // Overrides are processed one hold at a time, so
553 // we have to invoke the post-holds logic here
554 // instead of the batch placeHolds() method. If
555 // there is ever a batch override option, this
556 // logic will have to be adjusted avoid callling
557 // afterPlaceHolds in batch mode.
558 if (override) { this.afterPlaceHolds(true); }
561 console.debug('hold failed with: ', request);
563 // If this request failed and was not already an override,
564 // see of this user has permission to override.
565 if (!request.override && request.result.evt) {
567 const txtcode = request.result.evt.textcode;
568 const perm = txtcode + '.override';
570 return this.perm.hasWorkPermHere(perm).then(
571 permResult => ctx.canOverride = permResult[perm]);
576 ctx.processing = false;
577 console.error(error);
582 override(ctx: HoldContext) {
583 this.placeOneHold(ctx, true);
586 canOverride(ctx: HoldContext): boolean {
587 return ctx.lastRequest &&
588 !ctx.lastRequest.result.success && ctx.canOverride;
591 iconFormatLabel(code: string): string {
592 return this.cat.iconFormatLabel(code);
595 // TODO: for now, only show meta filters for meta holds.
596 // Add an "advanced holds" option to display these for T hold.
597 hasMetaFilters(ctx: HoldContext): boolean {
599 this.holdType === 'M' && // TODO
600 ctx.holdMeta.metarecord_filters && (
601 ctx.holdMeta.metarecord_filters.langs.length > 1 ||
602 ctx.holdMeta.metarecord_filters.formats.length > 1
608 this.patronSearch.open({size: 'xl'}).toPromise().then(
610 if (!patrons || patrons.length === 0) { return; }
611 const user = patrons[0];
612 this.userBarcode = user.card().barcode();
613 this.userBarcodeChanged();
618 isItemHold(): boolean {
619 return this.holdType === 'C'
620 || this.holdType === 'R'
621 || this.holdType === 'F';
624 setPart(ctx: HoldContext, $event) {
625 const partId = $event.target.value;
628 ctx.holdMeta.parts.filter(p => +p.id() === +partId)[0];
630 ctx.holdMeta.part = null;
634 hasNoHistory(): boolean {
635 return history.length === 0;