1 import {Injectable} from '@angular/core';
2 import {Observable, empty, from} from 'rxjs';
3 import {map, concatMap, mergeMap} from 'rxjs/operators';
4 import {IdlObject} from '@eg/core/idl.service';
5 import {NetService} from '@eg/core/net.service';
6 import {OrgService} from '@eg/core/org.service';
7 import {PcrudService} from '@eg/core/pcrud.service';
8 import {EventService, EgEvent} from '@eg/core/event.service';
9 import {AuthService} from '@eg/core/auth.service';
10 import {BibRecordService, BibRecordSummary} from '@eg/share/catalog/bib-record.service';
11 import {AudioService} from '@eg/share/util/audio.service';
12 import {CircEventsComponent} from './events-dialog.component';
13 import {CircComponentsComponent} from './components.component';
14 import {StringService} from '@eg/share/string/string.service';
15 import {ServerStoreService} from '@eg/core/server-store.service';
16 import {HoldingsService} from '@eg/staff/share/holdings/holdings.service';
17 import {WorkLogService, WorkLogEntry} from '@eg/staff/share/worklog/worklog.service';
19 export interface CircDisplayInfo {
23 copy?: IdlObject; // acp
24 volume?: IdlObject; // acn
25 record?: IdlObject; // bre
26 display?: IdlObject; // mwde
29 const CAN_OVERRIDE_CHECKOUT_EVENTS = [
30 'PATRON_EXCEEDS_OVERDUE_COUNT',
31 'PATRON_EXCEEDS_CHECKOUT_COUNT',
32 'PATRON_EXCEEDS_FINES',
33 'PATRON_EXCEEDS_LONGOVERDUE_COUNT',
35 'CIRC_EXCEEDS_COPY_RANGE',
36 'ITEM_DEPOSIT_REQUIRED',
37 'ITEM_RENTAL_FEE_REQUIRED',
38 'PATRON_EXCEEDS_LOST_COUNT',
39 'COPY_CIRC_NOT_ALLOWED',
43 'ITEM_ON_HOLDS_SHELF',
53 const CHECKOUT_OVERRIDE_AFTER_FIRST = [
54 'PATRON_EXCEEDS_OVERDUE_COUNT',
56 'PATRON_EXCEEDS_LOST_COUNT',
57 'PATRON_EXCEEDS_CHECKOUT_COUNT',
58 'PATRON_EXCEEDS_FINES',
59 'PATRON_EXCEEDS_LONGOVERDUE_COUNT'
62 const CAN_OVERRIDE_RENEW_EVENTS = [
63 'PATRON_EXCEEDS_OVERDUE_COUNT',
64 'PATRON_EXCEEDS_LOST_COUNT',
65 'PATRON_EXCEEDS_CHECKOUT_COUNT',
66 'PATRON_EXCEEDS_FINES',
67 'PATRON_EXCEEDS_LONGOVERDUE_COUNT',
68 'CIRC_EXCEEDS_COPY_RANGE',
69 'ITEM_DEPOSIT_REQUIRED',
70 'ITEM_RENTAL_FEE_REQUIRED',
72 'COPY_CIRC_NOT_ALLOWED',
76 'COPY_NEEDED_FOR_HOLD',
77 'MAX_RENEWALS_REACHED',
78 'CIRC_CLAIMS_RETURNED',
88 // These checkin events do not produce alerts when
89 // options.suppress_alerts is in effect.
90 const CAN_SUPPRESS_CHECKIN_ALERTS = [
94 'PATRON_ACCOUNT_EXPIRED',
96 'CIRC_CLAIMS_RETURNED',
99 'COPY_STATUS_LOST_AND_PAID',
100 'COPY_STATUS_LONG_OVERDUE',
101 'COPY_STATUS_MISSING',
102 'PATRON_EXCEEDS_FINES'
105 const CAN_OVERRIDE_CHECKIN_ALERTS = [
106 // not technically overridable, but special prompt and param
107 'HOLD_CAPTURE_DELAYED',
108 'TRANSIT_CHECKIN_INTERVAL_BLOCK'
109 ].concat(CAN_SUPPRESS_CHECKIN_ALERTS);
112 // API parameter options
113 export interface CheckoutParams {
117 copy_barcode?: string;
119 noncat_type?: number;
120 noncat_count?: number;
123 dummy_title?: string;
124 dummy_author?: string;
126 circ_modifier?: string;
127 void_overdues?: boolean;
128 new_copy_alerts?: boolean;
133 _checkbarcode?: boolean;
134 _worklog?: WorkLogEntry;
137 export interface CircResultCommon {
139 params: CheckinParams | CheckoutParams;
141 allEvents: EgEvent[];
147 parent_circ?: IdlObject;
151 copyAlerts?: IdlObject[];
161 export interface CheckoutResult extends CircResultCommon {
162 params: CheckoutParams;
164 nonCatCirc?: IdlObject;
167 export interface CheckinParams {
170 copy_barcode?: string;
171 claims_never_checked_out?: boolean;
172 void_overdues?: boolean;
173 auto_print_holds_transits?: boolean;
176 next_copy_status?: number[];
177 new_copy_alerts?: boolean;
178 clear_expired?: boolean;
179 hold_as_transit?: boolean;
180 manual_float?: boolean;
181 do_inventory_update?: boolean;
182 no_precat_alert?: boolean;
183 retarget_mode?: string;
185 // internal / local values that are moved from the API request.
187 _worklog?: WorkLogEntry;
188 _checkbarcode?: boolean;
191 export interface CheckinResult extends CircResultCommon {
192 params: CheckinParams;
193 routeTo?: string; // org name or in-branch destination
195 destAddress?: IdlObject;
196 destCourierCode?: string;
200 export class CircService {
201 static resultIndex = 0;
203 components: CircComponentsComponent;
204 nonCatTypes: IdlObject[] = null;
205 autoOverrideCheckoutEvents: {[textcode: string]: boolean} = {};
206 suppressCheckinPopups = false;
207 ignoreCheckinPrecats = false;
208 copyLocationCache: {[id: number]: IdlObject} = {};
209 clearHoldsOnCheckout = false;
210 orgAddrCache: {[addrId: number]: IdlObject} = {};
213 private audio: AudioService,
214 private evt: EventService,
215 private org: OrgService,
216 private net: NetService,
217 private pcrud: PcrudService,
218 private serverStore: ServerStoreService,
219 private strings: StringService,
220 private auth: AuthService,
221 private holdings: HoldingsService,
222 private worklog: WorkLogService,
223 private bib: BibRecordService
226 applySettings(): Promise<any> {
227 return this.serverStore.getItemBatch([
228 'circ.clear_hold_on_checkout',
230 this.clearHoldsOnCheckout = sets['circ.clear_hold_on_checkout'];
231 return this.worklog.loadSettings();
235 // 'circ' is fleshed with copy, vol, bib, wide_display_entry
236 // Extracts some display info from a fleshed circ.
237 getDisplayInfo(circ: IdlObject): CircDisplayInfo {
238 return this.getCopyDisplayInfo(circ.target_copy());
241 getCopyDisplayInfo(copy: IdlObject): CircDisplayInfo {
243 if (copy.call_number() === -1 || copy.call_number().id() === -1) {
246 title: copy.dummy_title(),
247 author: copy.dummy_author(),
248 isbn: copy.dummy_isbn(),
253 const volume = copy.call_number();
254 const record = volume.record();
255 const display = record.wide_display_entry();
257 let isbn = JSON.parse(display.isbn());
258 if (Array.isArray(isbn)) { isbn = isbn.join(','); }
261 title: JSON.parse(display.title()),
262 author: JSON.parse(display.author()),
271 getOrgAddr(orgId: number, addrType): Promise<IdlObject> {
272 const org = this.org.get(orgId);
273 const addrId = this.org[addrType];
275 if (!addrId) { return Promise.resolve(null); }
277 if (this.orgAddrCache[addrId]) {
278 return Promise.resolve(this.orgAddrCache[addrId]);
281 return this.pcrud.retrieve('aoa', addrId).toPromise()
283 this.orgAddrCache[addrId] = addr;
288 // find the open transit for the given copy barcode; flesh the org
290 // Sets result.transit
291 findCopyTransit(result: CircResultCommon): Promise<IdlObject> {
292 // NOTE: result.transit may exist, but it's not necessarily
293 // the transit we want, since a transit close + open in the API
294 // returns the closed transit.
295 return this.findCopyTransitById(result.copy.id())
297 result.transit = transit;
302 findCopyTransitById(copyId: number): Promise<IdlObject> {
303 return this.pcrud.search('atc', {
304 dest_recv_time : null,
309 order_by : {atc : 'source_send_time desc'},
310 }, {authoritative : true}
311 ).toPromise().then(transit => {
313 transit.source(this.org.get(transit.source()));
314 transit.dest(this.org.get(transit.dest()));
318 return Promise.reject('No transit found');
322 // Sets result.transit and result.copy
323 findCopyTransitByBarcode(result: CircResultCommon): Promise<IdlObject> {
324 // NOTE: result.transit may exist, but it's not necessarily
325 // the transit we want, since a transit close + open in the API
326 // returns the closed transit.
328 const barcode = result.params.copy_barcode;
330 return this.pcrud.search('atc', {
331 dest_recv_time : null,
335 flesh_fields : {atc : ['target_copy']},
345 order_by : {atc : 'source_send_time desc'}
346 }, {authoritative : true}
348 ).toPromise().then(transit => {
350 transit.source(this.org.get(transit.source()));
351 transit.dest(this.org.get(transit.dest()));
352 result.transit = transit;
353 result.copy = transit.target_copy();
356 return Promise.reject('No transit found');
360 getNonCatTypes(): Promise<IdlObject[]> {
362 if (this.nonCatTypes) {
363 return Promise.resolve(this.nonCatTypes);
366 return this.pcrud.search('cnct',
367 {owning_lib: this.org.fullPath(this.auth.user().ws_ou(), true)},
368 {order_by: {cnct: 'name'}},
370 ).toPromise().then(types => this.nonCatTypes = types);
373 // Remove internal tracking variables on Param objects so they are
374 // not sent to the server, which can result in autoload errors.
376 params: CheckoutParams | CheckinParams): CheckoutParams | CheckinParams {
378 const apiParams = Object.assign({}, params); // clone
379 const remove = Object.keys(apiParams).filter(k => k.match(/^_/));
380 remove.forEach(p => delete apiParams[p]);
382 // This modifier is not sent to the server.
383 // Should be _-prefixed, but we already have a workstation setting,
384 // etc. for this one. Just manually remove it from the API params.
385 delete apiParams['auto_print_holds_transits'];
390 checkout(params: CheckoutParams): Promise<CheckoutResult> {
392 params.new_copy_alerts = true;
393 params._renewal = false;
394 console.debug('checking out with', params);
396 let method = 'open-ils.circ.checkout.full';
397 if (params._override) { method += '.override'; }
399 return this.inspectBarcode(params).then(barcodeOk => {
400 if (!barcodeOk) { return null; }
402 return this.net.request(
403 'open-ils.circ', method,
404 this.auth.token(), this.apiParams(params)).toPromise()
405 .then(result => this.unpackCheckoutData(params, result))
406 .then(result => this.processCheckoutResult(result));
410 renew(params: CheckoutParams): Promise<CheckoutResult> {
412 params.new_copy_alerts = true;
413 params._renewal = true;
414 console.debug('renewing out with', params);
416 let method = 'open-ils.circ.renew';
417 if (params._override) { method += '.override'; }
419 return this.inspectBarcode(params).then(barcodeOk => {
420 if (!barcodeOk) { return null; }
422 return this.net.request(
423 'open-ils.circ', method,
424 this.auth.token(), this.apiParams(params)).toPromise()
425 .then(result => this.unpackCheckoutData(params, result))
426 .then(result => this.processCheckoutResult(result));
432 params: CheckoutParams, response: any): Promise<CheckoutResult> {
434 const allEvents = Array.isArray(response) ?
435 response.map(r => this.evt.parse(r)) :
436 [this.evt.parse(response)];
438 console.debug('checkout events', allEvents.map(e => e.textcode));
439 console.debug('checkout returned', allEvents);
441 const firstEvent = allEvents[0];
442 const payload = firstEvent.payload;
444 const result: CheckoutResult = {
445 index: CircService.resultIndex++,
446 firstEvent: firstEvent,
447 allEvents: allEvents,
452 // Some scenarios (e.g. copy in transit) have no payload,
454 if (!payload) { return Promise.resolve(result); }
456 result.circ = payload.circ;
457 result.copy = payload.copy;
458 result.volume = payload.volume;
459 result.record = payload.record;
460 result.nonCatCirc = payload.noncat_circ;
462 return this.fleshCommonData(result).then(_ => {
463 const action = params._renewal ? 'renew' :
464 (params.noncat ? 'noncat_checkout' : 'checkout');
465 this.addWorkLog(action, result);
470 processCheckoutResult(result: CheckoutResult): Promise<CheckoutResult> {
471 const renewing = result.params._renewal;
472 const key = renewing ? 'renew' : 'checkout';
474 const overridable = renewing ?
475 CAN_OVERRIDE_RENEW_EVENTS : CAN_OVERRIDE_CHECKOUT_EVENTS;
477 if (result.allEvents.filter(
478 e => overridable.includes(e.textcode)).length > 0) {
479 return this.handleOverridableCheckoutEvents(result);
482 switch (result.firstEvent.textcode) {
484 result.success = true;
485 this.audio.play(`success.${key}`);
486 return Promise.resolve(result);
488 case 'ITEM_NOT_CATALOGED':
489 return this.handlePrecat(result);
491 case 'OPEN_CIRCULATION_EXISTS':
492 return this.handleOpenCirc(result);
494 case 'COPY_IN_TRANSIT':
495 this.audio.play(`warning.${key}.in_transit`);
496 return this.copyInTransitDialog(result);
498 case 'PATRON_CARD_INACTIVE':
499 case 'PATRON_INACTIVE':
500 case 'PATRON_ACCOUNT_EXPIRED':
501 case 'CIRC_CLAIMS_RETURNED':
502 case 'ACTOR_USER_NOT_FOUND':
503 case 'AVAIL_HOLD_COPY_RATIO_EXCEEDED':
504 this.audio.play(`warning.${key}`);
505 return this.exitAlert({
506 textcode: result.firstEvent.textcode,
507 barcode: result.params.copy_barcode
510 case 'ASSET_COPY_NOT_FOUND':
511 this.audio.play(`error.${key}.not_found`);
512 return this.exitAlert({
513 textcode: result.firstEvent.textcode,
514 barcode: result.params.copy_barcode
518 this.audio.play(`error.${key}.unknown`);
519 return this.exitAlert({
520 textcode: 'CHECKOUT_FAILED_GENERIC',
521 barcode: result.params.copy_barcode
526 exitAlert(context: any): Promise<any> {
527 const key = 'staff.circ.events.' + context.textcode;
528 return this.strings.interpolate(key, context)
530 this.components.circFailedDialog.dialogBody = str;
531 return this.components.circFailedDialog.open().toPromise();
533 .then(_ => Promise.reject('Bailling on event ' + context.textcode));
536 copyInTransitDialog(result: CheckoutResult): Promise<CheckoutResult> {
537 this.components.copyInTransitDialog.checkout = result;
539 return this.findCopyTransitByBarcode(result)
540 .then(_ => this.components.copyInTransitDialog.open().toPromise())
541 .then(cancelAndCheckout => {
542 if (cancelAndCheckout) {
544 return this.abortTransit(result.transit.id())
546 // We had to look up the copy from the barcode since
547 // it was not embedded in the result event. Since
548 // we have the specifics on the copy, go ahead and
549 // copy them into the params we use for the follow
551 result.params.copy_barcode = result.copy.barcode();
552 result.params.copy_id = result.copy.id();
553 return this.checkout(result.params);
562 // Ask the user if we should resolve the circulation and check
563 // out to the user or leave it alone.
564 // When resolving and checking out, renew if it's for the same
565 // user, otherwise check it in, then back out to the current user.
566 handleOpenCirc(result: CheckoutResult): Promise<CheckoutResult> {
568 let sameUser = false;
570 return this.net.request(
572 'open-ils.circ.copy_checkout_history.retrieve',
573 this.auth.token(), result.params.copy_id, 1).toPromise()
576 const circ = circs[0];
578 sameUser = result.params.patron_id === circ.usr();
579 this.components.openCircDialog.sameUser = sameUser;
580 this.components.openCircDialog.circDate = circ.xact_start();
582 return this.components.openCircDialog.open().toPromise();
585 .then(fromDialog => {
587 // Leave the open circ checked out.
588 if (!fromDialog) { return result; }
590 const coParams = Object.assign({}, result.params); // clone
593 coParams.void_overdues = fromDialog.forgiveFines;
594 return this.renew(coParams);
597 const ciParams: CheckinParams = {
599 copy_id: coParams.copy_id,
600 void_overdues: fromDialog.forgiveFines
603 return this.checkin(ciParams)
606 return this.checkout(coParams);
608 return Promise.reject('Unable to check in item');
614 handleOverridableCheckoutEvents(result: CheckoutResult): Promise<CheckoutResult> {
615 const params = result.params;
616 const firstEvent = result.firstEvent;
617 const events = result.allEvents;
619 if (params._override) {
620 // Should never get here. Just being safe.
621 return Promise.reject(null);
625 e => !this.autoOverrideCheckoutEvents[e.textcode]).length === 0) {
626 // User has already seen all of these events and overridden them,
627 // so avoid showing them again since they are all auto-overridable.
628 params._override = true;
629 return params._renewal ? this.renew(params) : this.checkout(params);
632 // New-style alerts are reported via COPY_ALERT_MESSAGE and
633 // includes the alerts in the payload as an array.
634 if (firstEvent.textcode === 'COPY_ALERT_MESSAGE'
635 && Array.isArray(firstEvent.payload)) {
636 this.components.copyAlertManager.alerts = firstEvent.payload;
638 this.components.copyAlertManager.mode =
639 params._renewal ? 'renew' : 'checkout';
641 return this.components.copyAlertManager.open().toPromise()
644 params._override = true;
645 return this.checkout(params);
650 return this.showOverrideDialog(result, events);
653 showOverrideDialog(result: CheckoutResult,
654 events: EgEvent[], checkin?: boolean): Promise<CheckoutResult> {
656 const params = result.params;
657 const mode = checkin ? 'checkin' : (params._renewal ? 'renew' : 'checkout');
659 const holdShelfEvent = events.filter(e => e.textcode === 'ITEM_ON_HOLDS_SHELF')[0];
661 if (holdShelfEvent) {
662 this.components.circEventsDialog.clearHolds = this.clearHoldsOnCheckout;
663 this.components.circEventsDialog.patronId = holdShelfEvent.payload.patron_id;
664 this.components.circEventsDialog.patronName = holdShelfEvent.payload.patron_name;
667 this.components.circEventsDialog.copyBarcode = result.params.copy_barcode;
668 this.components.circEventsDialog.events = events;
669 this.components.circEventsDialog.mode = mode;
671 return this.components.circEventsDialog.open().toPromise()
673 const confirmed = resp.override;
674 if (!confirmed) { return null; }
676 let promise = Promise.resolve(null);
679 // Indicate these events have been seen and overridden.
680 events.forEach(evt => {
681 if (CHECKOUT_OVERRIDE_AFTER_FIRST.includes(evt.textcode)) {
682 this.autoOverrideCheckoutEvents[evt.textcode] = true;
686 if (holdShelfEvent && resp.clearHold) {
687 const holdId = holdShelfEvent.payload.hold_id;
689 // Cancel the hold that put our checkout item
690 // on the holds shelf.
692 promise = promise.then(_ => {
693 return this.net.request(
695 'open-ils.circ.hold.cancel',
699 'Item checked out by other patron' // FIXME I18n
705 return promise.then(_ => {
706 params._override = true;
707 return this[mode](params); // checkout/renew/checkin
712 handlePrecat(result: CheckoutResult): Promise<CheckoutResult> {
713 this.components.precatDialog.barcode = result.params.copy_barcode;
715 return this.components.precatDialog.open().toPromise().then(values => {
717 if (values && values.dummy_title) {
718 const params = result.params;
719 params.precat = true;
720 Object.keys(values).forEach(key => params[key] = values[key]);
721 return this.checkout(params);
724 result.canceled = true;
725 return Promise.resolve(result);
729 checkin(params: CheckinParams): Promise<CheckinResult> {
730 params.new_copy_alerts = true;
732 console.debug('checking in with', params);
734 let method = 'open-ils.circ.checkin';
735 if (params._override) { method += '.override'; }
737 return this.inspectBarcode(params).then(barcodeOk => {
738 if (!barcodeOk) { return null; }
740 return this.net.request(
741 'open-ils.circ', method,
742 this.auth.token(), this.apiParams(params)).toPromise()
743 .then(result => this.unpackCheckinData(params, result))
744 .then(result => this.processCheckinResult(result));
748 fleshCommonData(result: CircResultCommon): Promise<CircResultCommon> {
750 const copy = result.copy;
751 const volume = result.volume;
752 const circ = result.circ;
753 const hold = result.hold;
754 const nonCatCirc = (result as CheckoutResult).nonCatCirc;
756 let promise = Promise.resolve();
758 if (!result.patron) {
761 patronId = hold.usr();
763 patronId = circ.usr();
764 } else if (nonCatCirc) {
765 patronId = nonCatCirc.patron();
769 promise = promise.then(_ => {
770 return this.pcrud.retrieve('au', patronId,
771 {flesh: 1, flesh_fields : {'au' : ['card']}})
772 .toPromise().then(p => result.patron = p);
779 result.title = result.record.title();
780 result.author = result.record.author();
781 result.isbn = result.record.isbn();
784 result.title = result.copy.dummy_title();
785 result.author = result.copy.dummy_author();
786 result.isbn = result.copy.dummy_isbn();
790 if (this.copyLocationCache[copy.location()]) {
791 copy.location(this.copyLocationCache[copy.location()]);
793 promise = this.pcrud.retrieve('acpl', copy.location()).toPromise()
796 this.copyLocationCache[loc.id()] = loc;
800 if (typeof copy.status() !== 'object') {
801 promise = promise.then(_ => this.holdings.getCopyStatuses())
804 Object.values(stats).filter(s => s.id() === copy.status())[0];
805 if (stat) { copy.status(stat); }
811 // Flesh volume prefixes and suffixes
813 if (typeof volume.prefix() !== 'object') {
814 promise = promise.then(_ =>
815 this.pcrud.retrieve('acnp', volume.prefix()).toPromise()
816 ).then(p => volume.prefix(p));
819 if (typeof volume.suffix() !== 'object') {
820 promise = promise.then(_ =>
821 this.pcrud.retrieve('acns', volume.suffix()).toPromise()
822 ).then(p => volume.suffix(p));
826 return promise.then(_ => result);
829 unpackCheckinData(params: CheckinParams, response: any): Promise<CheckinResult> {
830 const allEvents = Array.isArray(response) ?
831 response.map(r => this.evt.parse(r)) : [this.evt.parse(response)];
833 console.debug('checkin events', allEvents.map(e => e.textcode));
834 console.debug('checkin response', response);
836 const firstEvent = allEvents[0];
837 const payload = firstEvent.payload;
840 firstEvent.textcode.match(/SUCCESS|NO_CHANGE|ROUTE_ITEM/) !== null;
842 const result: CheckinResult = {
843 index: CircService.resultIndex++,
844 firstEvent: firstEvent,
845 allEvents: allEvents,
851 // e.g. ASSET_COPY_NOT_FOUND
852 return Promise.resolve(result);
855 result.circ = payload.circ;
856 result.parent_circ = payload.parent_circ;
857 result.copy = payload.copy;
858 result.volume = payload.volume;
859 result.record = payload.record;
860 result.transit = payload.transit;
861 result.hold = payload.hold;
863 const copy = result.copy;
864 const volume = result.volume;
865 const transit = result.transit;
866 const circ = result.circ;
867 const parent_circ = result.parent_circ;
870 if (typeof transit.dest() !== 'object') {
871 transit.dest(this.org.get(transit.dest()));
873 if (typeof transit.source() !== 'object') {
874 transit.source(this.org.get(transit.source()));
878 // for checkin, the mbts lives on the main circ
879 if (circ && circ.billable_transaction()) {
880 result.mbts = circ.billable_transaction().summary();
883 // on renewals, the mbts lives on the parent circ
884 if (parent_circ && parent_circ.billable_transaction()) {
885 result.mbts = parent_circ.billable_transaction().summary();
888 return this.fleshCommonData(result).then(_ => {
889 this.addWorkLog('checkin', result);
894 processCheckinResult(result: CheckinResult): Promise<CheckinResult> {
895 const params = result.params;
896 const allEvents = result.allEvents;
898 // Informational alerts that can be ignored if configured.
899 if (this.suppressCheckinPopups &&
900 allEvents.filter(e =>
901 !CAN_SUPPRESS_CHECKIN_ALERTS.includes(e.textcode)).length === 0) {
903 // Should not be necessary, but good to be safe.
904 if (params._override) { return Promise.resolve(null); }
906 params._override = true;
907 return this.checkin(params);
910 // Alerts that require a manual override.
911 if (allEvents.filter(
912 e => CAN_OVERRIDE_CHECKIN_ALERTS.includes(e.textcode)).length > 0) {
913 return this.handleOverridableCheckinEvents(result);
916 switch (result.firstEvent.textcode) {
919 return this.handleCheckinSuccess(result);
921 case 'ITEM_NOT_CATALOGED':
922 this.audio.play('error.checkout.no_cataloged');
923 result.routeTo = this.components.catalogingStr.text;
924 return this.showPrecatAlert().then(_ => result);
927 this.audio.play(result.hold ?
928 'info.checkin.transit.hold' : 'info.checkin.transit');
931 console.debug('Skipping route dialog on "noop" checkin');
932 return Promise.resolve(result);
935 this.components.routeDialog.checkin = result;
936 return this.findCopyTransit(result)
937 .then(_ => this.components.routeDialog.open().toPromise())
940 case 'ASSET_COPY_NOT_FOUND':
941 this.audio.play('error.checkin.not_found');
942 return this.handleCheckinUncatAlert(result);
945 this.audio.play('error.checkin.unknown');
947 'Unhandled checkin response : ' + result.firstEvent.textcode);
950 return Promise.resolve(result);
953 addWorkLog(action: string, result: CircResultCommon) {
954 const params = result.params;
955 const copy = result.copy;
956 const patron = result.patron;
958 // Some worklog data may be provided by the caller in the params.
959 const entry: WorkLogEntry =
960 Object.assign(params._worklog || {}, {action: action});
963 entry.item = copy.barcode();
964 entry.item_id = copy.id();
966 entry.item = params.copy_barcode;
967 entry.item_id = params.copy_id;
971 entry.patron_id = patron.id();
972 entry.user = patron.family_name();
976 entry.hold_id = result.hold.id();
979 this.worklog.record(entry);
982 showPrecatAlert(): Promise<any> {
983 if (!this.suppressCheckinPopups && !this.ignoreCheckinPrecats) {
984 // Tell the user its a precat and return the result.
985 return this.components.routeToCatalogingDialog.open()
988 return Promise.resolve(null);
991 handleCheckinSuccess(result: CheckinResult): Promise<CheckinResult> {
992 const copy = result.copy;
994 if (!copy) { return Promise.resolve(result); }
996 const stat = copy.status();
997 const statId = typeof stat === 'object' ? stat.id() : stat;
1001 case 0: /* AVAILABLE */
1002 case 4: /* MISSING */
1003 case 7: /* RESHELVING */
1004 this.audio.play('success.checkin');
1005 return this.handleCheckinLocAlert(result);
1007 case 8: /* ON HOLDS SHELF */
1008 this.audio.play('info.checkin.holds_shelf');
1010 const hold = result.hold;
1014 if (Number(hold.pickup_lib()) === Number(this.auth.user().ws_ou())) {
1015 result.routeTo = this.components.holdShelfStr.text;
1016 this.components.routeDialog.checkin = result;
1017 return this.components.routeDialog.open().toPromise()
1021 // Should not happen in practice, but to be safe.
1022 this.audio.play('warning.checkin.wrong_shelf');
1026 console.warn('API Returned insufficient info on holds');
1030 case 11: /* CATALOGING */
1031 this.audio.play('info.checkin.cataloging');
1032 result.routeTo = this.components.catalogingStr.text;
1033 return this.showPrecatAlert().then(_ => result);
1035 case 15: /* ON_RESERVATION_SHELF */
1036 this.audio.play('info.checkin.reservation');
1040 this.audio.play('success.checkin');
1041 console.debug(`Unusual checkin copy status (may have been
1042 set via copy alert): status=${statId}`);
1045 return Promise.resolve(result);
1048 handleCheckinLocAlert(result: CheckinResult): Promise<CheckinResult> {
1049 const copy = result.copy;
1051 if (this.suppressCheckinPopups
1052 || copy.location().checkin_alert() === 'f') {
1053 return Promise.resolve(result);
1056 return this.strings.interpolate(
1057 'staff.circ.checkin.location.alert',
1058 {barcode: copy.barcode(), location: copy.location().name()}
1060 this.components.locationAlertDialog.dialogBody = str;
1061 return this.components.locationAlertDialog.open().toPromise()
1066 handleCheckinUncatAlert(result: CheckinResult): Promise<CheckinResult> {
1067 const barcode = result.copy ?
1068 result.copy.barcode() : result.params.copy_barcode;
1070 if (this.suppressCheckinPopups) {
1071 return Promise.resolve(result);
1074 return this.strings.interpolate(
1075 'staff.circ.checkin.uncat.alert', {barcode: barcode}
1077 this.components.uncatAlertDialog.dialogBody = str;
1078 return this.components.uncatAlertDialog.open().toPromise()
1084 handleOverridableCheckinEvents(result: CheckinResult): Promise<CheckinResult> {
1085 const params = result.params;
1086 const events = result.allEvents;
1087 const firstEvent = result.firstEvent;
1089 if (params._override) {
1090 // Should never get here. Just being safe.
1091 return Promise.reject(null);
1094 if (this.suppressCheckinPopups && events.filter(
1095 e => !CAN_SUPPRESS_CHECKIN_ALERTS.includes(e.textcode)).length === 0) {
1096 // These events are automatically overridden when suppress
1097 // popups are in effect.
1098 params._override = true;
1099 return this.checkin(params);
1102 // New-style alerts are reported via COPY_ALERT_MESSAGE and
1103 // includes the alerts in the payload as an array.
1104 if (firstEvent.textcode === 'COPY_ALERT_MESSAGE'
1105 && Array.isArray(firstEvent.payload)) {
1106 this.components.copyAlertManager.alerts = firstEvent.payload;
1107 this.components.copyAlertManager.mode = 'checkin';
1109 return this.components.copyAlertManager.open().toPromise()
1112 if (!resp) { return result; } // dialog was canceled
1114 if (resp.nextStatus !== null) {
1115 params.next_copy_status = [resp.nextStatus];
1116 params.capture = 'nocapture';
1119 params._override = true;
1121 return this.checkin(params);
1125 return this.showOverrideDialog(result, events, true);
1129 // The provided params (minus the copy_id) will be used
1131 checkoutBatch(copyIds: number[],
1132 params: CheckoutParams): Observable<CheckoutResult> {
1134 if (copyIds.length === 0) { return empty(); }
1136 return from(copyIds).pipe(concatMap(id => {
1137 const cparams = Object.assign({}, params); // clone
1138 cparams.copy_id = id;
1139 return from(this.checkout(cparams));
1143 // The provided params (minus the copy_id) will be used
1145 renewBatch(copyIds: number[],
1146 params?: CheckoutParams): Observable<CheckoutResult> {
1148 if (copyIds.length === 0) { return empty(); }
1149 if (!params) { params = {}; }
1151 return from(copyIds).pipe(concatMap(id => {
1152 const cparams = Object.assign({}, params); // clone
1153 cparams.copy_id = id;
1154 return from(this.renew(cparams));
1158 // The provided params (minus the copy_id) will be used
1160 checkinBatch(copyIds: number[],
1161 params?: CheckinParams): Observable<CheckinResult> {
1163 if (copyIds.length === 0) { return empty(); }
1164 if (!params) { params = {}; }
1166 return from(copyIds).pipe(concatMap(id => {
1167 const cparams = Object.assign({}, params); // clone
1168 cparams.copy_id = id;
1169 return from(this.checkin(cparams));
1173 abortTransit(transitId: number): Promise<any> {
1174 return this.net.request(
1176 'open-ils.circ.transit.abort',
1177 this.auth.token(), {transitid : transitId}
1178 ).toPromise().then(resp => {
1179 const evt = this.evt.parse(resp);
1182 return Promise.reject(evt.toString());
1184 return Promise.resolve();
1188 lastCopyCirc(copyId: number): Promise<IdlObject> {
1189 return this.pcrud.search('circ',
1190 {target_copy : copyId},
1191 {order_by : {circ : 'xact_start desc' }, limit : 1}
1195 // Resolves to true if the barcode is OK or the user confirmed it or
1196 // the user doesn't care to begin with
1197 inspectBarcode(params: CheckoutParams | CheckinParams): Promise<boolean> {
1198 if (!params._checkbarcode || !params.copy_barcode) {
1199 return Promise.resolve(true);
1202 if (this.checkBarcode(params.copy_barcode)) {
1203 // Avoid prompting again on an override
1204 params._checkbarcode = false;
1205 return Promise.resolve(true);
1208 this.components.badBarcodeDialog.barcode = params.copy_barcode;
1209 return this.components.badBarcodeDialog.open().toPromise()
1210 // Avoid prompting again on an override
1212 params._checkbarcode = false
1217 checkBarcode(barcode: string): boolean {
1218 if (barcode !== Number(barcode).toString()) { return false; }
1220 const bc = barcode.toString();
1222 // "16.00" == Number("16.00"), but the . is bad.
1223 // Throw out any barcode that isn't just digits
1224 if (bc.search(/\D/) !== -1) { return false; }
1226 const lastDigit = bc.substr(bc.length - 1);
1227 const strippedBarcode = bc.substr(0, bc.length - 1);
1228 return this.barcodeCheckdigit(strippedBarcode).toString() === lastDigit;
1231 barcodeCheckdigit(bc: string): number {
1234 const reverseBarcode = bc.toString().split('').reverse();
1236 reverseBarcode.forEach(ch => {
1238 const product = (Number(ch) * multiplier) + '';
1239 product.split('').forEach(num => tempSum += Number(num));
1240 checkSum += Number(tempSum);
1241 multiplier = multiplier === 2 ? 1 : 2;
1244 const cSumStr = checkSum.toString();
1245 const nextMultipleOf10 =
1246 (Number(cSumStr.match(/(\d*)\d$/)[1]) * 10) + 10;
1248 let checkDigit = nextMultipleOf10 - Number(cSumStr);
1249 if (checkDigit === 10) { checkDigit = 0; }