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';
27 holdMeta: HoldRequestTarget;
29 lastRequest: HoldRequest;
30 canOverride?: boolean;
35 constructor(target: number) {
36 this.holdTarget = target;
37 this.processing = false;
38 this.selectedFormats = {
39 // code => selected-boolean
45 clone(target: number): HoldContext {
46 const ctx = new HoldContext(target);
47 ctx.holdMeta = this.holdMeta;
53 templateUrl: 'hold.component.html'
55 export class HoldComponent implements OnInit {
58 holdTargets: number[];
70 activeDateStr: string;
71 activeDateYmd: string;
73 activeDateInvalid = false;
75 holdContexts: HoldContext[];
76 recordSummaries: BibRecordSummary[];
78 currentUserBarcode: string;
79 smsCarriers: ComboboxEntry[];
80 userBarcodeTimeout: number;
86 // True if mult-copy holds are active for the current receipient.
87 multiHoldsActive = false;
89 canPlaceMultiAt: number[] = [];
91 placeHoldsClicked: boolean;
92 badBarcode: string = null;
94 puLibWsFallback = false;
95 puLibWsDefault = false;
97 // Orgs which are not valid pickup locations
98 disableOrgs: number[] = [];
100 @ViewChild('patronSearch', {static: false})
101 patronSearch: PatronSearchDialogComponent;
103 @ViewChild('smsCbox', {static: false}) smsCbox: ComboboxComponent;
104 @ViewChild('barcodeSelect') private barcodeSelect: BarcodeSelectComponent;
106 @ViewChild('activeDateAlert') private activeDateAlert: AlertDialogComponent;
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
125 this.holdContexts = [];
126 this.smsCarriers = [];
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'));
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';
142 if (this.staffCat.holdForBarcode) {
143 this.holdFor = 'patron';
144 this.userBarcode = this.staffCat.holdForBarcode;
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());
157 this.org.list().forEach(org => {
158 if (org.ou_type().can_have_vols() === 'f') {
159 this.disableOrgs.push(org.id());
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));
172 if (!Array.isArray(this.holdTargets)) {
173 this.holdTargets = [this.holdTargets];
176 this.holdTargets = this.holdTargets.map(t => Number(t));
178 this.requestor = this.auth.user();
179 this.pickupLib = this.auth.user().ws_ou();
183 this.getRequestorSetsAndPerms()
186 // Load receipient data if we have any.
187 if (this.staffCat.holdForBarcode) {
188 this.holdFor = 'patron';
189 this.userBarcode = this.staffCat.holdForBarcode;
192 if (this.holdFor === 'staff' || this.userBarcode) {
193 this.holdForChanged();
198 const node = document.getElementById('patron-barcode');
199 if (node) { node.focus(); }
203 getRequestorSetsAndPerms(): Promise<any> {
205 return this.org.settings(
206 ['sms.enable', 'circ.holds.max_duplicate_holds'])
210 this.smsEnabled = sets['sms.enable'];
212 const max = Number(sets['circ.holds.max_duplicate_holds']);
213 if (Number(max) > 0) { this.maxMultiHolds = Number(max); }
215 if (this.smsEnabled) {
217 return this.patron.getSmsCarriers().then(carriers => {
218 carriers.forEach(carrier => {
219 this.smsCarriers.push({
221 label: carrier.name()
229 if (this.maxMultiHolds) {
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']);
240 holdCountRange(): number[] {
241 return [...Array(this.maxMultiHolds).keys()].map(n => n + 1);
244 // Load the bib, call number, copy, etc. data associated with each target.
245 getTargetMeta(): Promise<any> {
247 return new Promise(resolve => {
248 this.holds.getHoldTargetMeta(this.holdType, this.holdTargets, this.auth.user().ws_ou())
251 this.holdContexts.filter(ctx => ctx.holdTarget === meta.target)
254 this.mrFiltersToSelectors(ctx);
263 // By default, all metarecord filters options are enabled.
264 mrFiltersToSelectors(ctx: HoldContext) {
265 if (this.holdType !== 'M') { return; }
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);
273 if (meta.metarecord_filters.langs) {
274 meta.metarecord_filters.langs.forEach(
275 ccvm => ctx.selectedFormats.langs[ccvm.code()] = true);
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} {
287 const meta = ctx.holdMeta;
288 const slf = ctx.selectedFormats;
289 const result: any = {};
291 const formats = Object.keys(slf.formats)
292 .filter(code => Boolean(slf.formats[code])); // user-selected
294 const langs = Object.keys(slf.langs)
295 .filter(code => Boolean(slf.langs[code])); // user-selected
297 const compiled: any = {};
299 if (formats.length > 0) {
301 formats.forEach(code => {
302 const ccvm = meta.metarecord_filters.formats.filter(
303 format => format.code() === code)[0];
311 if (langs.length > 0) {
313 langs.forEach(code => {
314 const ccvm = meta.metarecord_filters.langs.filter(
315 format => format.code() === code)[0];
323 if (Object.keys(compiled).length > 0) {
325 res[ctx.holdTarget] = JSON.stringify(compiled);
335 if (this.holdFor === 'patron') {
336 if (this.userBarcode) {
337 this.userBarcodeChanged();
340 this.userBarcode = null;
341 this.currentUserBarcode = null;
342 this.getUser(this.requestor.id());
346 activeDateSelected(dateStr: string) {
347 this.activeDateStr = dateStr;
350 setActiveDate(date: Date) {
351 this.activeDate = date;
352 if (date && date < new Date()) {
353 this.activeDateInvalid = true;
354 this.activeDateAlert.open();
356 this.activeDateInvalid = false;
360 // Note this is called before this.userBarcode has its latest value.
361 debounceUserBarcodeLookup(barcode: string | ClipboardEvent) {
362 clearTimeout(this.userBarcodeTimeout);
365 this.badBarcode = null;
370 (barcode && (barcode as ClipboardEvent).target) ? 0 : 500;
372 this.userBarcodeTimeout =
373 setTimeout(() => this.userBarcodeChanged(), timeout);
376 userBarcodeChanged() {
377 const newBc = this.userBarcode;
379 if (!newBc) { this.resetRecipient(); return; }
381 // Avoid simultaneous or duplicate lookups
382 if (newBc === this.currentUserBarcode) { return; }
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();
393 getUser(id?: number): Promise<any> {
395 let promise = this.resetForm(true);
396 this.currentUserBarcode = this.userBarcode;
398 const flesh = {flesh: 1, flesh_fields: {au: ['settings']}};
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);
407 promise = promise.then(matchId => {
409 return this.patron.getById(matchId, flesh);
415 this.badBarcode = null;
416 return promise.then(user => {
419 // IDs are assumed to valid
420 this.badBarcode = this.userBarcode;
425 this.applyUserSettings();
426 this.multiHoldsActive =
427 this.canPlaceMultiAt.includes(user.home_ou());
431 resetRecipient(keepBarcode?: boolean) {
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;
441 this.activeDate = null;
442 this.activeDateStr = null;
443 this.suspend = false;
444 if (this.smsCbox) { this.smsCbox.selectedId = null; }
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; }
451 resetForm(keepBarcode?: boolean): Promise<any> {
452 this.placeHoldsClicked = false;
453 this.resetRecipient(keepBarcode);
455 this.holdContexts = this.holdTargets.map(target => {
456 const ctx = new HoldContext(target);
460 // Required after rebuilding the contexts
461 return this.getTargetMeta();
464 applyUserSettings() {
465 if (!this.user) { return; }
467 // Start with defaults.
468 this.phoneValue = this.user.day_phone() || this.user.evening_phone();
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();
480 if (!this.user.settings()) { return; }
482 this.user.settings().forEach(setting => {
483 const name = setting.name();
484 let value = setting.value();
486 if (value === '' || value === null) { return; }
488 // When fleshing 'settings' on the actor.usr object,
489 // we're grabbing the raw JSON values.
490 value = JSON.parse(value);
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/));
499 case 'opac.default_pickup_location':
500 if (!this.puLibWsDefault && value) {
501 this.pickupLib = Number(value);
505 case 'opac.default_phone':
506 this.phoneValue = value;
509 case 'opac.default_sms_carrier':
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.
516 this.smsCbox.selectedId = Number(value);
521 case 'opac.default_sms_notify':
522 this.smsValue = value;
527 if (!this.user.email()) {
528 this.notifyEmail = false;
531 if (!this.phoneValue) {
532 this.notifyPhone = false;
536 readyToPlaceHolds(): boolean {
537 if (!this.user || this.placeHoldsClicked || this.activeDateInvalid) {
540 if (this.notifySms) {
541 if (!this.smsValue.length || !this.smsCbox?.selectedId) {
548 // Attempt hold placement on all targets
549 placeHolds(idx?: number, override?: boolean) {
552 if (this.multiHoldCount > 1 && !override) {
553 this.addMultHoldContexts();
557 if (!this.holdContexts[idx]) {
558 return this.afterPlaceHolds(idx > 0);
561 this.placeHoldsClicked = true;
563 const ctx = this.holdContexts[idx];
564 this.placeOneHold(ctx, override).then(() =>
565 this.placeHolds(idx + 1, override)
569 afterPlaceHolds(somePlaced: boolean) {
570 this.placeHoldsClicked = false;
572 if (!somePlaced) { return; }
574 // At least one hold attempted. Confirm all succeeded
575 // before resetting the recipient info in the form.
577 this.holdContexts.forEach(ctx => {
578 if (!ctx.success) { reset = false; }
581 if (reset) { this.resetRecipient(); }
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 = [];
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);
596 // Group the contexts by hold target
597 this.holdContexts = this.holdContexts.concat(newContexts)
599 h1.holdTarget === h2.holdTarget ? 0 :
600 h1.holdTarget < h2.holdTarget ? -1 : 1
604 placeOneHold(ctx: HoldContext, override?: boolean): Promise<any> {
606 if (override && !this.canOverride(ctx)) {
607 return Promise.resolve();
610 ctx.processing = true;
611 const selectedFormats = this.mrSelectorsToFilters(ctx);
613 let hType = this.holdType;
614 let hTarget = ctx.holdTarget;
616 if (ctx.holdMeta.parts && !ctx.holdMeta.part) {
617 ctx.holdMeta.part = (ctx.holdMeta.part_required ? ctx.holdMeta.parts[0] : null);
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.
625 hTarget = ctx.holdMeta.part.id();
628 console.debug(`Placing ${hType}-type hold on ${hTarget}`);
630 return this.holds.placeHold({
633 recipient: this.user.id(),
634 requestor: this.requestor.id(),
635 pickupLib: this.pickupLib,
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
647 ctx.lastRequest = request;
648 ctx.processing = false;
650 if (request.result.success) {
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()
661 console.debug('hold failed with: ', request);
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) {
667 const txtcode = request.result.evt.textcode;
668 const perm = txtcode + '.override';
670 return this.perm.hasWorkPermHere(perm).then(
671 permResult => ctx.canOverride = permResult[perm]);
676 ctx.processing = false;
677 console.error(error);
682 override(ctx: HoldContext) {
683 this.placeOneHold(ctx, true).then(() => {
684 this.afterPlaceHolds(ctx.success);
688 canOverride(ctx: HoldContext): boolean {
689 return ctx.lastRequest &&
690 !ctx.lastRequest.result.success && ctx.canOverride;
693 showOverrideAll(): boolean {
694 return this.holdContexts.filter(ctx =>
695 this.canOverride(ctx)
699 overrideAll(): void {
700 this.placeHolds(0, true);
703 iconFormatLabel(code: string): string {
704 return this.cat.iconFormatLabel(code);
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 {
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
720 this.patronSearch.open({size: 'xl'}).toPromise().then(
722 if (!patrons || patrons.length === 0) { return; }
723 const user = patrons[0];
724 this.userBarcode = user.card().barcode();
725 this.userBarcodeChanged();
730 isItemHold(): boolean {
731 return this.holdType === 'C'
732 || this.holdType === 'R'
733 || this.holdType === 'F';
736 setPart(ctx: HoldContext, $event) {
737 const partId = $event.target.value;
740 ctx.holdMeta.parts.filter(p => +p.id() === +partId)[0];
742 ctx.holdMeta.part = null;
746 hasNoHistory(): boolean {
747 return history.length === 0;