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