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