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