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.record = payload.record;
459 result.nonCatCirc = payload.noncat_circ;
461 return this.fleshCommonData(result).then(_ => {
462 const action = params._renewal ? 'renew' :
463 (params.noncat ? 'noncat_checkout' : 'checkout');
464 this.addWorkLog(action, result);
469 processCheckoutResult(result: CheckoutResult): Promise<CheckoutResult> {
470 const renewing = result.params._renewal;
471 const key = renewing ? 'renew' : 'checkout';
473 const overridable = renewing ?
474 CAN_OVERRIDE_RENEW_EVENTS : CAN_OVERRIDE_CHECKOUT_EVENTS;
476 if (result.allEvents.filter(
477 e => overridable.includes(e.textcode)).length > 0) {
478 return this.handleOverridableCheckoutEvents(result);
481 switch (result.firstEvent.textcode) {
483 result.success = true;
484 this.audio.play(`success.${key}`);
485 return Promise.resolve(result);
487 case 'ITEM_NOT_CATALOGED':
488 return this.handlePrecat(result);
490 case 'OPEN_CIRCULATION_EXISTS':
491 return this.handleOpenCirc(result);
493 case 'COPY_IN_TRANSIT':
494 this.audio.play(`warning.${key}.in_transit`);
495 return this.copyInTransitDialog(result);
497 case 'PATRON_CARD_INACTIVE':
498 case 'PATRON_INACTIVE':
499 case 'PATRON_ACCOUNT_EXPIRED':
500 case 'CIRC_CLAIMS_RETURNED':
501 case 'ACTOR_USER_NOT_FOUND':
502 case 'AVAIL_HOLD_COPY_RATIO_EXCEEDED':
503 this.audio.play(`warning.${key}`);
504 return this.exitAlert({
505 textcode: result.firstEvent.textcode,
506 barcode: result.params.copy_barcode
509 case 'ASSET_COPY_NOT_FOUND':
510 this.audio.play(`error.${key}.not_found`);
511 return this.exitAlert({
512 textcode: result.firstEvent.textcode,
513 barcode: result.params.copy_barcode
517 this.audio.play(`error.${key}.unknown`);
518 return this.exitAlert({
519 textcode: 'CHECKOUT_FAILED_GENERIC',
520 barcode: result.params.copy_barcode
525 exitAlert(context: any): Promise<any> {
526 const key = 'staff.circ.events.' + context.textcode;
527 return this.strings.interpolate(key, context)
529 this.components.circFailedDialog.dialogBody = str;
530 return this.components.circFailedDialog.open().toPromise();
532 .then(_ => Promise.reject('Bailling on event ' + context.textcode));
535 copyInTransitDialog(result: CheckoutResult): Promise<CheckoutResult> {
536 this.components.copyInTransitDialog.checkout = result;
538 return this.findCopyTransitByBarcode(result)
539 .then(_ => this.components.copyInTransitDialog.open().toPromise())
540 .then(cancelAndCheckout => {
541 if (cancelAndCheckout) {
543 return this.abortTransit(result.transit.id())
545 // We had to look up the copy from the barcode since
546 // it was not embedded in the result event. Since
547 // we have the specifics on the copy, go ahead and
548 // copy them into the params we use for the follow
550 result.params.copy_barcode = result.copy.barcode();
551 result.params.copy_id = result.copy.id();
552 return this.checkout(result.params);
561 // Ask the user if we should resolve the circulation and check
562 // out to the user or leave it alone.
563 // When resolving and checking out, renew if it's for the same
564 // user, otherwise check it in, then back out to the current user.
565 handleOpenCirc(result: CheckoutResult): Promise<CheckoutResult> {
567 let sameUser = false;
569 return this.net.request(
571 'open-ils.circ.copy_checkout_history.retrieve',
572 this.auth.token(), result.params.copy_id, 1).toPromise()
575 const circ = circs[0];
577 sameUser = result.params.patron_id === circ.usr();
578 this.components.openCircDialog.sameUser = sameUser;
579 this.components.openCircDialog.circDate = circ.xact_start();
581 return this.components.openCircDialog.open().toPromise();
584 .then(fromDialog => {
586 // Leave the open circ checked out.
587 if (!fromDialog) { return result; }
589 const coParams = Object.assign({}, result.params); // clone
592 coParams.void_overdues = fromDialog.forgiveFines;
593 return this.renew(coParams);
596 const ciParams: CheckinParams = {
598 copy_id: coParams.copy_id,
599 void_overdues: fromDialog.forgiveFines
602 return this.checkin(ciParams)
605 return this.checkout(coParams);
607 return Promise.reject('Unable to check in item');
613 handleOverridableCheckoutEvents(result: CheckoutResult): Promise<CheckoutResult> {
614 const params = result.params;
615 const firstEvent = result.firstEvent;
616 const events = result.allEvents;
618 if (params._override) {
619 // Should never get here. Just being safe.
620 return Promise.reject(null);
624 e => !this.autoOverrideCheckoutEvents[e.textcode]).length === 0) {
625 // User has already seen all of these events and overridden them,
626 // so avoid showing them again since they are all auto-overridable.
627 params._override = true;
628 return params._renewal ? this.renew(params) : this.checkout(params);
631 // New-style alerts are reported via COPY_ALERT_MESSAGE and
632 // includes the alerts in the payload as an array.
633 if (firstEvent.textcode === 'COPY_ALERT_MESSAGE'
634 && Array.isArray(firstEvent.payload)) {
635 this.components.copyAlertManager.alerts = firstEvent.payload;
637 this.components.copyAlertManager.mode =
638 params._renewal ? 'renew' : 'checkout';
640 return this.components.copyAlertManager.open().toPromise()
643 params._override = true;
644 return this.checkout(params);
649 return this.showOverrideDialog(result, events);
652 showOverrideDialog(result: CheckoutResult,
653 events: EgEvent[], checkin?: boolean): Promise<CheckoutResult> {
655 const params = result.params;
656 const mode = checkin ? 'checkin' : (params._renewal ? 'renew' : 'checkout');
658 const holdShelfEvent = events.filter(e => e.textcode === 'ITEM_ON_HOLDS_SHELF')[0];
660 if (holdShelfEvent) {
661 this.components.circEventsDialog.clearHolds = this.clearHoldsOnCheckout;
662 this.components.circEventsDialog.patronId = holdShelfEvent.payload.patron_id;
663 this.components.circEventsDialog.patronName = holdShelfEvent.payload.patron_name;
666 this.components.circEventsDialog.copyBarcode = result.params.copy_barcode;
667 this.components.circEventsDialog.events = events;
668 this.components.circEventsDialog.mode = mode;
670 return this.components.circEventsDialog.open().toPromise()
672 const confirmed = resp.override;
673 if (!confirmed) { return null; }
675 let promise = Promise.resolve(null);
678 // Indicate these events have been seen and overridden.
679 events.forEach(evt => {
680 if (CHECKOUT_OVERRIDE_AFTER_FIRST.includes(evt.textcode)) {
681 this.autoOverrideCheckoutEvents[evt.textcode] = true;
685 if (holdShelfEvent && resp.clearHold) {
686 const holdId = holdShelfEvent.payload.hold_id;
688 // Cancel the hold that put our checkout item
689 // on the holds shelf.
691 promise = promise.then(_ => {
692 return this.net.request(
694 'open-ils.circ.hold.cancel',
698 'Item checked out by other patron' // FIXME I18n
704 return promise.then(_ => {
705 params._override = true;
706 return this[mode](params); // checkout/renew/checkin
711 handlePrecat(result: CheckoutResult): Promise<CheckoutResult> {
712 this.components.precatDialog.barcode = result.params.copy_barcode;
714 return this.components.precatDialog.open().toPromise().then(values => {
716 if (values && values.dummy_title) {
717 const params = result.params;
718 params.precat = true;
719 Object.keys(values).forEach(key => params[key] = values[key]);
720 return this.checkout(params);
723 result.canceled = true;
724 return Promise.resolve(result);
728 checkin(params: CheckinParams): Promise<CheckinResult> {
729 params.new_copy_alerts = true;
731 console.debug('checking in with', params);
733 let method = 'open-ils.circ.checkin';
734 if (params._override) { method += '.override'; }
736 return this.inspectBarcode(params).then(barcodeOk => {
737 if (!barcodeOk) { return null; }
739 return this.net.request(
740 'open-ils.circ', method,
741 this.auth.token(), this.apiParams(params)).toPromise()
742 .then(result => this.unpackCheckinData(params, result))
743 .then(result => this.processCheckinResult(result));
747 fleshCommonData(result: CircResultCommon): Promise<CircResultCommon> {
749 const copy = result.copy;
750 const volume = result.volume;
751 const circ = result.circ;
752 const hold = result.hold;
753 const nonCatCirc = (result as CheckoutResult).nonCatCirc;
755 let promise = Promise.resolve();
757 if (!result.patron) {
760 patronId = hold.usr();
762 patronId = circ.usr();
763 } else if (nonCatCirc) {
764 patronId = nonCatCirc.patron();
768 promise = promise.then(_ => {
769 return this.pcrud.retrieve('au', patronId,
770 {flesh: 1, flesh_fields : {'au' : ['card']}})
771 .toPromise().then(p => result.patron = p);
778 result.title = result.record.title();
779 result.author = result.record.author();
780 result.isbn = result.record.isbn();
783 result.title = result.copy.dummy_title();
784 result.author = result.copy.dummy_author();
785 result.isbn = result.copy.dummy_isbn();
789 if (this.copyLocationCache[copy.location()]) {
790 copy.location(this.copyLocationCache[copy.location()]);
792 promise = this.pcrud.retrieve('acpl', copy.location()).toPromise()
795 this.copyLocationCache[loc.id()] = loc;
799 if (typeof copy.status() !== 'object') {
800 promise = promise.then(_ => this.holdings.getCopyStatuses())
803 Object.values(stats).filter(s => s.id() === copy.status())[0];
804 if (stat) { copy.status(stat); }
810 // Flesh volume prefixes and suffixes
812 if (typeof volume.prefix() !== 'object') {
813 promise = promise.then(_ =>
814 this.pcrud.retrieve('acnp', volume.prefix()).toPromise()
815 ).then(p => volume.prefix(p));
818 if (typeof volume.suffix() !== 'object') {
819 promise = promise.then(_ =>
820 this.pcrud.retrieve('acns', volume.suffix()).toPromise()
821 ).then(p => volume.suffix(p));
825 return promise.then(_ => result);
828 unpackCheckinData(params: CheckinParams, response: any): Promise<CheckinResult> {
829 const allEvents = Array.isArray(response) ?
830 response.map(r => this.evt.parse(r)) : [this.evt.parse(response)];
832 console.debug('checkin events', allEvents.map(e => e.textcode));
833 console.debug('checkin response', response);
835 const firstEvent = allEvents[0];
836 const payload = firstEvent.payload;
839 firstEvent.textcode.match(/SUCCESS|NO_CHANGE|ROUTE_ITEM/) !== null;
841 const result: CheckinResult = {
842 index: CircService.resultIndex++,
843 firstEvent: firstEvent,
844 allEvents: allEvents,
850 // e.g. ASSET_COPY_NOT_FOUND
851 return Promise.resolve(result);
854 result.circ = payload.circ;
855 result.parent_circ = payload.parent_circ;
856 result.copy = payload.copy;
857 result.volume = payload.volume;
858 result.record = payload.record;
859 result.transit = payload.transit;
860 result.hold = payload.hold;
862 const copy = result.copy;
863 const volume = result.volume;
864 const transit = result.transit;
865 const circ = result.circ;
866 const parent_circ = result.parent_circ;
869 if (typeof transit.dest() !== 'object') {
870 transit.dest(this.org.get(transit.dest()));
872 if (typeof transit.source() !== 'object') {
873 transit.source(this.org.get(transit.source()));
877 // for checkin, the mbts lives on the main circ
878 if (circ && circ.billable_transaction()) {
879 result.mbts = circ.billable_transaction().summary();
882 // on renewals, the mbts lives on the parent circ
883 if (parent_circ && parent_circ.billable_transaction()) {
884 result.mbts = parent_circ.billable_transaction().summary();
887 return this.fleshCommonData(result).then(_ => {
888 this.addWorkLog('checkin', result);
893 processCheckinResult(result: CheckinResult): Promise<CheckinResult> {
894 const params = result.params;
895 const allEvents = result.allEvents;
897 // Informational alerts that can be ignored if configured.
898 if (this.suppressCheckinPopups &&
899 allEvents.filter(e =>
900 !CAN_SUPPRESS_CHECKIN_ALERTS.includes(e.textcode)).length === 0) {
902 // Should not be necessary, but good to be safe.
903 if (params._override) { return Promise.resolve(null); }
905 params._override = true;
906 return this.checkin(params);
909 // Alerts that require a manual override.
910 if (allEvents.filter(
911 e => CAN_OVERRIDE_CHECKIN_ALERTS.includes(e.textcode)).length > 0) {
912 return this.handleOverridableCheckinEvents(result);
915 switch (result.firstEvent.textcode) {
918 return this.handleCheckinSuccess(result);
920 case 'ITEM_NOT_CATALOGED':
921 this.audio.play('error.checkout.no_cataloged');
922 result.routeTo = this.components.catalogingStr.text;
923 return this.showPrecatAlert().then(_ => result);
926 this.audio.play(result.hold ?
927 'info.checkin.transit.hold' : 'info.checkin.transit');
930 console.debug('Skipping route dialog on "noop" checkin');
931 return Promise.resolve(result);
934 this.components.routeDialog.checkin = result;
935 return this.findCopyTransit(result)
936 .then(_ => this.components.routeDialog.open().toPromise())
939 case 'ASSET_COPY_NOT_FOUND':
940 this.audio.play('error.checkin.not_found');
941 return this.handleCheckinUncatAlert(result);
944 this.audio.play('error.checkin.unknown');
946 'Unhandled checkin response : ' + result.firstEvent.textcode);
949 return Promise.resolve(result);
952 addWorkLog(action: string, result: CircResultCommon) {
953 const params = result.params;
954 const copy = result.copy;
955 const patron = result.patron;
957 // Some worklog data may be provided by the caller in the params.
958 const entry: WorkLogEntry =
959 Object.assign(params._worklog || {}, {action: action});
962 entry.item = copy.barcode();
963 entry.item_id = copy.id();
965 entry.item = params.copy_barcode;
966 entry.item_id = params.copy_id;
970 entry.patron_id = patron.id();
971 entry.user = patron.family_name();
975 entry.hold_id = result.hold.id();
978 this.worklog.record(entry);
981 showPrecatAlert(): Promise<any> {
982 if (!this.suppressCheckinPopups && !this.ignoreCheckinPrecats) {
983 // Tell the user its a precat and return the result.
984 return this.components.routeToCatalogingDialog.open()
987 return Promise.resolve(null);
990 handleCheckinSuccess(result: CheckinResult): Promise<CheckinResult> {
991 const copy = result.copy;
993 if (!copy) { return Promise.resolve(result); }
995 const stat = copy.status();
996 const statId = typeof stat === 'object' ? stat.id() : stat;
1000 case 0: /* AVAILABLE */
1001 case 4: /* MISSING */
1002 case 7: /* RESHELVING */
1003 this.audio.play('success.checkin');
1004 return this.handleCheckinLocAlert(result);
1006 case 8: /* ON HOLDS SHELF */
1007 this.audio.play('info.checkin.holds_shelf');
1009 const hold = result.hold;
1013 if (Number(hold.pickup_lib()) === Number(this.auth.user().ws_ou())) {
1014 result.routeTo = this.components.holdShelfStr.text;
1015 this.components.routeDialog.checkin = result;
1016 return this.components.routeDialog.open().toPromise()
1020 // Should not happen in practice, but to be safe.
1021 this.audio.play('warning.checkin.wrong_shelf');
1025 console.warn('API Returned insufficient info on holds');
1029 case 11: /* CATALOGING */
1030 this.audio.play('info.checkin.cataloging');
1031 result.routeTo = this.components.catalogingStr.text;
1032 return this.showPrecatAlert().then(_ => result);
1034 case 15: /* ON_RESERVATION_SHELF */
1035 this.audio.play('info.checkin.reservation');
1039 this.audio.play('success.checkin');
1040 console.debug(`Unusual checkin copy status (may have been
1041 set via copy alert): status=${statId}`);
1044 return Promise.resolve(result);
1047 handleCheckinLocAlert(result: CheckinResult): Promise<CheckinResult> {
1048 const copy = result.copy;
1050 if (this.suppressCheckinPopups
1051 || copy.location().checkin_alert() === 'f') {
1052 return Promise.resolve(result);
1055 return this.strings.interpolate(
1056 'staff.circ.checkin.location.alert',
1057 {barcode: copy.barcode(), location: copy.location().name()}
1059 this.components.locationAlertDialog.dialogBody = str;
1060 return this.components.locationAlertDialog.open().toPromise()
1065 handleCheckinUncatAlert(result: CheckinResult): Promise<CheckinResult> {
1066 const barcode = result.copy ?
1067 result.copy.barcode() : result.params.copy_barcode;
1069 if (this.suppressCheckinPopups) {
1070 return Promise.resolve(result);
1073 return this.strings.interpolate(
1074 'staff.circ.checkin.uncat.alert', {barcode: barcode}
1076 this.components.uncatAlertDialog.dialogBody = str;
1077 return this.components.uncatAlertDialog.open().toPromise()
1083 handleOverridableCheckinEvents(result: CheckinResult): Promise<CheckinResult> {
1084 const params = result.params;
1085 const events = result.allEvents;
1086 const firstEvent = result.firstEvent;
1088 if (params._override) {
1089 // Should never get here. Just being safe.
1090 return Promise.reject(null);
1093 if (this.suppressCheckinPopups && events.filter(
1094 e => !CAN_SUPPRESS_CHECKIN_ALERTS.includes(e.textcode)).length === 0) {
1095 // These events are automatically overridden when suppress
1096 // popups are in effect.
1097 params._override = true;
1098 return this.checkin(params);
1101 // New-style alerts are reported via COPY_ALERT_MESSAGE and
1102 // includes the alerts in the payload as an array.
1103 if (firstEvent.textcode === 'COPY_ALERT_MESSAGE'
1104 && Array.isArray(firstEvent.payload)) {
1105 this.components.copyAlertManager.alerts = firstEvent.payload;
1106 this.components.copyAlertManager.mode = 'checkin';
1108 return this.components.copyAlertManager.open().toPromise()
1111 if (!resp) { return result; } // dialog was canceled
1113 if (resp.nextStatus !== null) {
1114 params.next_copy_status = [resp.nextStatus];
1115 params.capture = 'nocapture';
1118 params._override = true;
1120 return this.checkin(params);
1124 return this.showOverrideDialog(result, events, true);
1128 // The provided params (minus the copy_id) will be used
1130 checkoutBatch(copyIds: number[],
1131 params: CheckoutParams): Observable<CheckoutResult> {
1133 if (copyIds.length === 0) { return empty(); }
1135 return from(copyIds).pipe(concatMap(id => {
1136 const cparams = Object.assign({}, params); // clone
1137 cparams.copy_id = id;
1138 return from(this.checkout(cparams));
1142 // The provided params (minus the copy_id) will be used
1144 renewBatch(copyIds: number[],
1145 params?: CheckoutParams): Observable<CheckoutResult> {
1147 if (copyIds.length === 0) { return empty(); }
1148 if (!params) { params = {}; }
1150 return from(copyIds).pipe(concatMap(id => {
1151 const cparams = Object.assign({}, params); // clone
1152 cparams.copy_id = id;
1153 return from(this.renew(cparams));
1157 // The provided params (minus the copy_id) will be used
1159 checkinBatch(copyIds: number[],
1160 params?: CheckinParams): Observable<CheckinResult> {
1162 if (copyIds.length === 0) { return empty(); }
1163 if (!params) { params = {}; }
1165 return from(copyIds).pipe(concatMap(id => {
1166 const cparams = Object.assign({}, params); // clone
1167 cparams.copy_id = id;
1168 return from(this.checkin(cparams));
1172 abortTransit(transitId: number): Promise<any> {
1173 return this.net.request(
1175 'open-ils.circ.transit.abort',
1176 this.auth.token(), {transitid : transitId}
1177 ).toPromise().then(resp => {
1178 const evt = this.evt.parse(resp);
1181 return Promise.reject(evt.toString());
1183 return Promise.resolve();
1187 lastCopyCirc(copyId: number): Promise<IdlObject> {
1188 return this.pcrud.search('circ',
1189 {target_copy : copyId},
1190 {order_by : {circ : 'xact_start desc' }, limit : 1}
1194 // Resolves to true if the barcode is OK or the user confirmed it or
1195 // the user doesn't care to begin with
1196 inspectBarcode(params: CheckoutParams | CheckinParams): Promise<boolean> {
1197 if (!params._checkbarcode || !params.copy_barcode) {
1198 return Promise.resolve(true);
1201 if (this.checkBarcode(params.copy_barcode)) {
1202 // Avoid prompting again on an override
1203 params._checkbarcode = false;
1204 return Promise.resolve(true);
1207 this.components.badBarcodeDialog.barcode = params.copy_barcode;
1208 return this.components.badBarcodeDialog.open().toPromise()
1209 // Avoid prompting again on an override
1211 params._checkbarcode = false
1216 checkBarcode(barcode: string): boolean {
1217 if (barcode !== Number(barcode).toString()) { return false; }
1219 const bc = barcode.toString();
1221 // "16.00" == Number("16.00"), but the . is bad.
1222 // Throw out any barcode that isn't just digits
1223 if (bc.search(/\D/) !== -1) { return false; }
1225 const lastDigit = bc.substr(bc.length - 1);
1226 const strippedBarcode = bc.substr(0, bc.length - 1);
1227 return this.barcodeCheckdigit(strippedBarcode).toString() === lastDigit;
1230 barcodeCheckdigit(bc: string): number {
1233 const reverseBarcode = bc.toString().split('').reverse();
1235 reverseBarcode.forEach(ch => {
1237 const product = (Number(ch) * multiplier) + '';
1238 product.split('').forEach(num => tempSum += Number(num));
1239 checkSum += Number(tempSum);
1240 multiplier = multiplier === 2 ? 1 : 2;
1243 const cSumStr = checkSum.toString();
1244 const nextMultipleOf10 =
1245 (Number(cSumStr.match(/(\d*)\d$/)[1]) * 10) + 10;
1247 let checkDigit = nextMultipleOf10 - Number(cSumStr);
1248 if (checkDigit === 10) { checkDigit = 0; }