2ccac2314a2d4f9ef8becb46f601e457aa5fd269
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / patron / bills.js
1
2 /* Billing Service */
3
4 angular.module('egPatronApp')
5
6 .factory('billSvc', 
7        ['$q','egCore','egWorkLog','patronSvc',
8 function($q , egCore , egWorkLog , patronSvc) {
9
10     var service = {};
11
12     // fetch org unit settings specific to the bills display
13     service.fetchBillSettings = function() {
14         if (service.settings) return $q.when(service.settings);
15         return egCore.org.settings([
16             'ui.circ.billing.uncheck_bills_and_unfocus_payment_box',
17             'ui.circ.billing.amount_warn', 'ui.circ.billing.amount_limit',
18             'circ.staff_client.do_not_auto_attempt_print',
19             'circ.disable_patron_credit'
20         ]).then(function(s) {return service.settings = s});
21     }
22
23     // user billing summary
24     service.fetchSummary = function() {
25         return egCore.pcrud.retrieve(
26             'mous', service.userId, {}, {authoritative : true})
27         .then(function(summary) {return service.summary = summary})
28     }
29
30     service.applyPayment = function(
31         type, payments, note, check, cc_args, patron_credit) {
32
33         return egCore.net.request(
34             'open-ils.circ',
35             'open-ils.circ.money.payment',
36             egCore.auth.token(), {
37                 userid : service.userId,
38                 note : note || '', 
39                 payment_type : type,
40                 check_number : check,
41                 payments : payments,
42                 patron_credit : patron_credit,
43                 cc_args : cc_args
44             },
45             patronSvc.current.last_xact_id()
46         ).then(function(resp) {
47             console.debug('payments: ' + js2JSON(resp));
48
49             if (evt = egCore.evt.parse(resp)) {
50                 // Ideally, all scenarios that lead to this alert appearing
51                 // will be avoided by the application logic.  Leave the alert
52                 // in place now to root out any that remain to be addressed.
53                 alert(evt);
54                 return $q.reject(''+evt);
55             }
56
57             var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
58             var msg;
59             switch(type) {
60                 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
61                 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
62                 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
63                 case 'debit_card_payment' : msg = egCore.strings.EG_WORK_LOG_DEBIT_CARD_PAYMENT; break;
64                 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
65                 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
66                 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
67                 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
68             }
69             egWorkLog.record(
70                 msg,{
71                     'action' : 'paid_bill',
72                     'patron_id' : service.userId,
73                     'total_amount' : total
74                 }
75             );
76
77             // payment API returns the update xact id so we can track it
78             // for future payments without having to refresh the user.
79             patronSvc.current.last_xact_id(resp.last_xact_id);
80
81             // reload patron data if credit balance has changed:
82             if(type === 'credit_payment' || patron_credit){ patronSvc.refreshPrimary(); }
83
84             return resp.payments;
85         });
86     }
87
88     service.fetchBills = function(xact_id) {
89         var bills = [];
90         return egCore.pcrud.search('mb',
91             {xact : xact_id}, null,
92             {authoritative : true}
93         ).then(
94             function() {return bills},
95             null,
96             function(bill) {bills.push(bill); return bill}
97         );
98     }
99
100     service.fetchStatement = function(xact_id) {
101         return egCore.net.request(
102             'open-ils.circ',
103             'open-ils.circ.money.statement.retrieve',
104             egCore.auth.token(), xact_id
105         ).then(function(resp) {
106             if (evt = egCore.evt.parse(resp)) return alert(evt);
107             return resp;
108         });
109     }
110
111     // TODO: no longer needed?
112     service.fetchPayments = function(xact_id) {
113         return egCore.net.request(
114             'open-ils.circ',
115             'open-ils.circ.money.payment.retrieve.all.authoritative',
116             egCore.auth.token(), xact_id
117         );
118     }
119
120     service.voidBills = function(bill_ids) {
121         return egCore.net.requestWithParamList(
122             'open-ils.circ',
123             'open-ils.circ.money.billing.void',
124             [egCore.auth.token()].concat(bill_ids)
125         ).then(function(resp) {
126             if (evt = egCore.evt.parse(resp)) return alert(evt);
127             return resp;
128         });
129     }
130
131     service.adjustBillsToZero = function(bill_ids) {
132         return egCore.net.request(
133             'open-ils.circ',
134             'open-ils.circ.money.billable_xact.adjust_to_zero',
135             egCore.auth.token(),
136             bill_ids
137         ).then(function(resp) {
138             if (evt = egCore.evt.parse(resp)) return alert(evt);
139             return resp;
140         });
141     }
142
143     service.updateBillNotes = function(note, ids) {
144         return egCore.net.requestWithParamList(
145             'open-ils.circ',
146             'open-ils.circ.money.billing.note.edit',
147             [egCore.auth.token(), note].concat(ids)
148         ).then(function(resp) {
149             if (evt = egCore.evt.parse(resp)) return alert(evt);
150             return resp;
151         });
152     }
153
154     service.updatePaymentNotes = function(note, ids) {
155         return egCore.net.requestWithParamList(
156             'open-ils.circ',
157             'open-ils.circ.money.payment.note.edit',
158             [egCore.auth.token(), note].concat(ids)
159         ).then(function(resp) {
160             if (evt = egCore.evt.parse(resp)) return alert(evt);
161             return resp;
162         });
163     }
164
165     return service;
166 }])
167
168
169 /**
170  * Manages Bills
171  */
172 .controller('PatronBillsCtrl',
173        ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
174         'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
175         'egBilling','$uibModal',
176 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
177          egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
178          egBilling , $uibModal) {
179
180     $scope.initTab('bills', $routeParams.id);
181     billSvc.userId = $routeParams.id;
182
183     // set up some defaults
184     $scope.check_number = null;
185     $scope.payment_amount = null;
186     $scope.session_voided = 0;
187     $scope.payment_type = 'cash_payment';
188     $scope.focus_payment = true;
189     $scope.annotate_payment = false;
190     $scope.receipt_count = 1;
191     $scope.receipt_on_pay = { isChecked: false };
192     $scope.convert_to_credit = {isChecked: false};
193     $scope.warn_amount = 1000;
194     $scope.max_amount = 100000;
195     $scope.amount_verified = false;
196     $scope.disable_auto_print = false;
197
198     // Load persistant settings
199     egCore.hatch.getItem('circ.bills.receiptonpay')
200                 .then(function(rcptOnPay){
201                     if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
202                 });
203
204     egCore.hatch.getItem('eg.circ.bills.annotatepayment')
205                 .then(function(annoPay){
206                     if (annoPay) $scope.annotate_payment = annoPay;
207                 });
208
209     // pre-define list-returning funcs in case we access them
210     // before the grid instantiates
211     $scope.gridControls = {
212         focusRowSelector : false,
213         selectedItems : function(){return []},
214         allItems : function(){return []},
215         itemRetrieved : function(item) {
216             item.payment_pending = 0;
217         },
218         activateItem : function(item) {
219             $scope.showFullDetails([item]);
220         },
221         setQuery : function() {    
222             return {
223                 usr : billSvc.userId, 
224                 xact_finish : null,
225                 'summary.balance_owed' : {'<>' : 0}
226             }
227         }, 
228         setSort : function() {
229             return ['xact_start']; 
230         }
231     }
232     // -------------
233     // Apply coloring to rows based on fines stop reason
234     $scope.colorizeBillsList = {
235         apply: function(item) {
236             if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
237                 if (item['circulation.stop_fines'] == 'LOST') {
238                     return 'lost-row';
239                 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
240                     return 'longoverdue-row';
241                 } else {
242                     return 'overdue-row';
243                 }
244             }
245         }
246     }
247
248     // Status Icon Column definition
249     $scope.statusIconColumn = {
250         isEnabled: true,
251         template: function(item) {
252             var icon = '';
253             if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
254                 if (item['circulation.stop_fines'] == "LOST") {
255                     icon = 'glyphicon-question-sign';
256                 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
257                     icon = 'glyphicon-exclamation-sign';
258                 } else {
259                     icon = 'glyphicon-time';
260                 }
261             }
262             return "<i class='glyphicon " + icon + "'></i>"
263         }
264     }
265
266     billSvc.fetchSummary().then(function(s) {$scope.summary = s});
267
268     // given a payment amount, determines how much of that is applied
269     // to selected transactions and how much is left over (change).
270     function pending_payment_info() {
271         var amt = $scope.payment_amount || 0;
272         if (amt >= $scope.owed_selected()) {
273             return {
274                 payment : $scope.owed_selected(),
275                 change : amt - $scope.owed_selected()
276             }
277         } 
278         return {payment : amt, change : 0};
279     }
280
281     // calculates amount owed, billed, and paid for selected items
282     // TODO: move me to service
283     function selected_payment_info() {
284         var info = {owed : 0, billed : 0, paid : 0};
285         angular.forEach($scope.gridControls.selectedItems(), function(item) {
286             info.owed   += Number(item['summary.balance_owed']) * 100;
287             info.billed += Number(item['summary.total_owed']) * 100;
288             info.paid   += Number(item['summary.total_paid']) * 100;
289         });
290         info.owed /= 100;
291         info.billed /= 100;
292         info.paid /= 100;
293         return info;
294     }
295
296     $scope.pending_payment = function() {
297         return pending_payment_info().payment;
298     }
299     $scope.pending_change = function() {
300         return pending_payment_info().change;
301     }
302     $scope.owed_selected = function() {
303         return selected_payment_info().owed; 
304     }
305     $scope.billed_selected = function() {
306         return selected_payment_info().billed;
307     }
308     $scope.paid_selected = function() {
309         return selected_payment_info().paid;
310     }
311     $scope.refunds_available = function() {
312         var amount = 0;
313         angular.forEach($scope.gridControls.allItems(), function(item) {
314             if (item['summary.balance_owed'] < 0) 
315                 amount += item['summary.balance_owed'] * 100;
316         });
317         return -(amount / 100);
318     }
319     $scope.invalid_check_number = function() { 
320         return $scope.payment_type == 'check_payment' && ! $scope.check_number; 
321     }
322
323     // update the item.payment_pending value each time the user
324     // selects different transactions to pay against.
325     $scope.$watch(
326         function() {return $scope.gridControls.selectedItems()},
327         function() {updatePendingColumn()},
328         true
329     );
330
331     // update the item.payment_pending for each (selected) 
332     // transaction any time the user-entered payment amount is modified
333     $scope.$watch('payment_amount', updatePendingColumn);
334
335     // updates the value of the payment_pending column in the grid.
336     // This has to be managed manually since the display value in the grid
337     // is derived from the value on the stored item and not the contents
338     // of our local scope variables.
339     function updatePendingColumn() {
340         // reset all to zero..
341         angular.forEach($scope.gridControls.allItems(), 
342             function(item) {item.payment_pending = 0});
343
344         var payment_amount = $scope.pending_payment();
345
346         var selected = $scope.gridControls.selectedItems();
347         for (var i = 0; i < selected.length; i++) { // for/break
348             var item = selected[i];
349             var owed = Number(item['summary.balance_owed']);
350
351             if (payment_amount > owed) {
352                 // pending payment exceeds balance of current item.
353                 // pay the entire item.
354                 item.payment_pending = owed;
355                 payment_amount -= owed;
356
357             } else {
358                 // balance owed on the current item matches or exceeds
359                 // the pending payment.  Apply the full remainder of
360                 // the payment to this item.. and we're done.
361                 // Limit to two decimal places to avoid floating point issues
362                 item.payment_pending = payment_amount.toFixed(2);
363                 break;
364             }
365         }
366     }
367
368     // builds payment arrays ([xact_id, ammount]) for all transactions
369     // which have a pending payment amount.
370     function generatePayments() {
371         var payments = [];
372         angular.forEach($scope.gridControls.selectedItems(), function(item) {
373             if (item.payment_pending == 0) return;
374             payments.push([item.id, item.payment_pending]);
375         });
376         return payments;
377     }
378
379     function refreshDisplay() {
380         patronSvc.fetchUserStats();
381         billSvc.fetchSummary().then(function(s) {$scope.summary = s});
382         $scope.payment_amount = null;
383         $scope.gridControls.refresh();
384     }
385
386     // generates payments, collects user note if needed, and sends payment
387     // to server.
388     function sendPayment(note, cc_args) {
389         $scope.applyingPayment = true;
390         var make_payments = generatePayments();
391         var patron_credit = $scope.convert_to_credit.isChecked ?
392             $scope.pending_change() : 0; 
393         billSvc.applyPayment($scope.payment_type, 
394             make_payments, note, $scope.check_number, cc_args, patron_credit)
395         .then(
396             function(payment_ids) {
397
398                 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
399                     printReceipt(
400                         $scope.payment_type, payment_ids, make_payments, note);
401                 }
402
403                 refreshDisplay();
404             },
405             function(msg) {
406                 console.error('Payment was rejected: ' + msg);
407             }
408         )
409         .finally(function() { $scope.applyingPayment = false; })
410     }
411
412     $scope.onReceiptOnPayChanged = function(){
413         egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
414     }
415
416     $scope.onAnnotatePaymentChanged = function(){
417         egCore.hatch.setItem('eg.circ.bills.annotatepayment', $scope.annotate_payment);
418     }
419
420     function printReceipt(type, payment_ids, payments_made, note) {
421         var payment_blobs = [];
422         var cusr = patronSvc.current;
423
424         angular.forEach(payments_made, function(payment) {
425             var xact_id = payment[0];
426
427             // find the original transaction in the grid..
428             var xact = $scope.gridControls.allItems().filter(
429                 function(item) {return item.id == xact_id})[0];
430
431             payment_blobs.push({
432                 xact : egCore.idl.flatToNestedHash(xact),
433                 amount : payment[1]
434             });
435         });
436
437         console.log(js2JSON(payment_blobs[0]));
438
439         // page data not yet refreshed, capture data from current scope
440         var print_data = {
441             payment_type : type,
442             payment_note : note,
443             previous_balance : Number($scope.summary.balance_owed()),
444             payment_total : Number($scope.payment_amount),
445             payment_applied : $scope.pending_payment(),
446             amount_voided : Number($scope.session_voided),
447             change_given : $scope.pending_change(),
448             payments : payment_blobs,
449             current_location : egCore.idl.toHash(
450                 egCore.org.get(egCore.auth.user().ws_ou()))
451         };
452
453         // Not a good idea to use patron_stats.fines for this; it's out of date
454         print_data.patron = {
455             prefix : cusr.prefix(),
456             first_given_name : cusr.first_given_name(),
457             second_given_name : cusr.second_given_name(),
458             family_name : cusr.family_name(),
459             suffix : cusr.suffix(),
460             pref_prefix : cusr.pref_prefix(),
461             pref_first_given_name : cusr.pref_first_given_name(),
462             pref_second_given_name : cusr.pref_second_given_name(),
463             pref_family_name : cusr.pref_family_name(),
464             pref_suffix : cusr.pref_suffix(),
465             card : { barcode : cusr.card().barcode() },
466             expire_date : cusr.expire_date(),
467             alias : cusr.alias(),
468             has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
469             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
470         };
471
472         print_data.new_balance = (
473             print_data.previous_balance * 100 - 
474             print_data.payment_applied * 100) / 100;
475
476         for (var i = 0; i < $scope.receipt_count; i++) {
477             egCore.print.print({
478                 context : 'receipt', 
479                 template : 'bill_payment', 
480                 scope : print_data
481             });
482         }
483     }
484
485     $scope.showHistory = function() {
486         $location.path('/circ/patron/' + 
487             patronSvc.current.id() + '/bill_history/transactions');
488     }
489     
490     // For now, only adds billing to first selected item.
491     // Could do batches later if needed
492     $scope.addBilling = function(all) {
493         if (all[0]) {
494             egBilling.showBillDialog({
495                 xact : egCore.idl.flatToNestedHash(all[0]),
496                 patron : $scope.patron()
497             }).then(refreshDisplay);
498         }
499     }
500
501     $scope.showBillDialog = function($event) {
502         egBilling.showBillDialog({
503             patron : $scope.patron()
504         }).then(refreshDisplay);
505     }
506
507     // Select refunds adds all refunds to the existing selection.
508     // It does not /only/ select refunds
509     $scope.selectRefunds = function() {
510         var ids = $scope.gridControls.selectedItems().map(
511             function(i) { return i.id });
512         angular.forEach($scope.gridControls.allItems(), function(item) {
513             if (Number(item['summary.balance_owed']) < 0)
514                 ids.push(item.id);
515         });
516         $scope.gridControls.selectItems(ids);
517     }
518
519     // -------------
520     // determine on initial page load when all of the grid rows should
521     // be selected.
522     var selectOnLoad = true;
523     billSvc.fetchBillSettings().then(function(s) {
524         if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
525             $scope.focus_payment = false; // de-focus the payment box
526             $scope.gridControls.focusRowSelector = true;
527             selectOnLoad = false;
528             // if somehow the grid finishes rendering before our settings 
529             // arrive, manually de-select everything.
530             $scope.gridControls.selectItems([]);
531         }
532         if (s['ui.circ.billing.amount_warn']) {
533             $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
534         }
535         if (s['ui.circ.billing.amount_limit']) {
536             $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
537         }
538         if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
539             $scope.disable_auto_print = Boolean(
540                 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
541             );
542         }
543         if (s['circ.disable_patron_credit']) {
544             $scope.disablePatronCredit = true;
545         }
546     });
547
548     $scope.gridControls.allItemsRetrieved = function() {
549         if (selectOnLoad) {
550             selectOnLoad = false; // only for initial controller load.
551             // select all non-refund items
552             $scope.gridControls.selectItems( 
553                 $scope.gridControls.allItems()
554                 .filter(function(i) {return i['summary.balance_owed'] > 0})
555                 .map(function(i){return i.id})
556             );
557         }
558     }
559     // -------------
560
561
562     $scope.printBills = function(selected) {
563         if (!selected.length) return;
564         // bills print receipt assumes nested hashes, but our grid
565         // stores flattener data.  Fetch the selected xacts as
566         // fleshed pcrud objects and hashify.  
567         // (Consider an alternate approach..)
568         var ids = selected.map(function(t){ return t.id });
569         var xacts = [];
570         egCore.pcrud.search('mbt', 
571             {id : ids},
572             {flesh : 5, flesh_fields : {
573                 'mbt' : ['summary', 'circulation'],
574                 'circ' : ['target_copy'],
575                 'acp' : ['call_number'],
576                 'acn' : ['record','owning_lib','prefix','suffix'],
577                 'bre' : ['simple_record']
578                 }
579             },
580             {authoritative : true}
581         ).then(
582             function() {
583                 var cusr = patronSvc.current;
584                 egCore.print.print({
585                     context : 'receipt', 
586                     template : 'bills_current', 
587                     scope : {   
588                         transactions : xacts,
589                         current_location : egCore.idl.toHash(
590                             egCore.org.get(egCore.auth.user().ws_ou())),
591                         patron : {
592                             prefix : cusr.prefix(),
593                             first_given_name : cusr.first_given_name(),
594                             second_given_name : cusr.second_given_name(),
595                             family_name : cusr.family_name(),
596                             suffix : cusr.suffix(),
597                             pref_prefix : cusr.pref_prefix(),
598                             pref_first_given_name : cusr.pref_first_given_name(),
599                             pref_second_given_name : cusr.pref_second_given_name(),
600                             pref_family_name : cusr.pref_family_name(),
601                             pref_suffix : cusr.pref_suffix(),
602                             card : { barcode : cusr.card().barcode() },
603                             expire_date : cusr.expire_date(),
604                             alias : cusr.alias(),
605                             has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
606                             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
607                         }
608                     }
609                 });
610             }, 
611             null, 
612             function(xact) {
613                 newXact = {
614                     billing_total : xact.billing_total(),
615                     billings : xact.billings(),
616                     grocery : xact.grocery(),
617                     id : xact.id(),
618                     payment_total : xact.payment_total(),
619                     payments : xact.payments(),
620                     summary : egCore.idl.toHash(xact.summary()),
621                     unrecovered : xact.unrecovered(),
622                     xact_finish : xact.xact_finish(),
623                     xact_start : xact.xact_start(),
624                 }
625                 if (xact.circulation()) {
626                     newXact.copy_barcode = xact.circulation().target_copy().barcode(),
627                     newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
628                     newXact.call_number = {
629                         label : xact.circulation().target_copy().call_number().label(),
630                         prefix : xact.circulation().target_copy().call_number().prefix().label(),
631                         suffix : xact.circulation().target_copy().call_number().suffix().label(),
632                         owning_lib : {
633                              name : xact.circulation().target_copy().call_number().owning_lib().name(),
634                              shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
635                         }
636                     }
637                 }
638
639                 xacts.push(newXact);
640             }
641         );
642     }
643
644     $scope.applyPayment = function() {
645
646         if ($scope.payment_amount > $scope.max_amount ) {
647             egAlertDialog.open(
648                 egCore.strings.PAYMENT_OVER_MAX,
649                 {   max_amount : ''+$scope.max_amount,
650                     ok : function() {
651                         $scope.payment_amount = 0;
652                     }
653                 }
654             );
655             return;
656         }
657
658         verify_payment_amount().then(
659             function() { // amount confirmed
660                 add_payment_note().then(function(pay_note) {
661                     add_cc_args().then(function(cc_args) {
662                         var note_text = pay_note ? pay_note.value || '' : null;
663                         sendPayment(note_text, cc_args);
664                     })
665                 });
666             },
667             function() { // amount rejected
668                 console.warn('payment amount rejected');
669                 $scope.payment_amount = 0;
670             }
671         );
672     }
673
674     function verify_payment_amount() {
675         if ($scope.payment_amount < $scope.warn_amount)
676             return $q.when();
677
678         return egConfirmDialog.open(
679             egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, 
680             egCore.strings.PAYMENT_WARN_AMOUNT,
681             {payment_amount : ''+$scope.payment_amount}
682         ).result;
683     }
684
685     function add_payment_note() {
686         if (!$scope.annotate_payment) return $q.when();
687         return egPromptDialog.open(
688             egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
689     }
690
691     function add_cc_args() {
692         if ($scope.payment_type != 'credit_card_payment') 
693             return $q.when();
694
695         return $uibModal.open({
696             templateUrl : './circ/patron/t_cc_payment_dialog',
697             backdrop: 'static',
698             controller : [
699                         '$scope','$uibModalInstance',
700                 function($scope , $uibModalInstance) {
701
702                     $scope.context = {
703                         cc : {
704                             where_process : '1', // internal=1 ; external=0
705                             type : 'VISA', // external only
706                             billing_first : patronSvc.current.first_given_name(),
707                             billing_last : patronSvc.current.family_name()
708                         }
709                     }
710
711                     var addr = patronSvc.current.billing_address() ||
712                         patronSvc.current.mailing_address();
713                     if (addr) {
714                         var cc = $scope.context.cc;
715                         cc.billing_address = addr.street1() + 
716                             (addr.street2() ? ' ' + addr.street2() : '');
717                         cc.billing_city = addr.city();
718                         cc.billing_state = addr.state();
719                         cc.billing_zip = addr.post_code();
720                     }
721
722                     $scope.ok = function() {
723                         // CC payment form is not a <form>, 
724                         // so apply validation manually.
725                         if ( $scope.context.cc.where_process == 0 && 
726                             !$scope.context.cc.approval_code)
727                             return;
728
729                         $uibModalInstance.close($scope.context.cc);
730                     }
731
732                     $scope.cancel = function() {
733                         $uibModalInstance.dismiss();
734                     }
735                 }
736             ]
737         }).result;
738     }
739
740     $scope.voidAllBillings = function(items) {
741         var promises = [];
742         var bill_ids = [];
743         var cents = 0;
744         angular.forEach(items, function(item) {
745             promises.push(
746                 billSvc.fetchBills(item.id).then(function(bills) {
747                     angular.forEach(bills, function(b) {
748                         if (b.voided() != 't') {
749                             cents += b.amount() * 100;
750                             bill_ids.push(b.id())
751                         }
752                     });
753
754                     if (bill_ids.length == 0) {
755                         // TODO: warn
756                         return;
757                     }
758
759                 })
760             );
761         });
762
763         $q.all(promises).then(function(){
764             egCore.audio.play('warning.circ.void_billings_confirmation');
765             egConfirmDialog.open(
766                 egCore.strings.CONFIRM_VOID_BILLINGS, '', 
767                 {   billIds : ''+bill_ids,
768                     amount : ''+(cents/100),
769                     ok : function() {
770                         billSvc.voidBills(bill_ids).then(function() {
771                             $scope.session_voided = 
772                                 ($scope.session_voided * 100 + cents) / 100;
773                             refreshDisplay();
774                         });
775                     }
776                 }
777             );
778         });
779     }
780
781     $scope.adjustToZero = function(items) {
782         if (items.length == 0) return;
783
784         var ids = items.map(function(item) {return item.id});
785
786         egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
787         egConfirmDialog.open(
788             egCore.strings.CONFIRM_ADJUST_TO_ZERO, '', 
789             {   xactIds : ''+ids,
790                 ok : function() {
791                     billSvc.adjustBillsToZero(ids).then(function() {
792                         refreshDisplay();
793                     });
794                 }
795             }
796         );
797
798     }
799
800     // note this is functionally equivalent to selecting a neg. transaction
801     // then clicking Apply Payment -- this just adds a speed bump (ditto
802     // the XUL client).
803     $scope.refundXact = function(all) {
804         var items = all.filter(function(item) {
805             return item['summary.balance_owed'] < 0
806         });
807
808         if (items.length == 0) return;
809
810         var ids = items.map(function(item) {return item.id});
811
812         egCore.audio.play('warning.circ.refund_confirmation');
813         egConfirmDialog.open(
814             egCore.strings.CONFIRM_REFUND_PAYMENT, '', 
815             {   xactIds : ''+ids,
816                 ok : function() {
817                     // reset the received payment amount.  this ensures
818                     // we're not mingling payments with refunds.
819                     $scope.payment_amount = 0;
820                 }
821             }
822         );
823     }
824
825     // direct the user to the transaction details page
826     $scope.showFullDetails = function(all) {
827         var lastClicked = $scope.gridControls.contextMenuItem();
828         if (lastClicked) {
829             $location.path('/circ/patron/' + 
830                 patronSvc.current.id() + '/bill/' + lastClicked + '/statement');
831         } else if (all[0]) {
832             $location.path('/circ/patron/' + 
833                 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
834         }
835             
836     }
837
838     $scope.activateBill = function(xact) {
839         $scope.showFullDetails([xact]);
840     }
841
842 }])
843
844 /**
845  * Displays details of a single transaction
846  */
847 .controller('XactDetailsCtrl',
848        ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
849 function($scope,  $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
850
851     $scope.initTab('bills', $routeParams.id);
852     var xact_id = $routeParams.xact_id;
853     $scope.xact_tab = $routeParams.xact_tab;
854
855     var xactGrid = $scope.xactGridControls = {
856         setQuery : function() { return {xact : xact_id} },
857         setSort : function() { return ['billing_ts'] }
858     }
859
860     var paymentGrid = $scope.paymentGridControls = {
861         setQuery : function() { return {xact : xact_id} },
862         setSort : function() { return ['payment_ts'] }
863     }
864
865     // -- actions
866     $scope.voidBillings = function(bill_list) {
867         var bill_ids = [];
868         var cents = 0;
869         angular.forEach(bill_list, function(b) {
870             if (b.voided != 't') {
871                 cents += b.amount * 100;
872                 bill_ids.push(b.id)
873             }
874         });
875
876         if (bill_ids.length == 0) {
877             // TODO: warn
878             return;
879         }
880
881         egCore.audio.play('warning.circ.void_billings_confirmation');
882         egConfirmDialog.open(
883             egCore.strings.CONFIRM_VOID_BILLINGS, '', 
884             {   billIds : ''+bill_ids,
885                 amount : ''+(cents/100),
886                 ok : function() {
887                     billSvc.voidBills(bill_ids).then(function() {
888                         // TODO? $scope.session_voided = ...
889
890                         // refresh bills and summary data
891                         // note: no need to update payments
892                         patronSvc.fetchUserStats();
893
894                         egBilling.fetchXact(xact_id).then(function(xact) {
895                             $scope.xact = xact
896                         });
897
898                         xactGrid.refresh();
899                     });
900                 }
901             }
902         );
903     }
904
905     // batch-edit billing and payment notes, depending on 'type'
906     function editNotes(selected, type) {
907         var notes = selected.map(function(b){ return b.note }).join(',');
908         var ids = selected.map(function(b){ return b.id });
909
910         // show the note edit prompt
911         egPromptDialog.open(
912             egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
913                 ids : ''+ids,
914                 ok : function(value) {
915
916                     var func = 'updateBillNotes';
917                     if (type == 'payment') func = 'updatePaymentNotes';
918
919                     billSvc[func](value, ids).then(function() {
920                         if (type == 'payment') {
921                             paymentGrid.refresh();
922                         } else {
923                             xactGrid.refresh();
924                         }
925                     });
926                 }
927             }
928         );
929     }
930
931     $scope.editBillNotes = function(selected) {
932         editNotes(selected, 'bill');
933     }
934
935     $scope.editPaymentNotes = function(selected) {
936         editNotes(selected, 'payment');
937     }
938
939     // -- retrieve our data
940     if ($scope.xact_tab == 'statement') {
941         //fetch combined billing statement data
942         billSvc.fetchStatement(xact_id).then(function(statement) {
943             //console.log(statement);
944             $scope.statement_data = statement;
945         });
946     }
947     $scope.total_circs = 0; // start with 0 instead of undefined
948     egBilling.fetchXact(xact_id).then(function(xact) {
949         $scope.xact = xact;
950
951         var copyId = xact.circulation().target_copy().id();
952         var circ_count = 0;
953         egCore.pcrud.search('circbyyr',
954             {copy : copyId}, null, {atomic : true})
955         .then(function(counts) {
956             angular.forEach(counts, function(count) {
957                 circ_count += Number(count.count());
958             });
959             $scope.total_circs = circ_count;
960         });
961         // set the title.  only needs to be done on initial page load
962         if (xact.circulation()) {
963             if (xact.circulation().target_copy().call_number().id() == -1) {
964                 $scope.title = xact.circulation().target_copy().dummy_title();
965             } else  {
966                 // TODO: shared bib service?
967                 $scope.title = xact.circulation().target_copy()
968                     .call_number().record().simple_record().title();
969                 $scope.title_id = xact.circulation().target_copy()
970                     .call_number().record().id();
971             }
972         }
973     });
974 }])
975
976
977 .controller('BillHistoryCtrl',
978        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
979 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
980
981     $scope.initTab('bills', $routeParams.id);
982     billSvc.userId = $routeParams.id;
983     $scope.bill_tab = $routeParams.history_tab;
984     $scope.totals = {};
985
986     // link page controller actions defined by sub-controllers here
987     $scope.actions = {};
988
989     var start = new Date(); // now - 1 year
990     start.setFullYear(start.getFullYear() - 1),
991     $scope.dates = {
992         xact_start : start,
993         xact_finish : new Date()
994     }
995
996     $scope.date_range = function() {
997         var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
998         var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
999         var today = new Date().toISOString().replace(/T.*/,'');
1000         if (end == today) end = 'now';
1001         return [start, end];
1002     }
1003 }])
1004
1005
1006 .controller('BillXactHistoryCtrl',
1007        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
1008 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
1009
1010     // generate a grid query with the current date widget values.
1011     function current_grid_query() {
1012         return {
1013             '-or' : [
1014                 {'summary.balance_owed' : {'<>' : 0}},
1015                 {'summary.last_payment_ts' : {'<>' : null}}
1016             ],
1017             xact_start : {between : $scope.date_range()},
1018             usr : billSvc.userId
1019         }
1020     }
1021
1022     $scope.gridControls = {
1023         selectedItems : function(){return []},
1024         activateItem : function(item) {
1025             $scope.showFullDetails([item]);
1026         },
1027         // this sets the query on page load
1028         setQuery : current_grid_query
1029     }
1030
1031     $scope.$watch('dates.xact_start', function(new_date, old_date) {
1032         if (new_date !== old_date && new_date) {
1033             if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1034                 $scope.dates.xact_finish = new_date;
1035             } else {
1036                 $scope.actions.apply_date_range();
1037             }
1038         }
1039     });
1040     $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1041         if (new_date !== old_date && new_date) {
1042             if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1043                 $scope.dates.xact_start = new_date;
1044             } else {
1045                 $scope.actions.apply_date_range();
1046             }
1047         }
1048     });
1049
1050     $scope.actions.apply_date_range = function() {
1051         // tells the grid to re-draw itself with the new query
1052         $scope.gridControls.setQuery(current_grid_query());
1053     }
1054
1055     // TODO; move me to service
1056     function selected_payment_info() {
1057         var info = {owed : 0, billed : 0, paid : 0};
1058         angular.forEach($scope.gridControls.selectedItems(), function(item) {
1059             info.owed   += Number(item['summary.balance_owed']) * 100;
1060             info.billed += Number(item['summary.total_owed']) * 100;
1061             info.paid   += Number(item['summary.total_paid']) * 100;
1062         });
1063         info.owed /= 100;
1064         info.billed /= 100;
1065         info.paid /= 100;
1066         return info;
1067     }
1068
1069     $scope.totals.selected_billed = function() {
1070         return selected_payment_info().billed;
1071     }
1072     $scope.totals.selected_paid = function() {
1073         return selected_payment_info().paid;
1074     }
1075
1076     $scope.showFullDetails = function(all) {
1077         if (all[0]) 
1078             $location.path('/circ/patron/' + 
1079                 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1080     }
1081
1082     // For now, only adds billing to first selected item.
1083     // Could do batches later if needed
1084     $scope.addBilling = function(all) {
1085         if (all[0]) {
1086             egBilling.showBillDialog({
1087                 xact : egCore.idl.flatToNestedHash(all[0]),
1088                 patron : $scope.patron()
1089             }).then(function() { 
1090                 $scope.gridControls.refresh();
1091                 patronSvc.fetchUserStats();
1092             })
1093         }
1094     }
1095
1096     $scope.printBills = function(selected) { // FIXME: refactor me
1097         if (!selected.length) return;
1098         // bills print receipt assumes nested hashes, but our grid
1099         // stores flattener data.  Fetch the selected xacts as
1100         // fleshed pcrud objects and hashify.  
1101         // (Consider an alternate approach..)
1102         var ids = selected.map(function(t){ return t.id });
1103         var xacts = [];
1104         egCore.pcrud.search('mbt', 
1105             {id : ids},
1106             {flesh : 5, flesh_fields : {
1107                 'mbt' : ['summary', 'circulation'],
1108                 'circ' : ['target_copy'],
1109                 'acp' : ['call_number'],
1110                 'acn' : ['record','owning_lib','prefix','suffix'],
1111                 'bre' : ['simple_record']
1112                 }
1113             },
1114             {authoritative : true}
1115         ).then(
1116             function() {
1117                 var cusr = patronSvc.current;
1118                 egCore.print.print({
1119                     context : 'receipt', 
1120                     template : 'bills_historical', 
1121                     scope : {   
1122                         transactions : xacts,
1123                         current_location : egCore.idl.toHash(
1124                             egCore.org.get(egCore.auth.user().ws_ou())),
1125                         patron : {
1126                             prefix : cusr.prefix(),
1127                             pref_prefix : cusr.pref_prefix(),
1128                             pref_first_given_name : cusr.pref_first_given_name(),
1129                             pref_second_given_name : cusr.pref_second_given_name(),
1130                             pref_family_name : cusr.pref_family_name(),
1131                             pref_suffix : cusr.pref_suffix(),
1132                             first_given_name : cusr.first_given_name(),
1133                             second_given_name : cusr.second_given_name(),
1134                             family_name : cusr.family_name(),
1135                             suffix : cusr.suffix(),
1136                             card : { barcode : cusr.card().barcode() },
1137                             expire_date : cusr.expire_date(),
1138                             alias : cusr.alias(),
1139                             has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1140                             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1141                         }
1142                     }
1143                 });
1144             }, 
1145             null, 
1146             function(xact) {
1147                 newXact = {
1148                     billing_total : xact.billing_total(),
1149                     billings : xact.billings(),
1150                     grocery : xact.grocery(),
1151                     id : xact.id(),
1152                     payment_total : xact.payment_total(),
1153                     payments : xact.payments(),
1154                     summary : egCore.idl.toHash(xact.summary()),
1155                     unrecovered : xact.unrecovered(),
1156                     xact_finish : xact.xact_finish(),
1157                     xact_start : xact.xact_start(),
1158                 }
1159                 if (xact.circulation()) {
1160                     newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1161                     newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1162                     newXact.call_number = {
1163                         label : xact.circulation().target_copy().call_number().label(),
1164                         prefix : xact.circulation().target_copy().call_number().prefix().label(),
1165                         suffix : xact.circulation().target_copy().call_number().suffix().label(),
1166                         owning_lib : {
1167                              name : xact.circulation().target_copy().call_number().owning_lib().name(),
1168                              shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
1169                         }
1170                     }
1171                 }
1172                 xacts.push(newXact);
1173             }
1174         );
1175     }
1176 }])
1177
1178 .controller('BillPaymentHistoryCtrl',
1179        ['$scope','$q','egCore','patronSvc','billSvc','$location',
1180 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
1181
1182     // generate a grid query with the current date widget values.
1183     function current_grid_query() {
1184         return {
1185             'payment_ts' : {between : $scope.date_range()},
1186             'xact.usr' : billSvc.userId
1187         }
1188     }
1189
1190     $scope.gridControls = {
1191         selectedItems : function(){return []},
1192         activateItem : function(item) {
1193             $scope.showFullDetails([item]);
1194         },
1195         setSort : function() {
1196             return [{'payment_ts' : 'DESC'}, 'id'];
1197         },
1198         setQuery : current_grid_query
1199     }
1200
1201     $scope.$watch('dates.xact_start', function(new_date, old_date) {
1202         if (new_date !== old_date && new_date) {
1203             if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1204                 $scope.dates.xact_finish = new_date;
1205             } else {
1206                 $scope.actions.apply_date_range();
1207             }
1208         }
1209     });
1210     $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1211         if (new_date !== old_date && new_date) {
1212             if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1213                 $scope.dates.xact_start = new_date;
1214             } else {
1215                 $scope.actions.apply_date_range();
1216             }
1217         }
1218     });
1219
1220     $scope.actions.apply_date_range = function() {
1221         // tells the grid to re-draw itself with the new query
1222         $scope.gridControls.setQuery(current_grid_query());
1223     }
1224
1225     $scope.showFullDetails = function(all) {
1226         if (all[0]) 
1227             $location.path('/circ/patron/' + 
1228                 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1229     }
1230
1231     $scope.totals.selected_paid = function() {
1232         var paid = 0;
1233         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1234             paid += Number(payment.amount) * 100;
1235         });
1236         return paid / 100;
1237     }
1238 }])
1239
1240
1241