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