LP1904036 Checkin grid shows circ user; routeTo updates
[evergreen-equinox.git] / Open-ILS / src / eg2 / src / app / staff / share / circ / circ.service.ts
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';
18
19 export interface CircDisplayInfo {
20     title?: string;
21     author?: string;
22     isbn?: string;
23     copy?: IdlObject;        // acp
24     volume?: IdlObject;      // acn
25     record?: IdlObject;      // bre
26     display?: IdlObject;     // mwde
27 }
28
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',
34     'PATRON_BARRED',
35     'CIRC_EXCEEDS_COPY_RANGE',
36     'ITEM_DEPOSIT_REQUIRED',
37     'ITEM_RENTAL_FEE_REQUIRED',
38     'PATRON_EXCEEDS_LOST_COUNT',
39     'COPY_CIRC_NOT_ALLOWED',
40     'COPY_NOT_AVAILABLE',
41     'COPY_IS_REFERENCE',
42     'COPY_ALERT_MESSAGE',
43     'ITEM_ON_HOLDS_SHELF',
44     'STAFF_C',
45     'STAFF_CH',
46     'STAFF_CHR',
47     'STAFF_CR',
48     'STAFF_H',
49     'STAFF_HR',
50     'STAFF_R'
51 ];
52
53 const CHECKOUT_OVERRIDE_AFTER_FIRST = [
54     'PATRON_EXCEEDS_OVERDUE_COUNT',
55     'PATRON_BARRED',
56     'PATRON_EXCEEDS_LOST_COUNT',
57     'PATRON_EXCEEDS_CHECKOUT_COUNT',
58     'PATRON_EXCEEDS_FINES',
59     'PATRON_EXCEEDS_LONGOVERDUE_COUNT'
60 ];
61
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',
71     'ITEM_DEPOSIT_PAID',
72     'COPY_CIRC_NOT_ALLOWED',
73     'COPY_NOT_AVAILABLE',
74     'COPY_IS_REFERENCE',
75     'COPY_ALERT_MESSAGE',
76     'COPY_NEEDED_FOR_HOLD',
77     'MAX_RENEWALS_REACHED',
78     'CIRC_CLAIMS_RETURNED',
79     'STAFF_C',
80     'STAFF_CH',
81     'STAFF_CHR',
82     'STAFF_CR',
83     'STAFF_H',
84     'STAFF_HR',
85     'STAFF_R'
86 ];
87
88 // These checkin events do not produce alerts when
89 // options.suppress_alerts is in effect.
90 const CAN_SUPPRESS_CHECKIN_ALERTS = [
91     'COPY_BAD_STATUS',
92     'PATRON_BARRED',
93     'PATRON_INACTIVE',
94     'PATRON_ACCOUNT_EXPIRED',
95     'ITEM_DEPOSIT_PAID',
96     'CIRC_CLAIMS_RETURNED',
97     'COPY_ALERT_MESSAGE',
98     'COPY_STATUS_LOST',
99     'COPY_STATUS_LOST_AND_PAID',
100     'COPY_STATUS_LONG_OVERDUE',
101     'COPY_STATUS_MISSING',
102     'PATRON_EXCEEDS_FINES'
103 ];
104
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);
110
111
112 // API parameter options
113 export interface CheckoutParams {
114     patron_id?: number;
115     due_date?: string;
116     copy_id?: number;
117     copy_barcode?: string;
118     noncat?: boolean;
119     noncat_type?: number;
120     noncat_count?: number;
121     noop?: boolean;
122     precat?: boolean;
123     dummy_title?: string;
124     dummy_author?: string;
125     dummy_isbn?: string;
126     circ_modifier?: string;
127     void_overdues?: boolean;
128     new_copy_alerts?: boolean;
129
130     // internal tracking
131     _override?: boolean;
132     _renewal?: boolean;
133     _checkbarcode?: boolean;
134     _worklog?: WorkLogEntry;
135 }
136
137 export interface CircResultCommon {
138     index: number;
139     params: CheckinParams | CheckoutParams;
140     firstEvent: EgEvent;
141     allEvents: EgEvent[];
142     success: boolean;
143     copy?: IdlObject;
144     volume?: IdlObject;
145     record?: IdlObject;
146     circ?: IdlObject;
147     parent_circ?: IdlObject;
148     hold?: IdlObject;
149
150     // Set to one of circ_patron or hold_patron depending on the context.
151     patron?: IdlObject;
152
153     // Set to the patron linked to the relevant circulation.
154     circ_patron?: IdlObject;
155
156     // Set to the patron linked to the relevant hold.
157     hold_patron?: IdlObject;
158
159     transit?: IdlObject;
160     copyAlerts?: IdlObject[];
161     mbts?: IdlObject;
162
163     routeTo?: string; // org name or in-branch destination
164
165     // Calculated values
166     title?: string;
167     author?: string;
168     isbn?: string;
169 }
170
171
172 export interface CheckoutResult extends CircResultCommon {
173     params: CheckoutParams;
174     canceled?: boolean;
175     nonCatCirc?: IdlObject;
176 }
177
178 export interface CheckinParams {
179     noop?: boolean;
180     copy_id?: number;
181     copy_barcode?: string;
182     claims_never_checked_out?: boolean;
183     void_overdues?: boolean;
184     auto_print_holds_transits?: boolean;
185     backdate?: string;
186     capture?: string;
187     next_copy_status?: number[];
188     new_copy_alerts?: boolean;
189     clear_expired?: boolean;
190     hold_as_transit?: boolean;
191     manual_float?: boolean;
192     do_inventory_update?: boolean;
193     no_precat_alert?: boolean;
194     retarget_mode?: string;
195
196     // internal / local values that are moved from the API request.
197     _override?: boolean;
198     _worklog?: WorkLogEntry;
199     _checkbarcode?: boolean;
200 }
201
202 export interface CheckinResult extends CircResultCommon {
203     params: CheckinParams;
204     destOrg?: IdlObject;
205     destAddress?: IdlObject;
206     destCourierCode?: string;
207 }
208
209 @Injectable()
210 export class CircService {
211     static resultIndex = 0;
212
213     components: CircComponentsComponent;
214     nonCatTypes: IdlObject[] = null;
215     autoOverrideCheckoutEvents: {[textcode: string]: boolean} = {};
216     suppressCheckinPopups = false;
217     ignoreCheckinPrecats = false;
218     copyLocationCache: {[id: number]: IdlObject} = {};
219     clearHoldsOnCheckout = false;
220     orgAddrCache: {[addrId: number]: IdlObject} = {};
221
222     constructor(
223         private audio: AudioService,
224         private evt: EventService,
225         private org: OrgService,
226         private net: NetService,
227         private pcrud: PcrudService,
228         private serverStore: ServerStoreService,
229         private strings: StringService,
230         private auth: AuthService,
231         private holdings: HoldingsService,
232         private worklog: WorkLogService,
233         private bib: BibRecordService
234     ) {}
235
236     applySettings(): Promise<any> {
237         return this.serverStore.getItemBatch([
238             'circ.clear_hold_on_checkout',
239         ]).then(sets => {
240             this.clearHoldsOnCheckout = sets['circ.clear_hold_on_checkout'];
241             return this.worklog.loadSettings();
242         });
243     }
244
245     // 'circ' is fleshed with copy, vol, bib, wide_display_entry
246     // Extracts some display info from a fleshed circ.
247     getDisplayInfo(circ: IdlObject): CircDisplayInfo {
248         return this.getCopyDisplayInfo(circ.target_copy());
249     }
250
251     getCopyDisplayInfo(copy: IdlObject): CircDisplayInfo {
252
253         if (copy.call_number() === -1 || copy.call_number().id() === -1) {
254             // Precat Copy
255             return {
256                 title: copy.dummy_title(),
257                 author: copy.dummy_author(),
258                 isbn: copy.dummy_isbn(),
259                 copy: copy
260             };
261         }
262
263         const volume = copy.call_number();
264         const record = volume.record();
265         const display = record.wide_display_entry();
266
267         let isbn = JSON.parse(display.isbn());
268         if (Array.isArray(isbn)) { isbn = isbn.join(','); }
269
270         return {
271             title: JSON.parse(display.title()),
272             author: JSON.parse(display.author()),
273             isbn: isbn,
274             copy: copy,
275             volume: volume,
276             record: record,
277             display: display
278         };
279     }
280
281     getOrgAddr(orgId: number, addrType): Promise<IdlObject> {
282         const org = this.org.get(orgId);
283         const addrId = this.org[addrType];
284
285         if (!addrId) { return Promise.resolve(null); }
286
287         if (this.orgAddrCache[addrId]) {
288             return Promise.resolve(this.orgAddrCache[addrId]);
289         }
290
291         return this.pcrud.retrieve('aoa', addrId).toPromise()
292         .then(addr => {
293             this.orgAddrCache[addrId] = addr;
294             return addr;
295         });
296     }
297
298     // find the open transit for the given copy barcode; flesh the org
299     // units locally.
300     // Sets result.transit
301     findCopyTransit(result: CircResultCommon): Promise<IdlObject> {
302         // NOTE: result.transit may exist, but it's not necessarily
303         // the transit we want, since a transit close + open in the API
304         // returns the closed transit.
305         return this.findCopyTransitById(result.copy.id())
306         .then(transit => {
307             result.transit = transit;
308             return transit;
309          });
310     }
311
312     findCopyTransitById(copyId: number): Promise<IdlObject> {
313         return this.pcrud.search('atc', {
314                 dest_recv_time : null,
315                 cancel_time : null,
316                 target_copy: copyId
317             }, {
318                 limit : 1,
319                 order_by : {atc : 'source_send_time desc'},
320             }, {authoritative : true}
321         ).toPromise().then(transit => {
322             if (transit) {
323                 transit.source(this.org.get(transit.source()));
324                 transit.dest(this.org.get(transit.dest()));
325                 return transit;
326             }
327
328             return Promise.reject('No transit found');
329         });
330     }
331
332     // Sets result.transit and result.copy
333     findCopyTransitByBarcode(result: CircResultCommon): Promise<IdlObject> {
334         // NOTE: result.transit may exist, but it's not necessarily
335         // the transit we want, since a transit close + open in the API
336         // returns the closed transit.
337
338          const barcode = result.params.copy_barcode;
339
340          return this.pcrud.search('atc', {
341                 dest_recv_time : null,
342                 cancel_time : null
343             }, {
344                 flesh : 1,
345                 flesh_fields : {atc : ['target_copy']},
346                 join : {
347                     acp : {
348                         filter : {
349                             barcode : barcode,
350                             deleted : 'f'
351                         }
352                     }
353                 },
354                 limit : 1,
355                 order_by : {atc : 'source_send_time desc'}
356             }, {authoritative : true}
357
358         ).toPromise().then(transit => {
359             if (transit) {
360                 transit.source(this.org.get(transit.source()));
361                 transit.dest(this.org.get(transit.dest()));
362                 result.transit = transit;
363                 result.copy = transit.target_copy();
364                 return transit;
365             }
366             return Promise.reject('No transit found');
367         });
368     }
369
370     getNonCatTypes(): Promise<IdlObject[]> {
371
372         if (this.nonCatTypes) {
373             return Promise.resolve(this.nonCatTypes);
374         }
375
376         return this.pcrud.search('cnct',
377             {owning_lib: this.org.fullPath(this.auth.user().ws_ou(), true)},
378             {order_by: {cnct: 'name'}},
379             {atomic: true}
380         ).toPromise().then(types => this.nonCatTypes = types);
381     }
382
383     // Remove internal tracking variables on Param objects so they are
384     // not sent to the server, which can result in autoload errors.
385     apiParams(
386         params: CheckoutParams | CheckinParams): CheckoutParams | CheckinParams {
387
388         const apiParams = Object.assign({}, params); // clone
389         const remove = Object.keys(apiParams).filter(k => k.match(/^_/));
390         remove.forEach(p => delete apiParams[p]);
391
392         // This modifier is not sent to the server.
393         // Should be _-prefixed, but we already have a workstation setting,
394         // etc. for this one.  Just manually remove it from the API params.
395         delete apiParams['auto_print_holds_transits'];
396
397         return apiParams;
398     }
399
400     checkout(params: CheckoutParams): Promise<CheckoutResult> {
401
402         params.new_copy_alerts = true;
403         params._renewal = false;
404         console.debug('checking out with', params);
405
406         let method = 'open-ils.circ.checkout.full';
407         if (params._override) { method += '.override'; }
408
409         return this.inspectBarcode(params).then(barcodeOk => {
410             if (!barcodeOk) { return null; }
411
412             return this.net.request(
413                 'open-ils.circ', method,
414                 this.auth.token(), this.apiParams(params)).toPromise()
415             .then(result => this.unpackCheckoutData(params, result))
416             .then(result => this.processCheckoutResult(result));
417         });
418     }
419
420     renew(params: CheckoutParams): Promise<CheckoutResult> {
421
422         params.new_copy_alerts = true;
423         params._renewal = true;
424         console.debug('renewing out with', params);
425
426         let method = 'open-ils.circ.renew';
427         if (params._override) { method += '.override'; }
428
429         return this.inspectBarcode(params).then(barcodeOk => {
430             if (!barcodeOk) { return null; }
431
432             return this.net.request(
433                 'open-ils.circ', method,
434                 this.auth.token(), this.apiParams(params)).toPromise()
435             .then(result => this.unpackCheckoutData(params, result))
436             .then(result => this.processCheckoutResult(result));
437         });
438     }
439
440
441     unpackCheckoutData(
442         params: CheckoutParams, response: any): Promise<CheckoutResult> {
443
444         const allEvents = Array.isArray(response) ?
445             response.map(r => this.evt.parse(r)) :
446             [this.evt.parse(response)];
447
448         console.debug('checkout events', allEvents.map(e => e.textcode));
449         console.debug('checkout returned', allEvents);
450
451         const firstEvent = allEvents[0];
452         const payload = firstEvent.payload;
453
454         const result: CheckoutResult = {
455             index: CircService.resultIndex++,
456             firstEvent: firstEvent,
457             allEvents: allEvents,
458             params: params,
459             success: false
460         };
461
462         // Some scenarios (e.g. copy in transit) have no payload,
463         // which is OK.
464         if (!payload) { return Promise.resolve(result); }
465
466         result.circ = payload.circ;
467         result.copy = payload.copy;
468         result.volume = payload.volume;
469         result.patron = payload.patron;
470         result.record = payload.record;
471         result.nonCatCirc = payload.noncat_circ;
472
473         return this.fleshCommonData(result).then(_ => {
474             const action = params._renewal ? 'renew' :
475                 (params.noncat ? 'noncat_checkout' : 'checkout');
476             this.addWorkLog(action, result);
477             return result;
478         });
479     }
480
481     processCheckoutResult(result: CheckoutResult): Promise<CheckoutResult> {
482         const renewing = result.params._renewal;
483         const key = renewing ? 'renew' : 'checkout';
484
485         const overridable = renewing ?
486             CAN_OVERRIDE_RENEW_EVENTS : CAN_OVERRIDE_CHECKOUT_EVENTS;
487
488         if (result.allEvents.filter(
489             e => overridable.includes(e.textcode)).length > 0) {
490             return this.handleOverridableCheckoutEvents(result);
491         }
492
493         switch (result.firstEvent.textcode) {
494             case 'SUCCESS':
495                 result.success = true;
496                 this.audio.play(`success.${key}`);
497                 return Promise.resolve(result);
498
499             case 'ITEM_NOT_CATALOGED':
500                 return this.handlePrecat(result);
501
502             case 'OPEN_CIRCULATION_EXISTS':
503                 return this.handleOpenCirc(result);
504
505             case 'COPY_IN_TRANSIT':
506                 this.audio.play(`warning.${key}.in_transit`);
507                 return this.copyInTransitDialog(result);
508
509             case 'PATRON_CARD_INACTIVE':
510             case 'PATRON_INACTIVE':
511             case 'PATRON_ACCOUNT_EXPIRED':
512             case 'CIRC_CLAIMS_RETURNED':
513             case 'ACTOR_USER_NOT_FOUND':
514             case 'AVAIL_HOLD_COPY_RATIO_EXCEEDED':
515                 this.audio.play(`warning.${key}`);
516                 return this.exitAlert({
517                     textcode: result.firstEvent.textcode,
518                     barcode: result.params.copy_barcode
519                 });
520
521             case 'ASSET_COPY_NOT_FOUND':
522                 this.audio.play(`error.${key}.not_found`);
523                 return this.exitAlert({
524                     textcode: result.firstEvent.textcode,
525                     barcode: result.params.copy_barcode
526                 });
527
528             default:
529                 this.audio.play(`error.${key}.unknown`);
530                 return this.exitAlert({
531                     textcode: 'CHECKOUT_FAILED_GENERIC',
532                     barcode: result.params.copy_barcode
533                 });
534         }
535     }
536
537     exitAlert(context: any): Promise<any> {
538         const key = 'staff.circ.events.' + context.textcode;
539         return this.strings.interpolate(key, context)
540         .then(str => {
541             this.components.circFailedDialog.dialogBody = str;
542             return this.components.circFailedDialog.open().toPromise();
543         })
544         .then(_ => Promise.reject('Bailling on event ' + context.textcode));
545     }
546
547     copyInTransitDialog(result: CheckoutResult): Promise<CheckoutResult> {
548         this.components.copyInTransitDialog.checkout = result;
549
550         return this.findCopyTransitByBarcode(result)
551         .then(_ => this.components.copyInTransitDialog.open().toPromise())
552         .then(cancelAndCheckout => {
553             if (cancelAndCheckout) {
554
555                 return this.abortTransit(result.transit.id())
556                 .then(_ => {
557                     // We had to look up the copy from the barcode since
558                     // it was not embedded in the result event.  Since
559                     // we have the specifics on the copy, go ahead and
560                     // copy them into the params we use for the follow
561                     // up checkout.
562                     result.params.copy_barcode = result.copy.barcode();
563                     result.params.copy_id = result.copy.id();
564                     return this.checkout(result.params);
565                 });
566
567             } else {
568                 return result;
569             }
570         });
571     }
572
573     // Ask the user if we should resolve the circulation and check
574     // out to the user or leave it alone.
575     // When resolving and checking out, renew if it's for the same
576     // user, otherwise check it in, then back out to the current user.
577     handleOpenCirc(result: CheckoutResult): Promise<CheckoutResult> {
578
579         let sameUser = false;
580
581         return this.net.request(
582             'open-ils.circ',
583             'open-ils.circ.copy_checkout_history.retrieve',
584             this.auth.token(), result.params.copy_id, 1).toPromise()
585
586         .then(circs => {
587             const circ = circs[0];
588
589             sameUser = result.params.patron_id === circ.usr();
590             this.components.openCircDialog.sameUser = sameUser;
591             this.components.openCircDialog.circDate = circ.xact_start();
592
593             return this.components.openCircDialog.open().toPromise();
594         })
595
596         .then(fromDialog => {
597
598             // Leave the open circ checked out.
599             if (!fromDialog) { return result; }
600
601             const coParams = Object.assign({}, result.params); // clone
602
603             if (sameUser) {
604                 coParams.void_overdues = fromDialog.forgiveFines;
605                 return this.renew(coParams);
606             }
607
608             const ciParams: CheckinParams = {
609                 noop: true,
610                 copy_id: coParams.copy_id,
611                 void_overdues: fromDialog.forgiveFines
612             };
613
614             return this.checkin(ciParams)
615             .then(res => {
616                 if (res.success) {
617                     return this.checkout(coParams);
618                 } else {
619                     return Promise.reject('Unable to check in item');
620                 }
621             });
622         });
623     }
624
625     handleOverridableCheckoutEvents(result: CheckoutResult): Promise<CheckoutResult> {
626         const params = result.params;
627         const firstEvent = result.firstEvent;
628         const events = result.allEvents;
629
630         if (params._override) {
631             // Should never get here.  Just being safe.
632             return Promise.reject(null);
633         }
634
635         if (events.filter(
636             e => !this.autoOverrideCheckoutEvents[e.textcode]).length === 0) {
637             // User has already seen all of these events and overridden them,
638             // so avoid showing them again since they are all auto-overridable.
639             params._override = true;
640             return params._renewal ? this.renew(params) : this.checkout(params);
641         }
642
643         // New-style alerts are reported via COPY_ALERT_MESSAGE and
644         // includes the alerts in the payload as an array.
645         if (firstEvent.textcode === 'COPY_ALERT_MESSAGE'
646             && Array.isArray(firstEvent.payload)) {
647             this.components.copyAlertManager.alerts = firstEvent.payload;
648
649             this.components.copyAlertManager.mode =
650                 params._renewal ? 'renew' : 'checkout';
651
652             return this.components.copyAlertManager.open().toPromise()
653             .then(resp => {
654                 if (resp) {
655                     params._override = true;
656                     return this.checkout(params);
657                 }
658             });
659         }
660
661         return this.showOverrideDialog(result, events);
662     }
663
664     showOverrideDialog(result: CheckoutResult,
665         events: EgEvent[], checkin?: boolean): Promise<CheckoutResult> {
666
667         const params = result.params;
668         const mode = checkin ? 'checkin' : (params._renewal ? 'renew' : 'checkout');
669
670         const holdShelfEvent = events.filter(e => e.textcode === 'ITEM_ON_HOLDS_SHELF')[0];
671
672         if (holdShelfEvent) {
673             this.components.circEventsDialog.clearHolds = this.clearHoldsOnCheckout;
674             this.components.circEventsDialog.patronId = holdShelfEvent.payload.patron_id;
675             this.components.circEventsDialog.patronName = holdShelfEvent.payload.patron_name;
676         }
677
678         this.components.circEventsDialog.copyBarcode = result.params.copy_barcode;
679         this.components.circEventsDialog.events = events;
680         this.components.circEventsDialog.mode = mode;
681
682         return this.components.circEventsDialog.open().toPromise()
683         .then(resp => {
684             const confirmed = resp.override;
685             if (!confirmed) { return null; }
686
687             let promise = Promise.resolve(null);
688
689             if (!checkin) {
690                 // Indicate these events have been seen and overridden.
691                 events.forEach(evt => {
692                     if (CHECKOUT_OVERRIDE_AFTER_FIRST.includes(evt.textcode)) {
693                         this.autoOverrideCheckoutEvents[evt.textcode] = true;
694                     }
695                 });
696
697                 if (holdShelfEvent && resp.clearHold) {
698                     const holdId = holdShelfEvent.payload.hold_id;
699
700                     // Cancel the hold that put our checkout item
701                     // on the holds shelf.
702
703                     promise = promise.then(_ => {
704                         return this.net.request(
705                             'open-ils.circ',
706                             'open-ils.circ.hold.cancel',
707                             this.auth.token(),
708                             holdId,
709                             5, // staff forced
710                             'Item checked out by other patron' // FIXME I18n
711                         ).toPromise();
712                     });
713                 }
714             }
715
716             return promise.then(_ => {
717                 params._override = true;
718                 return this[mode](params); // checkout/renew/checkin
719             });
720         });
721     }
722
723     handlePrecat(result: CheckoutResult): Promise<CheckoutResult> {
724         this.components.precatDialog.barcode = result.params.copy_barcode;
725
726         return this.components.precatDialog.open().toPromise().then(values => {
727
728             if (values && values.dummy_title) {
729                 const params = result.params;
730                 params.precat = true;
731                 Object.keys(values).forEach(key => params[key] = values[key]);
732                 return this.checkout(params);
733             }
734
735             result.canceled = true;
736             return Promise.resolve(result);
737         });
738     }
739
740     checkin(params: CheckinParams): Promise<CheckinResult> {
741         params.new_copy_alerts = true;
742
743         console.debug('checking in with', params);
744
745         let method = 'open-ils.circ.checkin';
746         if (params._override) { method += '.override'; }
747
748         return this.inspectBarcode(params).then(barcodeOk => {
749             if (!barcodeOk) { return null; }
750
751             return this.net.request(
752                 'open-ils.circ', method,
753                 this.auth.token(), this.apiParams(params)).toPromise()
754             .then(result => this.unpackCheckinData(params, result))
755             .then(result => this.processCheckinResult(result));
756         });
757     }
758
759     fetchPatron(userId: number): Promise<IdlObject> {
760         return this.pcrud.retrieve('au', userId, {
761             flesh: 1,
762             flesh_fields : {'au' : ['card', 'stat_cat_entries']}
763         })
764         .toPromise();
765     }
766
767     fleshCommonData(result: CircResultCommon): Promise<CircResultCommon> {
768
769         console.warn('fleshCommonData()');
770
771         const copy = result.copy;
772         const volume = result.volume;
773         const circ = result.circ;
774         const hold = result.hold;
775         const nonCatCirc = (result as CheckoutResult).nonCatCirc;
776
777         let promise: Promise<any> = Promise.resolve();
778
779         if (hold) {
780             console.debug('fleshCommonData() hold ', hold.usr());
781             promise = promise.then(_ => {
782                 return this.fetchPatron(hold.usr())
783                 .then(usr => {
784                     result.hold_patron = usr;
785                     console.debug('Setting hold patron to ' + usr.id());
786                 });
787             });
788         }
789
790         const circPatronId = circ ? circ.usr() :
791             (nonCatCirc ? nonCatCirc.patron() : null);
792
793         if (circPatronId) {
794             console.debug('fleshCommonData() circ ', circPatronId);
795             promise = promise.then(_ => {
796                 return this.fetchPatron(circPatronId)
797                 .then(usr => {
798                     result.circ_patron = usr;
799                     console.debug('Setting circ patron to ' + usr.id());
800                 });
801             });
802         }
803
804         // Set a default patron value which is used in most cases.
805         promise = promise.then(_ => {
806             result.patron = result.hold_patron || result.circ_patron;
807         });
808
809         if (result.record) {
810             result.title = result.record.title();
811             result.author = result.record.author();
812             result.isbn = result.record.isbn();
813
814         } else if (copy) {
815             result.title = result.copy.dummy_title();
816             result.author = result.copy.dummy_author();
817             result.isbn = result.copy.dummy_isbn();
818         }
819
820         if (copy) {
821             if (this.copyLocationCache[copy.location()]) {
822                 copy.location(this.copyLocationCache[copy.location()]);
823             } else {
824                 promise = this.pcrud.retrieve('acpl', copy.location()).toPromise()
825                 .then(loc => {
826                     copy.location(loc);
827                     this.copyLocationCache[loc.id()] = loc;
828                 });
829             }
830
831             if (typeof copy.status() !== 'object') {
832                 promise = promise.then(_ => this.holdings.getCopyStatuses())
833                 .then(stats => {
834                     const stat =
835                         Object.values(stats).filter(s => s.id() === copy.status())[0];
836                     if (stat) { copy.status(stat); }
837                 });
838             }
839         }
840
841         promise = promise.then(_ => {
842             // By default, all items route-to their location.
843             // Value replaced later on as needed.
844             if (copy && typeof copy.location() === 'object') {
845                 result.routeTo = copy.location().name();
846             }
847         });
848
849         if (volume) {
850             // Flesh volume prefixes and suffixes
851
852             if (typeof volume.prefix() !== 'object') {
853                 promise = promise.then(_ =>
854                     this.pcrud.retrieve('acnp', volume.prefix()).toPromise()
855                 ).then(p => volume.prefix(p));
856             }
857
858             if (typeof volume.suffix() !== 'object') {
859                 promise = promise.then(_ =>
860                     this.pcrud.retrieve('acns', volume.suffix()).toPromise()
861                 ).then(p => volume.suffix(p));
862             }
863         }
864
865         return promise.then(_ => result);
866     }
867
868     unpackCheckinData(params: CheckinParams, response: any): Promise<CheckinResult> {
869         const allEvents = Array.isArray(response) ?
870             response.map(r => this.evt.parse(r)) : [this.evt.parse(response)];
871
872         console.debug('checkin events', allEvents.map(e => e.textcode));
873         console.debug('checkin response', response);
874
875         const firstEvent = allEvents[0];
876         const payload = firstEvent.payload;
877
878         const success =
879             firstEvent.textcode.match(/SUCCESS|NO_CHANGE|ROUTE_ITEM/) !== null;
880
881         const result: CheckinResult = {
882             index: CircService.resultIndex++,
883             firstEvent: firstEvent,
884             allEvents: allEvents,
885             params: params,
886             success: success,
887         };
888
889         if (!payload) {
890             // e.g. ASSET_COPY_NOT_FOUND
891             return Promise.resolve(result);
892         }
893
894         result.circ = payload.circ;
895         result.parent_circ = payload.parent_circ;
896         result.copy = payload.copy;
897         result.volume = payload.volume;
898         result.record = payload.record;
899         result.transit = payload.transit;
900         result.hold = payload.hold;
901
902         const copy = result.copy;
903         const volume = result.volume;
904         const transit = result.transit;
905         const circ = result.circ;
906         const parent_circ = result.parent_circ;
907
908         if (transit) {
909             if (typeof transit.dest() !== 'object') {
910                 transit.dest(this.org.get(transit.dest()));
911             }
912             if (typeof transit.source() !== 'object') {
913                 transit.source(this.org.get(transit.source()));
914             }
915         }
916
917         // for checkin, the mbts lives on the main circ
918         if (circ && circ.billable_transaction()) {
919             result.mbts = circ.billable_transaction().summary();
920         }
921
922         // on renewals, the mbts lives on the parent circ
923         if (parent_circ && parent_circ.billable_transaction()) {
924             result.mbts = parent_circ.billable_transaction().summary();
925         }
926
927         return this.fleshCommonData(result).then(_ => {
928             this.addWorkLog('checkin', result);
929             return result;
930         });
931     }
932
933     processCheckinResult(result: CheckinResult): Promise<CheckinResult> {
934         const params = result.params;
935         const allEvents = result.allEvents;
936
937         // Informational alerts that can be ignored if configured.
938         if (this.suppressCheckinPopups &&
939             allEvents.filter(e =>
940                 !CAN_SUPPRESS_CHECKIN_ALERTS.includes(e.textcode)).length === 0) {
941
942             // Should not be necessary, but good to be safe.
943             if (params._override) { return Promise.resolve(null); }
944
945             params._override = true;
946             return this.checkin(params);
947         }
948
949         // Alerts that require a manual override.
950         if (allEvents.filter(
951             e => CAN_OVERRIDE_CHECKIN_ALERTS.includes(e.textcode)).length > 0) {
952             return this.handleOverridableCheckinEvents(result);
953         }
954
955         switch (result.firstEvent.textcode) {
956             case 'SUCCESS':
957             case 'NO_CHANGE':
958                 return this.handleCheckinSuccess(result);
959
960             case 'ITEM_NOT_CATALOGED':
961                 this.audio.play('error.checkout.no_cataloged');
962                 result.routeTo = this.components.catalogingStr.text;
963                 return this.showPrecatAlert().then(_ => result);
964
965             case 'ROUTE_ITEM':
966                 this.audio.play(result.hold ?
967                     'info.checkin.transit.hold' : 'info.checkin.transit');
968
969                 if (params.noop) {
970                     console.debug('Skipping route dialog on "noop" checkin');
971                     return Promise.resolve(result);
972                 }
973
974                 this.components.routeDialog.checkin = result;
975                 return this.findCopyTransit(result)
976                 .then(_ => this.components.routeDialog.open().toPromise())
977                 .then(_ => result);
978
979             case 'ASSET_COPY_NOT_FOUND':
980                 this.audio.play('error.checkin.not_found');
981                 return this.handleCheckinUncatAlert(result);
982
983             default:
984                 this.audio.play('error.checkin.unknown');
985                 console.warn(
986                     'Unhandled checkin response : ' + result.firstEvent.textcode);
987         }
988
989         return Promise.resolve(result);
990     }
991
992     addWorkLog(action: string, result: CircResultCommon) {
993         const params = result.params;
994         const copy = result.copy;
995         const patron = result.patron;
996
997         // Some worklog data may be provided by the caller in the params.
998         const entry: WorkLogEntry =
999             Object.assign(params._worklog || {}, {action: action});
1000
1001         if (copy) {
1002             entry.item = copy.barcode();
1003             entry.item_id = copy.id();
1004         } else {
1005             entry.item = params.copy_barcode;
1006             entry.item_id = params.copy_id;
1007         }
1008
1009         if (patron) {
1010             entry.patron_id = patron.id();
1011             entry.user = patron.family_name();
1012         }
1013
1014         if (result.hold) {
1015             entry.hold_id = result.hold.id();
1016         }
1017
1018         this.worklog.record(entry);
1019     }
1020
1021     showPrecatAlert(): Promise<any> {
1022         if (!this.suppressCheckinPopups && !this.ignoreCheckinPrecats) {
1023             // Tell the user its a precat and return the result.
1024             return this.components.routeToCatalogingDialog.open()
1025             .toPromise();
1026         }
1027         return Promise.resolve(null);
1028     }
1029
1030     handleCheckinSuccess(result: CheckinResult): Promise<CheckinResult> {
1031         const copy = result.copy;
1032
1033         if (!copy) { return Promise.resolve(result); }
1034
1035         const stat = copy.status();
1036         const statId = typeof stat === 'object' ? stat.id() : stat;
1037
1038         switch (statId) {
1039
1040             case 0: /* AVAILABLE */
1041             case 4: /* MISSING */
1042             case 7: /* RESHELVING */
1043                 this.audio.play('success.checkin');
1044                 return this.handleCheckinLocAlert(result);
1045
1046             case 8: /* ON HOLDS SHELF */
1047                 this.audio.play('info.checkin.holds_shelf');
1048
1049                 const hold = result.hold;
1050
1051                 if (hold) {
1052
1053                     if (Number(hold.pickup_lib()) === Number(this.auth.user().ws_ou())) {
1054                         result.routeTo = this.components.holdShelfStr.text;
1055                         this.components.routeDialog.checkin = result;
1056                         return this.components.routeDialog.open().toPromise()
1057                         .then(_ => result);
1058
1059                     } else {
1060                         // Should not happen in practice, but to be safe.
1061                         this.audio.play('warning.checkin.wrong_shelf');
1062                     }
1063
1064                 } else {
1065                     console.warn('API Returned insufficient info on holds');
1066                 }
1067                 break;
1068
1069             case 11: /* CATALOGING */
1070                 this.audio.play('info.checkin.cataloging');
1071                 result.routeTo = this.components.catalogingStr.text;
1072                 return this.showPrecatAlert().then(_ => result);
1073
1074             case 15: /* ON_RESERVATION_SHELF */
1075                 this.audio.play('info.checkin.reservation');
1076                 break;
1077
1078             default:
1079                 this.audio.play('success.checkin');
1080                 console.debug(`Unusual checkin copy status (may have been
1081                     set via copy alert): status=${statId}`);
1082         }
1083
1084         return Promise.resolve(result);
1085     }
1086
1087     handleCheckinLocAlert(result: CheckinResult): Promise<CheckinResult> {
1088         const copy = result.copy;
1089
1090         if (this.suppressCheckinPopups
1091             || copy.location().checkin_alert() === 'f') {
1092             return Promise.resolve(result);
1093         }
1094
1095         return this.strings.interpolate(
1096             'staff.circ.checkin.location.alert',
1097             {barcode: copy.barcode(), location: copy.location().name()}
1098         ).then(str => {
1099             this.components.locationAlertDialog.dialogBody = str;
1100             return this.components.locationAlertDialog.open().toPromise()
1101             .then(_ => result);
1102         });
1103     }
1104
1105     handleCheckinUncatAlert(result: CheckinResult): Promise<CheckinResult> {
1106         const barcode = result.copy ?
1107             result.copy.barcode() : result.params.copy_barcode;
1108
1109         if (this.suppressCheckinPopups) {
1110             return Promise.resolve(result);
1111         }
1112
1113         return this.strings.interpolate(
1114             'staff.circ.checkin.uncat.alert', {barcode: barcode}
1115         ).then(str => {
1116             this.components.uncatAlertDialog.dialogBody = str;
1117             return this.components.uncatAlertDialog.open().toPromise()
1118             .then(_ => result);
1119         });
1120     }
1121
1122
1123     handleOverridableCheckinEvents(result: CheckinResult): Promise<CheckinResult> {
1124         const params = result.params;
1125         const events = result.allEvents;
1126         const firstEvent = result.firstEvent;
1127
1128         if (params._override) {
1129             // Should never get here.  Just being safe.
1130             return Promise.reject(null);
1131         }
1132
1133         if (this.suppressCheckinPopups && events.filter(
1134             e => !CAN_SUPPRESS_CHECKIN_ALERTS.includes(e.textcode)).length === 0) {
1135             // These events are automatically overridden when suppress
1136             // popups are in effect.
1137             params._override = true;
1138             return this.checkin(params);
1139         }
1140
1141         // New-style alerts are reported via COPY_ALERT_MESSAGE and
1142         // includes the alerts in the payload as an array.
1143         if (firstEvent.textcode === 'COPY_ALERT_MESSAGE'
1144             && Array.isArray(firstEvent.payload)) {
1145             this.components.copyAlertManager.alerts = firstEvent.payload;
1146             this.components.copyAlertManager.mode = 'checkin';
1147
1148             return this.components.copyAlertManager.open().toPromise()
1149             .then(resp => {
1150
1151                 if (!resp) { return result; } // dialog was canceled
1152
1153                 if (resp.nextStatus !== null) {
1154                     params.next_copy_status = [resp.nextStatus];
1155                     params.capture = 'nocapture';
1156                 }
1157
1158                 params._override = true;
1159
1160                 return this.checkin(params);
1161             });
1162         }
1163
1164         return this.showOverrideDialog(result, events, true);
1165     }
1166
1167
1168     // The provided params (minus the copy_id) will be used
1169     // for all items.
1170     checkoutBatch(copyIds: number[],
1171         params: CheckoutParams): Observable<CheckoutResult> {
1172
1173         if (copyIds.length === 0) { return empty(); }
1174
1175         return from(copyIds).pipe(concatMap(id => {
1176             const cparams = Object.assign({}, params); // clone
1177             cparams.copy_id = id;
1178             return from(this.checkout(cparams));
1179         }));
1180     }
1181
1182     // The provided params (minus the copy_id) will be used
1183     // for all items.
1184     renewBatch(copyIds: number[],
1185         params?: CheckoutParams): Observable<CheckoutResult> {
1186
1187         if (copyIds.length === 0) { return empty(); }
1188         if (!params) { params = {}; }
1189
1190         return from(copyIds).pipe(concatMap(id => {
1191             const cparams = Object.assign({}, params); // clone
1192             cparams.copy_id = id;
1193             return from(this.renew(cparams));
1194         }));
1195     }
1196
1197     // The provided params (minus the copy_id) will be used
1198     // for all items.
1199     checkinBatch(copyIds: number[],
1200         params?: CheckinParams): Observable<CheckinResult> {
1201
1202         if (copyIds.length === 0) { return empty(); }
1203         if (!params) { params = {}; }
1204
1205         return from(copyIds).pipe(concatMap(id => {
1206             const cparams = Object.assign({}, params); // clone
1207             cparams.copy_id = id;
1208             return from(this.checkin(cparams));
1209         }));
1210     }
1211
1212     abortTransit(transitId: number): Promise<any> {
1213         return this.net.request(
1214             'open-ils.circ',
1215             'open-ils.circ.transit.abort',
1216             this.auth.token(), {transitid : transitId}
1217         ).toPromise().then(resp => {
1218             const evt = this.evt.parse(resp);
1219             if (evt) {
1220                 alert(evt);
1221                 return Promise.reject(evt.toString());
1222             }
1223             return Promise.resolve();
1224         });
1225     }
1226
1227     lastCopyCirc(copyId: number): Promise<IdlObject> {
1228         return this.pcrud.search('circ',
1229             {target_copy : copyId},
1230             {order_by : {circ : 'xact_start desc' }, limit : 1}
1231         ).toPromise();
1232     }
1233
1234     // Resolves to true if the barcode is OK or the user confirmed it or
1235     // the user doesn't care to begin with
1236     inspectBarcode(params: CheckoutParams | CheckinParams): Promise<boolean> {
1237         if (!params._checkbarcode || !params.copy_barcode) {
1238             return Promise.resolve(true);
1239         }
1240
1241         if (this.checkBarcode(params.copy_barcode)) {
1242             // Avoid prompting again on an override
1243             params._checkbarcode = false;
1244             return Promise.resolve(true);
1245         }
1246
1247         this.components.badBarcodeDialog.barcode = params.copy_barcode;
1248         return this.components.badBarcodeDialog.open().toPromise()
1249         // Avoid prompting again on an override
1250         .then(response => {
1251             params._checkbarcode = false
1252             return response;
1253         });
1254     }
1255
1256     checkBarcode(barcode: string): boolean {
1257         if (barcode !== Number(barcode).toString()) { return false; }
1258
1259         const bc = barcode.toString();
1260
1261         // "16.00" == Number("16.00"), but the . is bad.
1262         // Throw out any barcode that isn't just digits
1263         if (bc.search(/\D/) !== -1) { return false; }
1264
1265         const lastDigit = bc.substr(bc.length - 1);
1266         const strippedBarcode = bc.substr(0, bc.length - 1);
1267         return this.barcodeCheckdigit(strippedBarcode).toString() === lastDigit;
1268     }
1269
1270     barcodeCheckdigit(bc: string): number {
1271         let checkSum = 0;
1272         let multiplier = 2;
1273         const reverseBarcode = bc.toString().split('').reverse();
1274
1275         reverseBarcode.forEach(ch => {
1276             let tempSum = 0;
1277             const product = (Number(ch) * multiplier) + '';
1278             product.split('').forEach(num => tempSum += Number(num));
1279             checkSum += Number(tempSum);
1280             multiplier = multiplier === 2 ? 1 : 2;
1281         });
1282
1283         const cSumStr = checkSum.toString();
1284         const nextMultipleOf10 =
1285             (Number(cSumStr.match(/(\d*)\d$/)[1]) * 10) + 10;
1286
1287         let checkDigit = nextMultipleOf10 - Number(cSumStr);
1288         if (checkDigit === 10) { checkDigit = 0; }
1289
1290         return checkDigit;
1291     }
1292 }
1293