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