]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/services/circ.js
724ae7fee6c339f18306cd4f54abf3de66a4b534
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / services / circ.js
1 /**
2  * Checkin, checkout, and renew
3  */
4
5 angular.module('egCoreMod')
6
7 .factory('egCirc',
8
9        ['$uibModal','$q','egCore','egAlertDialog','egConfirmDialog','egAddCopyAlertDialog','egCopyAlertManagerDialog','egCopyAlertEditorDialog',
10         'egWorkLog',
11 function($uibModal , $q , egCore , egAlertDialog , egConfirmDialog,  egAddCopyAlertDialog , egCopyAlertManagerDialog,  egCopyAlertEditorDialog ,
12          egWorkLog) {
13
14     var service = {
15         // auto-override these events after the first override
16         auto_override_checkout_events : {},
17         require_initials : false,
18         never_auto_print : {
19             hold_shelf_slip : false,
20             hold_transit_slip : false,
21             transit_slip : false
22         },
23         in_flight_checkins: {}
24     };
25
26     egCore.startup.go().finally(function() {
27         egCore.org.settings([
28             'ui.staff.require_initials.patron_standing_penalty',
29             'ui.admin.work_log.max_entries',
30             'ui.admin.patron_log.max_entries',
31             'circ.staff_client.do_not_auto_attempt_print',
32             'circ.clear_hold_on_checkout'
33         ]).then(function(set) {
34             service.require_initials = Boolean(set['ui.staff.require_initials.patron_standing_penalty']);
35             service.clearHold = Boolean(set['circ.clear_hold_on_checkout']);
36
37             if (angular.isArray(set['circ.staff_client.do_not_auto_attempt_print'])) {
38                 if (set['circ.staff_client.do_not_auto_attempt_print'].indexOf('Hold Slip') > 1)
39                     service.never_auto_print['hold_shelf_slip'] = true;
40                 if (set['circ.staff_client.do_not_auto_attempt_print'].indexOf('Hold/Transit Slip') > 1)
41                     service.never_auto_print['hold_transit_slip'] = true;
42                 if (set['circ.staff_client.do_not_auto_attempt_print'].indexOf('Transit Slip') > 1)
43                     service.never_auto_print['transit_slip'] = true;
44             }
45         });
46     });
47
48     service.reset = function() {
49         service.auto_override_checkout_events = {};
50     }
51
52     // these events can be overridden by staff during checkout
53     service.checkout_overridable_events = [
54         'PATRON_EXCEEDS_OVERDUE_COUNT',
55         'PATRON_EXCEEDS_CHECKOUT_COUNT',
56         'PATRON_EXCEEDS_FINES',
57         'PATRON_BARRED',
58         'CIRC_EXCEEDS_COPY_RANGE',
59         'ITEM_DEPOSIT_REQUIRED',
60         'ITEM_RENTAL_FEE_REQUIRED',
61         'PATRON_EXCEEDS_LOST_COUNT',
62         'COPY_CIRC_NOT_ALLOWED',
63         'COPY_NOT_AVAILABLE',
64         'COPY_IS_REFERENCE',
65         'COPY_ALERT_MESSAGE',
66         'ITEM_ON_HOLDS_SHELF',
67         'STAFF_C',
68         'STAFF_CH',
69         'STAFF_CHR',
70         'STAFF_CR',
71         'STAFF_H',
72         'STAFF_HR',
73         'STAFF_R'
74     ]
75
76     // after the first override of any of these events, 
77     // auto-override them in subsequent calls.
78     service.checkout_auto_override_after_first = [
79         'PATRON_EXCEEDS_OVERDUE_COUNT',
80         'PATRON_BARRED',
81         'PATRON_EXCEEDS_LOST_COUNT',
82         'PATRON_EXCEEDS_CHECKOUT_COUNT',
83         'PATRON_EXCEEDS_FINES'
84     ]
85
86
87     // overridable during renewal
88     service.renew_overridable_events = [
89         'PATRON_EXCEEDS_OVERDUE_COUNT',
90         'PATRON_EXCEEDS_LOST_COUNT',
91         'PATRON_EXCEEDS_CHECKOUT_COUNT',
92         'PATRON_EXCEEDS_FINES',
93         'CIRC_EXCEEDS_COPY_RANGE',
94         'ITEM_DEPOSIT_REQUIRED',
95         'ITEM_RENTAL_FEE_REQUIRED',
96         'ITEM_DEPOSIT_PAID',
97         'COPY_CIRC_NOT_ALLOWED',
98         'COPY_IS_REFERENCE',
99         'COPY_ALERT_MESSAGE',
100         'COPY_NEEDED_FOR_HOLD',
101         'MAX_RENEWALS_REACHED',
102         'CIRC_CLAIMS_RETURNED',
103         'STAFF_C',
104         'STAFF_CH',
105         'STAFF_CHR',
106         'STAFF_CR',
107         'STAFF_H',
108         'STAFF_HR',
109         'STAFF_R'
110     ];
111
112     // these checkin events do not produce alerts when 
113     // options.suppress_alerts is in effect.
114     service.checkin_suppress_overrides = [
115         'COPY_BAD_STATUS',
116         'PATRON_BARRED',
117         'PATRON_INACTIVE',
118         'PATRON_ACCOUNT_EXPIRED',
119         'ITEM_DEPOSIT_PAID',
120         'CIRC_CLAIMS_RETURNED',
121         'COPY_ALERT_MESSAGE',
122         'COPY_STATUS_LOST',
123         'COPY_STATUS_LOST_AND_PAID',
124         'COPY_STATUS_LONG_OVERDUE',
125         'COPY_STATUS_MISSING',
126         'PATRON_EXCEEDS_FINES'
127     ]
128
129     // these events can be overridden by staff during checkin
130     service.checkin_overridable_events = 
131         service.checkin_suppress_overrides.concat([
132         'HOLD_CAPTURE_DELAYED', // not technically overridable, but special prompt and param
133         'TRANSIT_CHECKIN_INTERVAL_BLOCK'
134     ])
135
136     // Performs a checkout.
137     // Returns a promise resolved with the original params and options
138     // and the final checkout event (e.g. in the case of override).
139     // Rejected if the checkout cannot be completed.
140     //
141     // params : passed directly as arguments to the server API 
142     // options : non-parameter controls.  e.g. "override", "check_barcode"
143     service.checkout = function(params, options) {
144         if (!options) options = {};
145         params.new_copy_alerts = 1;
146
147         console.debug('egCirc.checkout() : ' 
148             + js2JSON(params) + ' : ' + js2JSON(options));
149
150         // handle barcode completion
151         return service.handle_barcode_completion(params.copy_barcode)
152         .then(function(barcode) {
153             console.debug('barcode after completion: ' + barcode);
154             params.copy_barcode = barcode;
155
156             var promise = options.check_barcode ? 
157                 service.test_barcode(params.copy_barcode) : $q.when();
158
159             // avoid re-check on override, etc.
160             delete options.check_barcode;
161
162             return promise.then(function() {
163
164                 var method = 'open-ils.circ.checkout.full';
165                 if (options.override) method += '.override';
166
167                 return egCore.net.request(
168                     'open-ils.circ', method, egCore.auth.token(), params
169
170                 ).then(function(evt) {
171
172                     if (!angular.isArray(evt)) evt = [evt];
173
174                     if (evt[0].payload && evt[0].payload.auto_renew == 1) {
175                         // open circulation found with auto-renew toggle on.
176                         console.debug('Auto-renewing item ' + params.copy_barcode);
177                         options.auto_renew = true;
178                         return service.renew(params, options);
179                     }
180
181                     var action = params.noncat ? 'noncat_checkout' : 'checkout';
182
183                     return service.flesh_response_data(action, evt, params, options)
184                     .then(function() {
185                         return service.handle_checkout_resp(evt, params, options);
186                     })
187                     .then(function(final_resp) {
188                         return service.munge_resp_data(final_resp,action,method)
189                     })
190                 });
191             });
192         });
193     }
194
195     // Performs a renewal.
196     // Returns a promise resolved with the original params and options
197     // and the final checkout event (e.g. in the case of override)
198     // Rejected if the renewal cannot be completed.
199     service.renew = function(params, options) {
200         if (!options) options = {};
201         params.new_copy_alerts = 1;
202
203         console.debug('egCirc.renew() : ' 
204             + js2JSON(params) + ' : ' + js2JSON(options));
205
206         // handle barcode completion
207         return service.handle_barcode_completion(params.copy_barcode)
208         .then(function(barcode) {
209             params.copy_barcode = barcode;
210
211             var promise = options.check_barcode ? 
212                 service.test_barcode(params.copy_barcode) : $q.when();
213
214             // avoid re-check on override, etc.
215             delete options.check_barcode;
216
217             return promise.then(function() {
218
219                 var method = 'open-ils.circ.renew';
220                 if (options.override) method += '.override';
221
222                 return egCore.net.request(
223                     'open-ils.circ', method, egCore.auth.token(), params
224
225                 ).then(function(evt) {
226
227                     if (!angular.isArray(evt)) evt = [evt];
228
229                     return service.flesh_response_data(
230                         'renew', evt, params, options)
231                     .then(function() {
232                         return service.handle_renew_resp(evt, params, options);
233                     })
234                     .then(function(final_resp) {
235                         final_resp.auto_renew = options.auto_renew;
236                         return service.munge_resp_data(final_resp,'renew',method)
237                     })
238                 });
239             });
240         });
241     }
242
243     // Performs a checkin
244     // Returns a promise resolved with the original params and options,
245     // plus the final checkin event (e.g. in the case of override).
246     // Rejected if the checkin cannot be completed.
247     service.checkin = function(params, options) {
248         if (!options) options = {};
249         params.new_copy_alerts = 1;
250
251         console.debug('egCirc.checkin() : ' 
252             + js2JSON(params) + ' : ' + js2JSON(options));
253
254         // handle barcode completion
255         return service.handle_barcode_completion(params.copy_barcode)
256         .then(function(barcode) {
257             params.copy_barcode = barcode;
258
259             var promise = options.check_barcode ? 
260                 service.test_barcode(params.copy_barcode) : $q.when();
261
262             // avoid re-check on override, etc.
263             delete options.check_barcode;
264
265             return promise.then(function() {
266
267                 var method = 'open-ils.circ.checkin';
268                 if (options.override) method += '.override';
269
270                 // Multiple checkin API calls should never be active
271                 // for a single barcode.
272                 if (service.in_flight_checkins[barcode]) {
273                     console.error('Barcode ' + barcode 
274                         + ' is already in flight for checkin, skipping');
275                     return $q.reject();
276                 }
277                 service.in_flight_checkins[barcode] = true;
278
279                 return egCore.net.request(
280                     'open-ils.circ', method, egCore.auth.token(), params
281
282                 ).then(function(evt) {
283                     delete service.in_flight_checkins[barcode];
284
285                     if (!angular.isArray(evt)) evt = [evt];
286                     return service.flesh_response_data(
287                         'checkin', evt, params, options)
288                     .then(function() {
289                         return service.handle_checkin_resp(evt, params, options);
290                     })
291                     .then(function(final_resp) {
292                         return service.munge_resp_data(final_resp,'checkin',method)
293                     })
294                 }, function() {delete service.in_flight_checkins[barcode]});
295             });
296         });
297     }
298
299     // provide consistent formatting of the final response data
300     service.munge_resp_data = function(final_resp,worklog_action,worklog_method) {
301         var data = final_resp.data = {};
302
303         if (!final_resp.evt[0]) {
304             egCore.audio.play('error.unknown.no_event');
305             return;
306         }
307
308         var payload = final_resp.evt[0].payload;
309         if (!payload) {
310             egCore.audio.play('error.unknown.no_payload');
311             return;
312         }
313
314         // retrieve call number affixes prior to sending payload data to the grid
315         if (payload.volume && typeof payload.volume.prefix() != 'object') {
316             egCore.pcrud.retrieve('acnp',payload.volume.prefix()).then(function(p) {payload.volume.prefix(p)});
317         };
318         if (payload.volume && typeof payload.volume.suffix() != 'object') {
319             egCore.pcrud.retrieve('acns',payload.volume.suffix()).then(function(s) {payload.volume.suffix(s)});
320         };
321
322         data.circ = payload.circ;
323         data.parent_circ = payload.parent_circ;
324         data.hold = payload.hold;
325         data.record = payload.record;
326         data.acp = payload.copy;
327         data.acn = payload.volume ?  payload.volume : payload.copy ? payload.copy.call_number() : null;
328         data.alci = egCore.idl.toHash(payload.latest_inventory, true);
329         data.au = payload.patron;
330         data.transit = payload.transit;
331         data.status = payload.status;
332         data.message = payload.message;
333         data.title = final_resp.evt[0].title;
334         data.author = final_resp.evt[0].author;
335         data.isbn = final_resp.evt[0].isbn;
336         data.route_to = final_resp.evt[0].route_to;
337
338
339         if (payload.circ) data.duration = payload.circ.duration();
340         if (payload.circ) data.circ_lib = payload.circ.circ_lib();
341         if (payload.do_inventory_update) {
342             if (payload.latest_inventory.id()) {
343                 egCore.pcrud.update(payload.latest_inventory);
344             } else {
345                 egCore.pcrud.create(payload.latest_inventory);
346             }
347         }
348
349         // for checkin, the mbts lives on the main circ
350         if (payload.circ && payload.circ.billable_transaction())
351             data.mbts = payload.circ.billable_transaction().summary();
352
353         // on renewals, the mbts lives on the parent circ
354         if (payload.parent_circ && payload.parent_circ.billable_transaction())
355             data.mbts = payload.parent_circ.billable_transaction().summary();
356
357         if (!data.route_to) {
358             if (data.transit) {
359                 data.route_to = data.transit.dest().shortname();
360             } else if (data.acp) {
361                 data.route_to = data.acp.location().name();
362             }
363         }
364
365         egWorkLog.record(
366             (worklog_action == 'checkout' || worklog_action == 'noncat_checkout')
367             ? egCore.strings.EG_WORK_LOG_CHECKOUT
368             : (worklog_action == 'renew'
369                 ? egCore.strings.EG_WORK_LOG_RENEW
370                 : egCore.strings.EG_WORK_LOG_CHECKIN // worklog_action == 'checkin'
371             ),{
372                 'action' : worklog_action,
373                 'method' : worklog_method,
374                 'response' : final_resp
375             }
376         );
377
378         return final_resp;
379     }
380
381     service.handle_overridable_checkout_event = function(evt, params, options) {
382
383         if (options.override) {
384             // override attempt already made and failed.
385             // NOTE: I don't think we'll ever get here, since the
386             // override attempt should produce a perm failure...
387             angular.forEach(evt, function(e){ console.debug('override failed: ' + e.textcode); });
388             return $q.reject();
389
390         } 
391
392         if (evt.filter(function(e){return !service.auto_override_checkout_events[e.textcode];}).length == 0) {
393             // user has already opted to override these type
394             // of events.  Re-run the checkout w/ override.
395             options.override = true;
396             return service.checkout(params, options);
397         } 
398
399         // Ask the user if they would like to override this event.
400         // Some events offer a stock override dialog, while others
401         // require additional context.
402
403         switch(evt[0].textcode) {
404             case 'COPY_NOT_AVAILABLE':
405                 return service.copy_not_avail_dialog(evt, params, options);
406             case 'COPY_ALERT_MESSAGE':
407                 return service.copy_alert_dialog(evt[0], params, options, 'checkout');
408             default: 
409                 return service.override_dialog(evt, params, options, 'checkout');
410         }
411     }
412
413     service.handle_overridable_renew_event = function(evt, params, options) {
414
415         if (options.override) {
416             // override attempt already made and failed.
417             // NOTE: I don't think we'll ever get here, since the
418             // override attempt should produce a perm failure...
419             angular.forEach(evt, function(e){ console.debug('override failed: ' + e.textcode); });
420             return $q.reject();
421
422         } 
423
424         // renewal auto-overrides are the same as checkout
425         if (evt.filter(function(e){return !service.auto_override_checkout_events[e.textcode];}).length == 0) {
426             // user has already opted to override these type
427             // of events.  Re-run the renew w/ override.
428             options.override = true;
429             return service.renew(params, options);
430         } 
431
432         // Ask the user if they would like to override this event.
433         // Some events offer a stock override dialog, while others
434         // require additional context.
435
436         switch(evt[0].textcode) {
437             case 'COPY_ALERT_MESSAGE':
438                 return service.copy_alert_dialog(evt[0], params, options, 'renew');
439             default: 
440                 return service.override_dialog(evt, params, options, 'renew');
441         }
442     }
443
444
445     service.handle_overridable_checkin_event = function(evt, params, options) {
446
447         if (options.override) {
448             // override attempt already made and failed.
449             // NOTE: I don't think we'll ever get here, since the
450             // override attempt should produce a perm failure...
451             angular.forEach(evt, function(e){ console.debug('override failed: ' + e.textcode); });
452             return $q.reject();
453
454         } 
455
456         if (options.suppress_checkin_popups
457             && evt.filter(function(e){return service.checkin_suppress_overrides.indexOf(e.textcode) == -1;}).length == 0) {
458             // Events are suppressed.  Re-run the checkin w/ override.
459             options.override = true;
460             return service.checkin(params, options);
461         } 
462
463         // Ask the user if they would like to override this event.
464         // Some events offer a stock override dialog, while others
465         // require additional context.
466
467         switch(evt[0].textcode) {
468             case 'COPY_ALERT_MESSAGE':
469                 return service.copy_alert_dialog(evt[0], params, options, 'checkin');
470             case 'HOLD_CAPTURE_DELAYED':
471                 return service.hold_capture_delay_dialog(evt[0], params, options, 'checkin');
472             default: 
473                 return service.override_dialog(evt, params, options, 'checkin');
474         }
475     }
476
477
478     service.handle_renew_resp = function(evt, params, options) {
479
480         var final_resp = {evt : evt, params : params, options : options};
481
482         // track the barcode regardless of whether it refers to a copy
483         angular.forEach(evt, function(e){ e.copy_barcode = params.copy_barcode; });
484
485         // Overridable Events
486         if (evt.filter(function(e){return service.renew_overridable_events.indexOf(e.textcode) > -1;}).length > 0)
487             return service.handle_overridable_renew_event(evt, params, options);
488
489         // Other events
490         switch (evt[0].textcode) {
491             case 'SUCCESS':
492                 egCore.audio.play('info.renew');
493                 return $q.when(final_resp);
494
495             case 'COPY_IN_TRANSIT':
496             case 'PATRON_CARD_INACTIVE':
497             case 'PATRON_INACTIVE':
498             case 'PATRON_ACCOUNT_EXPIRED':
499             case 'CIRC_CLAIMS_RETURNED':
500                 egCore.audio.play('warning.renew');
501                 return service.exit_alert(
502                     egCore.strings[evt[0].textcode],
503                     {barcode : params.copy_barcode}
504                 );
505
506             default:
507                 egCore.audio.play('warning.renew.unknown');
508                 return service.exit_alert(
509                     egCore.strings.CHECKOUT_FAILED_GENERIC, {
510                         barcode : params.copy_barcode,
511                         textcode : evt[0].textcode,
512                         desc : evt[0].desc
513                     }
514                 );
515         }
516     }
517
518
519     service.handle_checkout_resp = function(evt, params, options) {
520
521         var final_resp = {evt : evt, params : params, options : options};
522
523         // track the barcode regardless of whether it refers to a copy
524         angular.forEach(evt, function(e){ e.copy_barcode = params.copy_barcode; });
525
526         // Overridable Events
527         if (evt.filter(function(e){return service.checkout_overridable_events.indexOf(e.textcode) > -1;}).length > 0)
528             return service.handle_overridable_checkout_event(evt, params, options);
529
530         // Other events
531         switch (evt[0].textcode) {
532             case 'SUCCESS':
533                 egCore.audio.play('success.checkout');
534                 return $q.when(final_resp);
535
536             case 'ITEM_NOT_CATALOGED':
537                 egCore.audio.play('error.checkout.no_cataloged');
538                 return service.precat_dialog(params, options);
539
540             case 'OPEN_CIRCULATION_EXISTS':
541                 // auto_renew checked in service.checkout()
542                 egCore.audio.play('error.checkout.open_circ');
543                 return service.circ_exists_dialog(evt, params, options);
544
545             case 'COPY_IN_TRANSIT':
546                 egCore.audio.play('warning.checkout.in_transit');
547                 return service.copy_in_transit_dialog(evt, params, options);
548
549             case 'PATRON_CARD_INACTIVE':
550             case 'PATRON_INACTIVE':
551             case 'PATRON_ACCOUNT_EXPIRED':
552             case 'CIRC_CLAIMS_RETURNED':
553                 egCore.audio.play('warning.checkout');
554                 return service.exit_alert(
555                     egCore.strings[evt[0].textcode],
556                     {barcode : params.copy_barcode}
557                 );
558
559             default:
560                 egCore.audio.play('error.checkout.unknown');
561                 return service.exit_alert(
562                     egCore.strings.CHECKOUT_FAILED_GENERIC, {
563                         barcode : params.copy_barcode,
564                         textcode : evt[0].textcode,
565                         desc : evt[0].desc
566                     }
567                 );
568         }
569     }
570
571     // returns a promise resolved with the list of circ mods
572     service.get_circ_mods = function() {
573         if (egCore.env.ccm) 
574             return $q.when(egCore.env.ccm.list);
575
576         return egCore.pcrud.retrieveAll('ccm', null, {atomic : true})
577         .then(function(list) { 
578             egCore.env.absorbList(list, 'ccm');
579             return list;
580         });
581     };
582
583     // returns a promise resolved with the list of noncat types
584     service.get_noncat_types = function() {
585         if (egCore.env.cnct) 
586             return $q.when(egCore.env.cnct.list);
587
588         return egCore.pcrud.search('cnct', 
589             {owning_lib : 
590                 egCore.org.fullPath(egCore.auth.user().ws_ou(), true)}, 
591             null, {atomic : true}
592         ).then(function(list) { 
593             egCore.env.absorbList(list, 'cnct');
594             return list;
595         });
596     }
597
598     service.get_staff_penalty_types = function() {
599         if (egCore.env.csp) 
600             return $q.when(egCore.env.csp.list);
601         return egCore.pcrud.search(
602             // id <= 100 are reserved for system use
603             'csp', {id : {'>': 100}}, {}, {atomic : true})
604         .then(function(penalties) {
605             return egCore.env.absorbList(penalties, 'csp').list;
606         });
607     }
608
609     // ideally all of these data should be returned with the response,
610     // but until then, grab what we need.
611     service.flesh_response_data = function(action, evt, params, options) {
612         var promises = [];
613         var payload;
614         if (!evt[0] || !(payload = evt[0].payload)) return $q.when();
615         
616         promises.push(service.flesh_copy_location(payload.copy));
617         if (payload.copy) {
618             promises.push(service.flesh_acn_owning_lib(payload.volume));
619             promises.push(service.flesh_copy_circ_library(payload.copy));
620             promises.push(service.flesh_copy_circ_modifier(payload.copy));
621             promises.push(
622                 service.flesh_copy_status(payload.copy)
623
624                 .then(function() {
625                     // copy is in transit, but no transit was delivered
626                     // in the payload.  Do this here instead of below to
627                     // ensure consistent copy status fleshiness
628                     if (!payload.transit && payload.copy.status().id() == 6) { // in-transit
629                         return service.find_copy_transit(evt, params, options)
630                         .then(function(trans) {
631                             if (trans) {
632                                 trans.source(egCore.org.get(trans.source()));
633                                 trans.dest(egCore.org.get(trans.dest()));
634                                 payload.transit = trans;
635                             }
636                         })
637                     }
638                 })
639             );
640         }
641
642         // local flesh transit
643         if (transit = payload.transit) {
644             transit.source(egCore.org.get(transit.source()));
645             transit.dest(egCore.org.get(transit.dest()));
646         } 
647
648         // TODO: renewal responses should include the patron
649         if (!payload.patron) {
650             var user_id;
651             if (payload.circ) user_id = payload.circ.usr();
652             if (payload.noncat_circ) user_id = payload.noncat_circ.patron();
653             if (user_id) {
654                 promises.push(
655                     egCore.pcrud.retrieve('au', user_id)
656                     .then(function(user) {payload.patron = user})
657                 );
658             }
659         }
660
661         // extract precat values
662         angular.forEach(evt, function(e){ e.title = payload.record ? payload.record.title() : 
663             (payload.copy ? payload.copy.dummy_title() : null);});
664
665         angular.forEach(evt, function(e){ e.author = payload.record ? payload.record.author() : 
666             (payload.copy ? payload.copy.dummy_author() : null);});
667
668         angular.forEach(evt, function(e){ e.isbn = payload.record ? payload.record.isbn() : 
669             (payload.copy ? payload.copy.dummy_isbn() : null);});
670
671         return $q.all(promises);
672     }
673
674     service.flesh_acn_owning_lib = function(acn) {
675         if (!acn) return $q.when();
676         return $q.when(acn.owning_lib(egCore.org.get( acn.owning_lib() )));
677     }
678
679     service.flesh_copy_circ_library = function(copy) {
680         if (!copy) return $q.when();
681         
682         return $q.when(copy.circ_lib(egCore.org.get( copy.circ_lib() )));
683     }
684
685     // fetches the full list of circ modifiers
686     service.flesh_copy_circ_modifier = function(copy) {
687         if (!copy) return $q.when();
688         if (egCore.env.ccm)
689             return $q.when(copy.circ_modifier(egCore.env.ccm.map[copy.circ_modifier()]));
690         return egCore.pcrud.retrieveAll('ccm', {}, {atomic : true}).then(
691             function(list) {
692                 egCore.env.absorbList(list, 'ccm');
693                 copy.circ_modifier(egCore.env.ccm.map[copy.circ_modifier()]);
694             }
695         );
696     }
697
698     // fetches the full list of copy statuses
699     service.flesh_copy_status = function(copy) {
700         if (!copy) return $q.when();
701         if (egCore.env.ccs) 
702             return $q.when(copy.status(egCore.env.ccs.map[copy.status()]));
703         return egCore.pcrud.retrieveAll('ccs', {}, {atomic : true}).then(
704             function(list) {
705                 egCore.env.absorbList(list, 'ccs');
706                 copy.status(egCore.env.ccs.map[copy.status()]);
707             }
708         );
709     }
710
711     // there may be *many* copy locations and we may be handling items
712     // for other locations.  Fetch copy locations as-needed and cache.
713     service.flesh_copy_location = function(copy) {
714         if (!copy) return $q.when();
715         if (angular.isObject(copy.location())) return $q.when(copy);
716         if (egCore.env.acpl) {
717             if (egCore.env.acpl.map[copy.location()]) {
718                 copy.location(egCore.env.acpl.map[copy.location()]);
719                 return $q.when(copy);
720             }
721         } 
722         return egCore.pcrud.retrieve('acpl', copy.location())
723         .then(function(loc) {
724             egCore.env.absorbList([loc], 'acpl'); // append to cache
725             copy.location(loc);
726             return copy;
727         });
728     }
729
730
731     // fetch org unit addresses as needed.
732     service.get_org_addr = function(org_id, addr_type) {
733         var org = egCore.org.get(org_id);
734         var addr_id = org[addr_type]();
735
736         if (!addr_id) return $q.when(null);
737
738         if (egCore.env.aoa && egCore.env.aoa.map[addr_id]) 
739             return $q.when(egCore.env.aoa.map[addr_id]); 
740
741         return egCore.pcrud.retrieve('aoa', addr_id).then(function(addr) {
742             egCore.env.absorbList([addr], 'aoa');
743             return egCore.env.aoa.map[addr_id]; 
744         });
745     }
746
747     service.exit_alert = function(msg, scope) {
748         return egAlertDialog.open(msg, scope).result.then(
749             function() {return $q.reject()});
750     }
751
752     // opens a dialog asking the user if they would like to override
753     // the returned event.
754     service.override_dialog = function(evt, params, options, action) {
755         if (!angular.isArray(evt)) evt = [evt];
756
757         egCore.audio.play('warning.circ.event_override');
758         var copy_alert = evt.filter(function(e) {
759             return e.textcode == 'COPY_ALERT_MESSAGE';
760         });
761         evt = evt.filter(function(e) {
762             return e.textcode !== 'COPY_ALERT_MESSAGE';
763         });
764
765         return $uibModal.open({
766             templateUrl: './circ/share/t_event_override_dialog',
767             backdrop: 'static',
768             controller: 
769                 ['$scope', '$uibModalInstance', 
770                 function($scope, $uibModalInstance) {
771                 $scope.events = evt;
772
773                 // Find the event, if any, that is for ITEM_ON_HOLDS_SHELF
774                 //  and grab the patron name of the owner. 
775                 $scope.holdEvent = evt.filter(function(e) {
776                     return e.textcode === 'ITEM_ON_HOLDS_SHELF'
777                 });
778
779                 if ($scope.holdEvent.length > 0) {
780                     // Ensure we have a scalar here
781                     if (angular.isArray($scope.holdEvent)) {
782                         $scope.holdEvent = $scope.holdEvent[0];
783                     }
784
785                     $scope.patronName = $scope.holdEvent.payload.patron_name;
786                     $scope.holdID = $scope.holdEvent.payload.hold_id;
787                     $scope.patronID = $scope.holdEvent.payload.patron_id;
788                 }
789
790                 $scope.auto_override =
791                     evt.filter(function(e){
792                         return service.checkout_auto_override_after_first.indexOf(evt.textcode) > -1;
793                     }).length > 0;
794                 $scope.copy_barcode = params.copy_barcode; // may be null
795
796                 // Implementation note: Why not use a primitive here? It
797                 // doesn't work.  See: 
798                 // http://stackoverflow.com/questions/18642371/checkbox-not-binding-to-scope-in-angularjs
799                 $scope.formdata = {clearHold : service.clearHold};
800
801                 $scope.ok = function() { 
802                     // Handle the cancellation of the assciated hold here
803                     if ($scope.formdata.clearHold && $scope.holdID) {
804                         egCore.net.request(
805                             'open-ils.circ',
806                             'open-ils.circ.hold.cancel',
807                             egCore.auth.token(), $scope.holdID,
808                             5, // staff forced
809                             'Item checked out by other patron' // FIXME I18n
810                         );
811                     }
812                     $uibModalInstance.close();
813                 }
814
815                 $scope.cancel = function ($event) { 
816                     $uibModalInstance.dismiss();
817                     $event.preventDefault();
818                 }
819             }]
820         }).result.then(
821             function() {
822                 options.override = true;
823
824                 if (copy_alert.length > 0) {
825                     return service.copy_alert_dialog(copy_alert, params, options, action);
826                 }
827
828                 if (action == 'checkin') {
829                     return service.checkin(params, options);
830                 }
831
832                 // checkout/renew support override-after-first
833                 angular.forEach(evt, function(e){
834                     if (service.checkout_auto_override_after_first.indexOf(e.textcode) > -1)
835                         service.auto_override_checkout_events[e.textcode] = true;
836                 });
837
838                 return service[action](params, options);
839             }
840         );
841     }
842
843     service.copy_not_avail_dialog = function(evt, params, options) {
844         if (!angular.isArray(evt)) evt = [evt];
845
846         var copy_alert = evt.filter(function(e) {
847             return e.textcode == 'COPY_ALERT_MESSAGE';
848         });
849         evt = evt.filter(function(e) {
850             return e.textcode !== 'COPY_ALERT_MESSAGE';
851         });
852         evt = evt[0];
853
854         return $uibModal.open({
855             templateUrl: './circ/share/t_copy_not_avail_dialog',
856             backdrop: 'static',
857             controller: 
858                        ['$scope','$uibModalInstance','copyStatus',
859                 function($scope , $uibModalInstance , copyStatus) {
860                 $scope.copyStatus = copyStatus;
861                 $scope.ok = function() {$uibModalInstance.close()}
862                 $scope.cancel = function() {$uibModalInstance.dismiss()}
863             }],
864             resolve : {
865                 copyStatus : function() {
866                     return egCore.pcrud.retrieve(
867                         'ccs', evt.payload.status());
868                 }
869             }
870         }).result.then(
871             function() {
872                 options.override = true;
873
874                 if (copy_alert.length > 0) {
875                     return service.copy_alert_dialog(copy_alert, params, options, 'checkout');
876                 }
877
878                 return service.checkout(params, options);
879             }
880         );
881     }
882
883     // Opens a dialog allowing the user to fill in the desired non-cat count.
884     // Unlike other dialogs, which kickoff circ actions internally
885     // as a result of events, this dialog does not kick off any circ
886     // actions. It just collects the count and and resolves the promise.
887     //
888     // This assumes the caller has already handled the noncat-type
889     // selection and just needs to collect the count info.
890     service.noncat_dialog = function(params, options) {
891         var noncatMax = 99; // hard-coded max
892         
893         // the caller should presumably have fetched the noncat_types via
894         // our API already, but fetch them again (from cache) to be safe.
895         return service.get_noncat_types().then(function() {
896
897             params.noncat = true;
898             var type = egCore.env.cnct.map[params.noncat_type];
899
900             return $uibModal.open({
901                 templateUrl: './circ/share/t_noncat_dialog',
902                 backdrop: 'static',
903                 controller: 
904                     ['$scope', '$uibModalInstance',
905                     function($scope, $uibModalInstance) {
906                     $scope.focusMe = true;
907                     $scope.type = type;
908                     $scope.count = 1;
909                     $scope.noncatMax = noncatMax;
910                     $scope.ok = function(count) { $uibModalInstance.close(count) }
911                     $scope.cancel = function ($event) { 
912                         $uibModalInstance.dismiss() 
913                         $event.preventDefault();
914                     }
915                 }],
916             }).result.then(
917                 function(count) {
918                     if (count && count > 0 && count <= noncatMax) { 
919                         // NOTE: in Chrome, form validation ensure a valid number
920                         params.noncat_count = count;
921                         return $q.when(params);
922                     } else {
923                         return $q.reject();
924                     }
925                 }
926             );
927         });
928     }
929
930     // Opens a dialog allowing the user to fill in pre-cat copy info.
931     service.precat_dialog = function(params, options) {
932
933         return $uibModal.open({
934             templateUrl: './circ/share/t_precat_dialog',
935             backdrop: 'static',
936             controller: 
937                 ['$scope', '$uibModalInstance', 'circMods',
938                 function($scope, $uibModalInstance, circMods) {
939                 $scope.focusMe = true;
940                 $scope.precatArgs = {
941                     copy_barcode : params.copy_barcode
942                 };
943                 $scope.circModifiers = circMods;
944                 $scope.ok = function(args) { $uibModalInstance.close(args) }
945                 $scope.cancel = function () { $uibModalInstance.dismiss() }
946
947                 // use this function as a keydown handler on form
948                 // elements that should not submit the form on enter.
949                 $scope.preventSubmit = function($event) {
950                     if ($event.keyCode == 13)
951                         $event.preventDefault();
952                 }
953             }],
954             resolve : {
955                 circMods : function() { 
956                     return service.get_circ_mods();
957                 }
958             }
959         }).result.then(
960             function(args) {
961                 if (!args || !args.dummy_title) return $q.reject();
962                 if(args.circ_modifier == "") args.circ_modifier = null;
963                 angular.forEach(args, function(val, key) {params[key] = val});
964                 params.precat = true;
965                 return service.checkout(params, options);
966             }
967         );
968     }
969
970     // find the open transit for the given copy barcode; flesh the org
971     // units locally.
972     service.find_copy_transit = function(evt, params, options) {
973         if (angular.isArray(evt)) evt = evt[0];
974
975         // NOTE: evt.payload.transit may exist, but it's not necessarily
976         // the transit we want, since a transit close + open in the API
977         // returns the closed transit.
978
979          return egCore.pcrud.search('atc',
980             {   dest_recv_time : null, cancel_time : null},
981             {   flesh : 1, 
982                 flesh_fields : {atc : ['target_copy']},
983                 join : {
984                     acp : {
985                         filter : {
986                             barcode : params.copy_barcode,
987                             deleted : 'f'
988                         }
989                     }
990                 },
991                 limit : 1,
992                 order_by : {atc : 'source_send_time desc'}, 
993             }, {authoritative : true}
994         ).then(function(transit) {
995             transit.source(egCore.org.get(transit.source()));
996             transit.dest(egCore.org.get(transit.dest()));
997             return transit;
998         });
999     }
1000
1001     service.copy_in_transit_dialog = function(evt, params, options) {
1002         if (angular.isArray(evt)) evt = evt[0];
1003         return $uibModal.open({
1004             templateUrl: './circ/share/t_copy_in_transit_dialog',
1005             backdrop: 'static',
1006             controller: 
1007                        ['$scope','$uibModalInstance','transit',
1008                 function($scope , $uibModalInstance , transit) {
1009                 $scope.transit = transit;
1010                 $scope.ok = function() { $uibModalInstance.close(transit) }
1011                 $scope.cancel = function() { $uibModalInstance.dismiss() }
1012             }],
1013             resolve : {
1014                 // fetch the conflicting open transit w/ fleshed copy
1015                 transit : function() {
1016                     return service.find_copy_transit(evt, params, options);
1017                 }
1018             }
1019         }).result.then(
1020             function(transit) {
1021                 // user chose to abort the transit then checkout
1022                 return service.abort_transit(transit.id())
1023                 .then(function() {
1024                     return service.checkout(params, options);
1025                 });
1026             }
1027         );
1028     }
1029
1030     service.abort_transit = function(transit_id) {
1031         return egCore.net.request(
1032             'open-ils.circ',
1033             'open-ils.circ.transit.abort',
1034             egCore.auth.token(), {transitid : transit_id}
1035         ).then(function(resp) {
1036             if (evt = egCore.evt.parse(resp)) {
1037                 alert(evt);
1038                 return $q.reject();
1039             }
1040             return $q.when();
1041         });
1042     }
1043
1044     service.last_copy_circ = function(copy_id) {
1045         return egCore.pcrud.search('circ', 
1046             {target_copy : copy_id},
1047             {order_by : {circ : 'xact_start desc' }, limit : 1}
1048         );
1049     }
1050
1051     service.circ_exists_dialog = function(evt, params, options) {
1052         if (angular.isArray(evt)) evt = evt[0];
1053
1054         if (!evt.payload.old_circ) {
1055             return egCore.net.request(
1056                 'open-ils.search',
1057                 'open-ils.search.asset.copy.fleshed2.find_by_barcode',
1058                 params.copy_barcode
1059             ).then(function(resp){
1060                 console.log(resp);
1061                 if (egCore.evt.parse(resp)) {
1062                     console.error(egCore.evt.parse(resp));
1063                 } else {
1064                     return egCore.net.request(
1065                          'open-ils.circ',
1066                          'open-ils.circ.copy_checkout_history.retrieve',
1067                          egCore.auth.token(), resp.id(), 1
1068                     ).then( function (circs) {
1069                         evt.payload.old_circ = circs[0];
1070                         return service.circ_exists_dialog_impl( evt, params, options );
1071                     });
1072                 }
1073             });
1074         } else {
1075             return service.circ_exists_dialog_impl( evt, params, options );
1076         }
1077     },
1078
1079     service.circ_exists_dialog_impl = function (evt, params, options) {
1080
1081         var openCirc = evt.payload.old_circ;
1082         var sameUser = openCirc.usr() == params.patron_id;
1083         
1084         return $uibModal.open({
1085             templateUrl: './circ/share/t_circ_exists_dialog',
1086             backdrop: 'static',
1087             controller: 
1088                        ['$scope','$uibModalInstance',
1089                 function($scope , $uibModalInstance) {
1090                 $scope.args = {forgive_fines : false};
1091                 $scope.circDate = openCirc.xact_start();
1092                 $scope.sameUser = sameUser;
1093                 $scope.ok = function() { $uibModalInstance.close($scope.args) }
1094                 $scope.cancel = function($event) { 
1095                     $uibModalInstance.dismiss();
1096                     $event.preventDefault(); // form, avoid calling ok();
1097                 }
1098             }]
1099         }).result.then(
1100             function(args) {
1101                 if (sameUser) {
1102                     params.void_overdues = args.forgive_fines;
1103                     return service.renew(params, options);
1104                 }
1105
1106                 return service.checkin({
1107                     barcode : params.copy_barcode,
1108                     noop : true,
1109                     void_overdues : args.forgive_fines
1110                 }).then(function(checkin_resp) {
1111                     if (checkin_resp.evt[0].textcode == 'SUCCESS') {
1112                         return service.checkout(params, options);
1113                     } else {
1114                         alert(egCore.evt.parse(checkin_resp.evt[0]));
1115                         return $q.reject();
1116                     }
1117                 });
1118             }
1119         );
1120     }
1121
1122     service.batch_backdate = function(circ_ids, backdate) {
1123         return egCore.net.request(
1124             'open-ils.circ',
1125             'open-ils.circ.post_checkin_backdate.batch',
1126             egCore.auth.token(), circ_ids, backdate);
1127     }
1128
1129     service.backdate_dialog = function(circ_ids) {
1130         return $uibModal.open({
1131             templateUrl: './circ/share/t_backdate_dialog',
1132             backdrop: 'static',
1133             controller: 
1134                        ['$scope','$uibModalInstance',
1135                 function($scope , $uibModalInstance) {
1136
1137                 var today = new Date();
1138                 $scope.dialog = {
1139                     num_circs : circ_ids.length,
1140                     num_processed : 0,
1141                     backdate : today
1142                 }
1143
1144                 $scope.$watch('dialog.backdate', function(newval) {
1145                     if (newval && newval > today) 
1146                         $scope.dialog.backdate = today;
1147                 });
1148
1149
1150                 $scope.cancel = function() { 
1151                     $uibModalInstance.dismiss();
1152                 }
1153
1154                 $scope.ok = function() { 
1155
1156                     var bd = $scope.dialog.backdate.toISOString().replace(/T.*/,'');
1157                     service.batch_backdate(circ_ids, bd)
1158                     .then(
1159                         function() { // on complete
1160                             $uibModalInstance.close({backdate : bd});
1161                         },
1162                         null,
1163                         function(resp) { // on response
1164                             console.debug('backdate returned ' + resp);
1165                             if (resp == '1') {
1166                                 $scope.num_processed++;
1167                             } else {
1168                                 console.error(egCore.evt.parse(resp));
1169                             }
1170                         }
1171                     );
1172                 }
1173             }]
1174         }).result;
1175     }
1176
1177     service.mark_claims_returned = function(barcode, date, override) {
1178
1179         var method = 'open-ils.circ.circulation.set_claims_returned';
1180         if (override) method += '.override';
1181
1182         console.debug('claims returned ' + method);
1183
1184         return egCore.net.request(
1185             'open-ils.circ', method, egCore.auth.token(),
1186             {barcode : barcode, backdate : date})
1187
1188         .then(function(resp) {
1189
1190             if (resp == 1) { // success
1191                 console.debug('claims returned succeeded for ' + barcode);
1192                 return barcode;
1193
1194             } else if (evt = egCore.evt.parse(resp)) {
1195                 console.debug('claims returned failed: ' + evt.toString());
1196
1197                 if (evt.textcode == 'PATRON_EXCEEDS_CLAIMS_RETURN_COUNT') {
1198                     // TODO check perms before offering override option?
1199
1200                     if (override) return;// just to be safe
1201
1202                     return egConfirmDialog.open(
1203                         egCore.strings.TOO_MANY_CLAIMS_RETURNED, '', {}
1204                     ).result.then(function() {
1205                         return service.mark_claims_returned(barcode, date, true);
1206                     });
1207                 }
1208
1209                 if (evt.textcode == 'PERM_FAILURE') {
1210                     console.error('claims returned permission denied')
1211                     // TODO: auth override dialog?
1212                 }
1213             }
1214         });
1215     }
1216
1217     service.mark_claims_returned_dialog = function(copy_barcodes) {
1218         if (!copy_barcodes.length) return;
1219
1220         return $uibModal.open({
1221             templateUrl: './circ/share/t_mark_claims_returned_dialog',
1222             backdrop: 'static',
1223             controller: 
1224                        ['$scope','$uibModalInstance',
1225                 function($scope , $uibModalInstance) {
1226
1227                 var today = new Date();
1228                 $scope.args = {
1229                     barcodes : copy_barcodes,
1230                     date : today
1231                 };
1232
1233                 $scope.$watch('args.date', function(newval) {
1234                     if (newval && newval > today) 
1235                         $scope.args.backdate = today;
1236                 });
1237
1238                 $scope.cancel = function() {$uibModalInstance.dismiss()}
1239                 $scope.ok = function() { 
1240
1241                     var date = $scope.args.date.toISOString().replace(/T.*/,'');
1242
1243                     var deferred = $q.defer();
1244
1245                     // serialize the action on each barcode so that the 
1246                     // caller will never see multiple alerts at the same time.
1247                     function mark_one() {
1248                         var bc = copy_barcodes.pop();
1249                         if (!bc) {
1250                             deferred.resolve();
1251                             $uibModalInstance.close();
1252                             return;
1253                         }
1254
1255                         // finally -> continue even when one fails
1256                         service.mark_claims_returned(bc, date)
1257                         .finally(function(barcode) {
1258                             if (barcode) deferred.notify(barcode);
1259                             mark_one();
1260                         });
1261                     }
1262                     mark_one(); // kick it off
1263                     return deferred.promise;
1264                 }
1265             }]
1266         }).result;
1267     }
1268
1269     // serially checks in each barcode with claims_never_checked_out set
1270     // returns promise, notified on each barcode, resolved after all
1271     // checkins are complete.
1272     service.mark_claims_never_checked_out = function(barcodes) {
1273         if (!barcodes.length) return;
1274
1275         var deferred = $q.defer();
1276         egConfirmDialog.open(
1277             egCore.strings.MARK_NEVER_CHECKED_OUT, '', {barcodes : barcodes}
1278
1279         ).result.then(function() {
1280             function mark_one() {
1281                 var bc = barcodes.pop();
1282
1283                 if (!bc) { // all done
1284                     deferred.resolve();
1285                     return;
1286                 }
1287
1288                 service.checkin(
1289                     {claims_never_checked_out : true, copy_barcode : bc})
1290                 .finally(function() { 
1291                     deferred.notify(bc);
1292                     mark_one();
1293                 })
1294             }
1295             mark_one();
1296         });
1297
1298         return deferred.promise;
1299     }
1300
1301     service.mark_damaged = function(params) {
1302         if (!params) return $q.when();
1303         return $uibModal.open({
1304             templateUrl: './circ/share/t_mark_damaged',
1305             controller:
1306                 ['$scope', '$uibModalInstance', 'egCore', 'egBilling', 'egItem',
1307                 function($scope, $uibModalInstance, egCore, egBilling, egItem) {
1308                     var doRefresh = params.refresh;
1309                     
1310                     $scope.billArgs = {charge: params.charge};
1311                     $scope.mode = 'charge';
1312                     $scope.barcode = params.barcode;
1313                     if (params.charge && params.charge > 0) {
1314                         $scope.applyFine = "apply";
1315                     }
1316                     if (params.circ) {
1317                         $scope.circ = params.circ;
1318                         $scope.circ_checkin_time = params.circ.checkin_time();
1319                         $scope.circ_patron_name = params.circ.usr().family_name() + ", "
1320                             + params.circ.usr().first_given_name() + " "
1321                             + params.circ.usr().second_given_name();
1322                     }
1323                     egBilling.fetchBillingTypes().then(function(res) {
1324                         $scope.billingTypes = res;
1325                     });
1326
1327                     $scope.btnChargeFees = function() {
1328                         $scope.mode = 'charge';
1329                         $scope.billArgs.charge = params.charge;
1330                         $scope.applyFine = "apply";
1331                     }
1332                     $scope.btnWaiveFees = function() {
1333                         $scope.mode = 'waive';
1334                         $scope.billArgs.charge = 0;
1335                         $scope.applyFine = "noapply";
1336                     }
1337
1338                     $scope.cancel = function ($event) { 
1339                         $uibModalInstance.dismiss();
1340                     }
1341                     $scope.ok = function() {
1342                         handle_mark_item_damaged();
1343                     }
1344
1345                     var handle_mark_item_damaged = function() {
1346                         egCore.net.request(
1347                             'open-ils.circ',
1348                             'open-ils.circ.mark_item_damaged',
1349                             egCore.auth.token(), params.id, {
1350                                 apply_fines: $scope.applyFine,
1351                                 override_amount: $scope.billArgs.charge,
1352                                 override_btype: $scope.billArgs.type,
1353                                 override_note: $scope.billArgs.note,
1354                                 handle_checkin: !$scope.applyFine
1355                         }).then(function(resp) {
1356                             if (evt = egCore.evt.parse(resp)) {
1357                                 doRefresh = false;
1358                                 console.debug("mark damaged more information required. Pushing back.");
1359                                 service.mark_damaged({
1360                                     id: params.id,
1361                                     barcode: params.barcode,
1362                                     charge: evt.payload.charge,
1363                                     circ: evt.payload.circ,
1364                                     refresh: params.refresh
1365                                 });
1366                                 console.error('mark damaged failed: ' + evt);
1367                             }
1368                         }).then(function() {
1369                             if (doRefresh) egItem.add_barcode_to_list(params.barcode);
1370                         });
1371                         $uibModalInstance.close();
1372                     }
1373                 }]
1374         }).result;
1375     }
1376
1377     service.mark_missing = function(copy_ids) {
1378         return egConfirmDialog.open(
1379             egCore.strings.MARK_MISSING_CONFIRM, '',
1380             {   num_items : copy_ids.length,
1381                 ok : function() {},
1382                 cancel : function() {}
1383             }
1384         ).result.then(function() {
1385             var promises = [];
1386             angular.forEach(copy_ids, function(copy_id) {
1387                 promises.push(
1388                     egCore.net.request(
1389                         'open-ils.circ',
1390                         'open-ils.circ.mark_item_missing',
1391                         egCore.auth.token(), copy_id
1392                     ).then(function(resp) {
1393                         if (evt = egCore.evt.parse(resp)) {
1394                             console.error('mark missing failed: ' + evt);
1395                         }
1396                     })
1397                 );
1398             });
1399
1400             return $q.all(promises);
1401         });
1402     }
1403
1404
1405
1406     // Mark circulations as lost via copy barcode.  As each item is 
1407     // processed, the returned promise is notified of the barcode.
1408     // No confirmation dialog is presented.
1409     service.mark_lost = function(copy_barcodes) {
1410         var deferred = $q.defer();
1411         var promises = [];
1412
1413         angular.forEach(copy_barcodes, function(barcode) {
1414             promises.push(
1415                 egCore.net.request(
1416                     'open-ils.circ',
1417                     'open-ils.circ.circulation.set_lost',
1418                     egCore.auth.token(), {barcode : barcode}
1419                 ).then(function(resp) {
1420                     if (evt = egCore.evt.parse(resp)) {
1421                         console.error("Mark lost failed: " + evt.toString());
1422                         return;
1423                     }
1424                     // inform the caller as each item is processed
1425                     deferred.notify(barcode);
1426                 })
1427             );
1428         });
1429
1430         $q.all(promises).then(function() {deferred.resolve()});
1431         return deferred.promise;
1432     }
1433
1434     service.abort_transits = function(transit_ids) {
1435         return egConfirmDialog.open(
1436             egCore.strings.ABORT_TRANSIT_CONFIRM, '',
1437             {   num_transits : transit_ids.length,
1438                 ok : function() {},
1439                 cancel : function() {}
1440             }
1441
1442         ).result.then(function() {
1443             var promises = [];
1444             angular.forEach(transit_ids, function(transit_id) {
1445                 promises.push(
1446                     egCore.net.request(
1447                         'open-ils.circ',
1448                         'open-ils.circ.transit.abort',
1449                         egCore.auth.token(), {transitid : transit_id}
1450                     ).then(function(resp) {
1451                         if (evt = egCore.evt.parse(resp)) {
1452                             console.error('abort transit failed: ' + evt);
1453                         }
1454                     })
1455                 );
1456             });
1457
1458             return $q.all(promises);
1459         });
1460     }
1461
1462     service.add_copy_alerts = function(item_ids) {
1463         return egAddCopyAlertDialog.open({
1464             copy_ids : item_ids,
1465             ok : function() { },
1466             cancel : function() {}
1467         }).result.then(function() { });
1468     }
1469
1470     service.manage_copy_alerts = function(item_ids) {
1471         return egCopyAlertEditorDialog.open({
1472             copy_id : item_ids[0],
1473             ok : function() { },
1474             cancel : function() {}
1475         }).result.then(function() { });
1476     }
1477
1478     // alert when copy location alert_message is set.
1479     // This does not affect processing, it only produces a click-through
1480     service.handle_checkin_loc_alert = function(evt, params, options) {
1481         if (angular.isArray(evt)) evt = evt[0];
1482
1483         var copy = evt && evt.payload ? evt.payload.copy : null;
1484
1485         if (copy && !options.suppress_checkin_popups
1486             && copy.location().checkin_alert() == 't') {
1487
1488             return egAlertDialog.open(
1489                 egCore.strings.LOCATION_ALERT_MSG, {copy : copy}).result;
1490         }
1491
1492         return $q.when();
1493     }
1494
1495     service.handle_checkin_resp = function(evt, params, options) {
1496         if (!angular.isArray(evt)) evt = [evt];
1497
1498         var final_resp = {evt : evt, params : params, options : options};
1499
1500         var copy, hold, transit, latest_inventory;
1501         if (evt[0].payload) {
1502             copy = evt[0].payload.copy;
1503             hold = evt[0].payload.hold;
1504             transit = evt[0].payload.transit;
1505             latest_inventory = evt[0].payload.latest_inventory;
1506         }
1507
1508         // track the barcode regardless of whether it's valid
1509         angular.forEach(evt, function(e){ e.copy_barcode = params.copy_barcode; });
1510
1511         angular.forEach(evt, function(e){ console.debug('checkin event ' + e.textcode); });
1512
1513         if (evt.filter(function(e){return service.checkin_overridable_events.indexOf(e.textcode) > -1;}).length > 0)
1514             return service.handle_overridable_checkin_event(evt, params, options);
1515
1516         switch (evt[0].textcode) {
1517
1518             case 'SUCCESS':
1519             case 'NO_CHANGE':
1520
1521                 switch(Number(copy.status().id())) {
1522
1523                     case 0: /* AVAILABLE */                                        
1524                     case 4: /* MISSING */                                          
1525                     case 7: /* RESHELVING */ 
1526
1527                         egCore.audio.play('success.checkin');
1528
1529                         // see if the copy location requires an alert
1530                         return service.handle_checkin_loc_alert(evt, params, options)
1531                         .then(function() {return final_resp});
1532
1533                     case 8: /* ON HOLDS SHELF */
1534                         egCore.audio.play('info.checkin.holds_shelf');
1535                         
1536                         if (hold) {
1537
1538                             if (hold.pickup_lib() == egCore.auth.user().ws_ou()) {
1539                                 // inform user if the item is on the local holds shelf
1540                             
1541                                 evt[0].route_to = egCore.strings.ROUTE_TO_HOLDS_SHELF;
1542                                 return service.route_dialog(
1543                                     './circ/share/t_hold_shelf_dialog', 
1544                                     evt[0], params, options
1545                                 ).then(function() { return final_resp });
1546
1547                             } else {
1548                                 // normally, if the hold was on the shelf at a 
1549                                 // different location, it would be put into 
1550                                 // transit, resulting in a ROUTE_ITEM event.
1551                                 egCore.audio.play('warning.checkin.wrong_shelf');
1552                                 return $q.when(final_resp);
1553                             }
1554                         } else {
1555
1556                             console.error('checkin: item on holds shelf, '
1557                                 + 'but hold info not returned from checkin');
1558                             return $q.when(final_resp);
1559                         }
1560
1561                     case 11: /* CATALOGING */
1562                         egCore.audio.play('info.checkin.cataloging');
1563                         evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1564                         if (options.no_precat_alert)
1565                             return $q.when(final_resp);
1566                         return egAlertDialog.open(
1567                             egCore.strings.PRECAT_CHECKIN_MSG, params)
1568                             .result.then(function() {return final_resp});
1569
1570
1571                     case 15: /* ON_RESERVATION_SHELF */
1572                         egCore.audio.play('info.checkin.reservation');
1573                         // TODO: show booking reservation dialog
1574                         return $q.when(final_resp);
1575
1576                     default:
1577                         egCore.audio.play('success.checkin');
1578                         console.debug('Unusual checkin copy status (may have been set via copy alert): '
1579                             + copy.status().id() + ' : ' + copy.status().name());
1580                         return $q.when(final_resp);
1581                 }
1582                 
1583             case 'ROUTE_ITEM':
1584                 return service.route_dialog(
1585                     './circ/share/t_transit_dialog', 
1586                     evt[0], params, options
1587                 ).then(function() { return final_resp });
1588
1589             case 'ASSET_COPY_NOT_FOUND':
1590                 egCore.audio.play('error.checkin.not_found');
1591                 return egAlertDialog.open(
1592                     egCore.strings.UNCAT_ALERT_DIALOG, params)
1593                     .result.then(function() {return final_resp});
1594
1595             case 'ITEM_NOT_CATALOGED':
1596                 egCore.audio.play('error.checkin.not_cataloged');
1597                 evt[0].route_to = egCore.strings.ROUTE_TO_CATALOGING;
1598                 if (options.no_precat_alert) 
1599                     return $q.when(final_resp);
1600                 return egAlertDialog.open(
1601                     egCore.strings.PRECAT_CHECKIN_MSG, params)
1602                     .result.then(function() {return final_resp});
1603
1604             default:
1605                 egCore.audio.play('error.checkin.unknown');
1606                 console.warn('unhandled checkin response : ' + evt[0].textcode);
1607                 return $q.when(final_resp);
1608         }
1609     }
1610
1611     // collect transit, address, and hold info that's not already
1612     // included in responses.
1613     service.collect_route_data = function(tmpl, evt, params, options) {
1614         if (angular.isArray(evt)) evt = evt[0];
1615         var promises = [];
1616         var data = {};
1617
1618         if (evt.org && !tmpl.match(/hold_shelf/)) {
1619             promises.push(
1620                 service.get_org_addr(evt.org, 'holds_address')
1621                 .then(function(addr) { data.address = addr })
1622             );
1623         }
1624
1625         if (evt.payload.hold) {
1626             promises.push(
1627                 egCore.pcrud.retrieve('au', 
1628                     evt.payload.hold.usr(), {
1629                         flesh : 1,
1630                         flesh_fields : {'au' : ['card']}
1631                     }
1632                 ).then(function(patron) {data.patron = patron})
1633             );
1634         }
1635
1636
1637         if (!tmpl.match(/hold_shelf/)) {
1638             var courier_deferred = $q.defer();
1639             promises.push(courier_deferred.promise);
1640             promises.push(
1641                 service.find_copy_transit(evt, params, options)
1642                 .then(function(trans) {
1643                     data.transit = trans;
1644                     egCore.org.settings('lib.courier_code', trans.dest().id())
1645                     .then(function(s) {
1646                         data.dest_courier_code = s['lib.courier_code'];
1647                         courier_deferred.resolve();
1648                     });
1649                 })
1650             );
1651         }
1652
1653         return $q.all(promises).then(function() { return data });
1654     }
1655
1656     service.route_dialog = function(tmpl, evt, params, options) {
1657         if (angular.isArray(evt)) evt = evt[0];
1658
1659         return service.collect_route_data(tmpl, evt, params, options)
1660         .then(function(data) {
1661
1662             var template = data.transit ?
1663                 (data.patron ? 'hold_transit_slip' : 'transit_slip') :
1664                 'hold_shelf_slip';
1665             if (service.never_auto_print[template]) {
1666                 // do not show the dialog or print if the
1667                 // disabled automatic print attempt type list includes
1668                 // the specified template
1669                 return;
1670             }
1671
1672             // All actions flow from the print data
1673
1674             var print_context = {
1675                 copy : egCore.idl.toHash(evt.payload.copy),
1676                 title : evt.title,
1677                 author : evt.author,
1678                 call_number : egCore.idl.toHash(evt.payload.volume)
1679             };
1680
1681             var acn = print_context.call_number; // fix up pre/suffixes
1682             if (acn.prefix == -1) acn.prefix = "";
1683             if (acn.suffix == -1) acn.suffix = "";
1684
1685             if (data.transit) {
1686                 // route_dialog includes the "route to holds shelf" 
1687                 // dialog, which has no transit
1688                 print_context.transit = egCore.idl.toHash(data.transit);
1689                 print_context.dest_courier_code = data.dest_courier_code;
1690                 if (data.address) {
1691                     print_context.dest_address = egCore.idl.toHash(data.address);
1692                 }
1693                 print_context.dest_location =
1694                     egCore.idl.toHash(egCore.org.get(data.transit.dest()));
1695             }
1696
1697             if (data.patron) {
1698                 print_context.hold = egCore.idl.toHash(evt.payload.hold);
1699                 var notes = print_context.hold.notes;
1700                 if(notes.length > 0){
1701                     print_context.hold_notes = [];
1702                     angular.forEach(notes, function(n){
1703                         print_context.hold_notes.push(n);
1704                     });
1705                 }
1706                 print_context.patron = egCore.idl.toHash(data.patron);
1707             }
1708
1709             var sound = 'info.checkin.transit';
1710             if (evt.payload.hold) sound += '.hold';
1711             egCore.audio.play(sound);
1712
1713             function print_transit(template) {
1714                 return egCore.print.print({
1715                     context : 'default', 
1716                     template : template, 
1717                     scope : print_context
1718                 });
1719             }
1720
1721             // when auto-print is on, skip the dialog and go straight
1722             // to printing.
1723             if (options.auto_print_holds_transits) 
1724                 return print_transit(template);
1725
1726             return $uibModal.open({
1727                 templateUrl: tmpl,
1728                 backdrop: 'static',
1729                 controller: [
1730                             '$scope','$uibModalInstance',
1731                     function($scope , $uibModalInstance) {
1732
1733                     $scope.today = new Date();
1734
1735                     // copy the print scope into the dialog scope
1736                     angular.forEach(print_context, function(val, key) {
1737                         $scope[key] = val;
1738                     });
1739
1740                     $scope.ok = function() {$uibModalInstance.close()}
1741
1742                     $scope.print = function() { 
1743                         $uibModalInstance.close();
1744                         print_transit(template);
1745                     }
1746                 }]
1747
1748             }).result;
1749         });
1750     }
1751
1752     // action == what action to take if the user confirms the alert
1753     service.copy_alert_dialog = function(evt, params, options, action) {
1754         if (angular.isArray(evt)) evt = evt[0];
1755         if (!angular.isArray(evt.payload)) {
1756             return egConfirmDialog.open(
1757                 egCore.strings.COPY_ALERT_MSG_DIALOG_TITLE, 
1758                 evt.payload,  // payload == alert message text
1759                 {   copy_barcode : params.copy_barcode,
1760                     ok : function() {},
1761                     cancel : function() {}
1762                 }
1763             ).result.then(function() {
1764                 options.override = true;
1765                 return service[action](params, options);
1766             });
1767         } else { // we got a list of copy alert objects ...
1768             return egCopyAlertManagerDialog.open({
1769                 alerts : evt.payload,
1770                 mode : action,
1771                 ok : function(the_next_status) {
1772                         if (the_next_status !== null) {
1773                             params.next_copy_status = [ the_next_status ];
1774                             params.capture = 'nocapture';
1775                         }
1776                      },
1777                 cancel : function() {}
1778             }).result.then(function() {
1779                 options.override = true;
1780                 return service[action](params, options);
1781             });
1782         }
1783     }
1784
1785     // action == what action to take if the user confirms the alert
1786     service.hold_capture_delay_dialog = function(evt, params, options, action) {
1787         if (angular.isArray(evt)) evt = evt[0];
1788         return $uibModal.open({
1789             templateUrl: './circ/checkin/t_hold_verify',
1790             backdrop: 'static',
1791             controller:
1792                        ['$scope','$uibModalInstance','params',
1793                 function($scope , $uibModalInstance , params) {
1794                 $scope.copy_barcode = params.copy_barcode;
1795                 $scope.capture = function() {
1796                     params.capture = 'capture';
1797                     $uibModalInstance.close();
1798                 };
1799                 $scope.nocapture = function() {
1800                     params.capture = 'nocapture';
1801                     $uibModalInstance.close();
1802                 };
1803                 $scope.cancel = function() { $uibModalInstance.dismiss(); };
1804             }],
1805             resolve : {
1806                 params : function() {
1807                     return params;
1808                 }
1809             }
1810         }).result.then(
1811             function(r) {
1812                 return service[action](params, options);
1813             }
1814         );
1815     }
1816
1817     // check the barcode.  If it's no good, show the warning dialog
1818     // Resolves on success, rejected on error
1819     service.test_barcode = function(bc) {
1820
1821         var ok = service.check_barcode(bc);
1822         if (ok) return $q.when();
1823
1824         egCore.audio.play('warning.circ.bad_barcode');
1825         return $uibModal.open({
1826             templateUrl: './circ/share/t_bad_barcode_dialog',
1827             backdrop: 'static',
1828             controller: 
1829                 ['$scope', '$uibModalInstance', 
1830                 function($scope, $uibModalInstance) {
1831                 $scope.barcode = bc;
1832                 $scope.ok = function() { $uibModalInstance.close() }
1833                 $scope.cancel = function() { $uibModalInstance.dismiss() }
1834             }]
1835         }).result;
1836     }
1837
1838     // check() and checkdigit() copied directly 
1839     // from chrome/content/util/barcode.js
1840
1841     service.check_barcode = function(bc) {
1842         if (bc != Number(bc)) return false;
1843         bc = bc.toString();
1844         // "16.00" == Number("16.00"), but the . is bad.
1845         // Throw out any barcode that isn't just digits
1846         if (bc.search(/\D/) != -1) return false;
1847         var last_digit = bc.substr(bc.length-1);
1848         var stripped_barcode = bc.substr(0,bc.length-1);
1849         return service.barcode_checkdigit(stripped_barcode).toString() == last_digit;
1850     }
1851
1852     service.barcode_checkdigit = function(bc) {
1853         var reverse_barcode = bc.toString().split('').reverse();
1854         var check_sum = 0; var multiplier = 2;
1855         for (var i = 0; i < reverse_barcode.length; i++) {
1856             var digit = reverse_barcode[i];
1857             var product = digit * multiplier; product = product.toString();
1858             var temp_sum = 0;
1859             for (var j = 0; j < product.length; j++) {
1860                 temp_sum += Number( product[j] );
1861             }
1862             check_sum += Number( temp_sum );
1863             multiplier = ( multiplier == 2 ? 1 : 2 );
1864         }
1865         check_sum = check_sum.toString();
1866         var next_multiple_of_10 = (check_sum.match(/(\d*)\d$/)[1] * 10) + 10;
1867         var check_digit = next_multiple_of_10 - Number(check_sum);
1868         if (check_digit == 10) check_digit = 0;
1869         return check_digit;
1870     }
1871
1872     service.handle_barcode_completion = function(barcode) {
1873         return egCore.net.request(
1874             'open-ils.actor',
1875             'open-ils.actor.get_barcodes',
1876             egCore.auth.token(), egCore.auth.user().ws_ou(), 
1877             'asset', barcode)
1878
1879         .then(function(resp) {
1880             // TODO: handle event during barcode lookup
1881             if (evt = egCore.evt.parse(resp)) {
1882                 console.error(evt.toString());
1883                 return $q.reject();
1884             }
1885
1886             // no matching barcodes: return the barcode as entered
1887             // by the user (so that, e.g., checkout can fall back to
1888             // precat/noncat handling)
1889             if (!resp || !resp[0]) {
1890                 return barcode;
1891             }
1892
1893             // exactly one matching barcode: return it
1894             if (resp.length == 1) {
1895                 return resp[0].barcode;
1896             }
1897
1898             // multiple matching barcodes: let the user pick one 
1899             console.debug('multiple matching barcodes');
1900             var matches = [];
1901             var promises = [];
1902             var final_barcode;
1903             angular.forEach(resp, function(cp) {
1904                 promises.push(
1905                     egCore.net.request(
1906                         'open-ils.circ',
1907                         'open-ils.circ.copy_details.retrieve',
1908                         egCore.auth.token(), cp.id
1909                     ).then(function(r) {
1910                         matches.push({
1911                             barcode: r.copy.barcode(),
1912                             title: r.mvr.title(),
1913                             org_name: egCore.org.get(r.copy.circ_lib()).name(),
1914                             org_shortname: egCore.org.get(r.copy.circ_lib()).shortname()
1915                         });
1916                     })
1917                 );
1918             });
1919             return $q.all(promises)
1920             .then(function() {
1921                 return $uibModal.open({
1922                     templateUrl: './circ/share/t_barcode_choice_dialog',
1923                     backdrop: 'static',
1924                     controller:
1925                         ['$scope', '$uibModalInstance',
1926                         function($scope, $uibModalInstance) {
1927                         $scope.matches = matches;
1928                         $scope.ok = function(barcode) {
1929                             $uibModalInstance.close();
1930                             final_barcode = barcode;
1931                         }
1932                         $scope.cancel = function() {$uibModalInstance.dismiss()}
1933                     }],
1934                 }).result.then(function() { return final_barcode });
1935             })
1936         });
1937     }
1938
1939     service.create_penalty = function(user_id) {
1940         return $uibModal.open({
1941             templateUrl: './circ/share/t_new_message_dialog',
1942             backdrop: 'static',
1943             controller: 
1944                    ['$scope','$uibModalInstance','staffPenalties',
1945             function($scope , $uibModalInstance , staffPenalties) {
1946                 $scope.focusNote = true;
1947                 $scope.penalties = staffPenalties;
1948                 $scope.require_initials = service.require_initials;
1949                 $scope.args = {penalty : 21}; // default to Note
1950                 $scope.setPenalty = function(id) {
1951                     args.penalty = id;
1952                 }
1953                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1954                 $scope.cancel = function($event) { 
1955                     $uibModalInstance.dismiss();
1956                     $event.preventDefault();
1957                 }
1958             }],
1959             resolve : { staffPenalties : service.get_staff_penalty_types }
1960         }).result.then(
1961             function(args) {
1962                 var pen = new egCore.idl.ausp();
1963                 pen.usr(user_id);
1964                 pen.org_unit(egCore.auth.user().ws_ou());
1965                 pen.note(args.note);
1966                 if (args.initials) pen.note(args.note + ' [' + args.initials + ']');
1967                 if (args.custom_penalty) {
1968                     pen.standing_penalty(args.custom_penalty);
1969                 } else {
1970                     pen.standing_penalty(args.penalty);
1971                 }
1972                 pen.staff(egCore.auth.user().id());
1973                 pen.set_date('now');
1974
1975                 return egCore.net.request(
1976                     'open-ils.actor',
1977                     'open-ils.actor.user.penalty.apply',
1978                     egCore.auth.token(), pen
1979                 );
1980             }
1981         );
1982     }
1983
1984     // assumes, for now anyway,  penalty type is fleshed onto usr_penalty.
1985     service.edit_penalty = function(usr_penalty) {
1986         return $uibModal.open({
1987             templateUrl: './circ/share/t_new_message_dialog',
1988             backdrop: 'static',
1989             controller: 
1990                    ['$scope','$uibModalInstance','staffPenalties',
1991             function($scope , $uibModalInstance , staffPenalties) {
1992                 $scope.focusNote = true;
1993                 $scope.penalties = staffPenalties;
1994                 $scope.require_initials = service.require_initials;
1995                 $scope.args = {
1996                     penalty : usr_penalty.standing_penalty().id(),
1997                     note : usr_penalty.note()
1998                 }
1999                 $scope.setPenalty = function(id) { args.penalty = id; }
2000                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
2001                 $scope.cancel = function($event) { 
2002                     $uibModalInstance.dismiss();
2003                     $event.preventDefault();
2004                 }
2005             }],
2006             resolve : { staffPenalties : service.get_staff_penalty_types }
2007         }).result.then(
2008             function(args) {
2009                 usr_penalty.note(args.note);
2010                 if (args.initials) usr_penalty.note(args.note + ' [' + args.initials + ']');
2011                 usr_penalty.standing_penalty(args.penalty);
2012                 return egCore.pcrud.update(usr_penalty);
2013             }
2014         );
2015     }
2016
2017     return service;
2018
2019 }]);
2020
2021