]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/bills.js
webstaff: fix support of the disabled automatic print attempt type list
[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','ui.circ.billing.amount_warn','ui.circ.billing.amount_limit','circ.staff_client.do_not_auto_attempt_print']
17         ).then(function(s) {return service.settings = s});
18     }
19
20     // user billing summary
21     service.fetchSummary = function() {
22         return egCore.pcrud.retrieve(
23             'mous', service.userId, {}, {authoritative : true})
24         .then(function(summary) {return service.summary = summary})
25     }
26
27     service.applyPayment = function(type, payments, note, check) {
28         return egCore.net.request(
29             'open-ils.circ',
30             'open-ils.circ.money.payment',
31             egCore.auth.token(), {
32                 userid : service.userId,
33                 note : note || '', 
34                 payment_type : type,
35                 check_number : check,
36                 payments : payments,
37                 patron_credit : 0
38             },
39             patronSvc.current.last_xact_id()
40         ).then(function(resp) {
41             console.debug('payments: ' + js2JSON(resp));
42             var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
43             var msg;
44             switch(type) {
45                 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
46                 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
47                 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
48                 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
49                 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
50                 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
51                 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
52             }
53             egWorkLog.record(
54                 msg,{
55                     'action' : 'paid_bill',
56                     'patron_id' : service.userId,
57                     'total_amount' : total
58                 }
59             );
60             if (evt = egCore.evt.parse(resp)) 
61                 return alert(evt);
62
63             // payment API returns the update xact id so we can track it
64             // for future payments without having to refresh the user.
65             patronSvc.current.last_xact_id(resp.last_xact_id);
66             return resp.payments;
67         });
68     }
69
70     service.fetchBills = function(xact_id) {
71         var bills = [];
72         return egCore.pcrud.search('mb',
73             {xact : xact_id}, null,
74             {authoritative : true}
75         ).then(
76             function() {return bills},
77             null,
78             function(bill) {bills.push(bill); return bill}
79         );
80     }
81
82     // TODO: no longer needed?
83     service.fetchPayments = function(xact_id) {
84         return egCore.net.request(
85             'open-ils.circ',
86             'open-ils.circ.money.payment.retrieve.all.authoritative',
87             egCore.auth.token(), xact_id
88         );
89     }
90
91     service.voidBills = function(bill_ids) {
92         return egCore.net.requestWithParamList(
93             'open-ils.circ',
94             'open-ils.circ.money.billing.void',
95             [egCore.auth.token()].concat(bill_ids)
96         ).then(function(resp) {
97             if (evt = egCore.evt.parse(resp)) return alert(evt);
98             return resp;
99         });
100     }
101
102     service.updateBillNotes = function(note, ids) {
103         return egCore.net.requestWithParamList(
104             'open-ils.circ',
105             'open-ils.circ.money.billing.note.edit',
106             [egCore.auth.token(), note].concat(ids)
107         ).then(function(resp) {
108             if (evt = egCore.evt.parse(resp)) return alert(evt);
109             return resp;
110         });
111     }
112
113     service.updatePaymentNotes = function(note, ids) {
114         return egCore.net.requestWithParamList(
115             'open-ils.circ',
116             'open-ils.circ.money.payment.note.edit',
117             [egCore.auth.token(), note].concat(ids)
118         ).then(function(resp) {
119             if (evt = egCore.evt.parse(resp)) return alert(evt);
120             return resp;
121         });
122     }
123
124     return service;
125 }])
126
127
128 /**
129  * Manages Bills
130  */
131 .controller('PatronBillsCtrl',
132        ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
133         'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
134         'egBilling',
135 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
136          egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
137          egBilling) {
138
139     $scope.initTab('bills', $routeParams.id);
140     billSvc.userId = $routeParams.id;
141
142     // set up some defaults
143     $scope.check_number = null;
144     $scope.payment_amount = null;
145     $scope.session_voided = 0;
146     $scope.payment_type = 'cash_payment';
147     $scope.focus_payment = true;
148     $scope.annotate_payment = false;
149     $scope.receipt_count = 1;
150     $scope.receipt_on_pay = false;
151     $scope.warn_amount = 1000;
152     $scope.max_amount = 100000;
153     $scope.amount_verified = false;
154     $scope.disable_auto_print = false;
155
156     // pre-define list-returning funcs in case we access them
157     // before the grid instantiates
158     $scope.gridControls = {
159         focusRowSelector : false,
160         selectedItems : function(){return []},
161         allItems : function(){return []},
162         itemRetrieved : function(item) {
163             item.payment_pending = 0;
164         },
165         activateItem : function(item) {
166             $scope.showFullDetails([item]);
167         },
168         setQuery : function() {    
169             return {
170                 usr : billSvc.userId, 
171                 xact_finish : null,
172                 'summary.balance_owed' : {'<>' : 0}
173             }
174         }, 
175         setSort : function() {
176             return ['xact_start']; 
177         }
178     }
179
180     billSvc.fetchSummary().then(function(s) {$scope.summary = s});
181
182     // given a payment amount, determines how much of that is applied
183     // to selected transactions and how much is left over (change).
184     function pending_payment_info() {
185         var amt = $scope.payment_amount || 0;
186         if (amt >= $scope.owed_selected()) {
187             return {
188                 payment : $scope.owed_selected(),
189                 change : amt - $scope.owed_selected()
190             }
191         } 
192         return {payment : amt, change : 0};
193     }
194
195     // calculates amount owed, billed, and paid for selected items
196     // TODO: move me to service
197     function selected_payment_info() {
198         var info = {owed : 0, billed : 0, paid : 0};
199         angular.forEach($scope.gridControls.selectedItems(), function(item) {
200             info.owed   += Number(item['summary.balance_owed']) * 100;
201             info.billed += Number(item['summary.total_owed']) * 100;
202             info.paid   += Number(item['summary.total_paid']) * 100;
203         });
204         info.owed /= 100;
205         info.billed /= 100;
206         info.paid /= 100;
207         return info;
208     }
209
210     $scope.pending_payment = function() {
211         return pending_payment_info().payment;
212     }
213     $scope.pending_change = function() {
214         return pending_payment_info().change;
215     }
216     $scope.owed_selected = function() {
217         return selected_payment_info().owed; 
218     }
219     $scope.billed_selected = function() {
220         return selected_payment_info().billed;
221     }
222     $scope.paid_selected = function() {
223         return selected_payment_info().paid;
224     }
225     $scope.refunds_available = function() {
226         var amount = 0;
227         angular.forEach($scope.gridControls.allItems(), function(item) {
228             if (item['summary.balance_owed'] < 0) 
229                 amount += item['summary.balance_owed'] * 100;
230         });
231         return -(amount / 100);
232     }
233     $scope.invalid_check_number = function() { 
234         return $scope.payment_type == 'check_payment' && ! $scope.check_number; 
235     }
236
237     // update the item.payment_pending value each time the user
238     // selects different transactions to pay against.
239     $scope.$watch(
240         function() {return $scope.gridControls.selectedItems()},
241         function() {updatePendingColumn()},
242         true
243     );
244
245     // update the item.payment_pending for each (selected) 
246     // transaction any time the user-entered payment amount is modified
247     $scope.$watch('payment_amount', updatePendingColumn);
248
249     // updates the value of the payment_pending column in the grid.
250     // This has to be managed manually since the display value in the grid
251     // is derived from the value on the stored item and not the contents
252     // of our local scope variables.
253     function updatePendingColumn() {
254         // reset all to zero..
255         angular.forEach($scope.gridControls.allItems(), 
256             function(item) {item.payment_pending = 0});
257
258         var payment_amount = $scope.pending_payment();
259
260         var selected = $scope.gridControls.selectedItems();
261         for (var i = 0; i < selected.length; i++) { // for/break
262             var item = selected[i];
263             var owed = Number(item['summary.balance_owed']);
264
265             if (payment_amount > owed) {
266                 // pending payment exceeds balance of current item.
267                 // pay the entire item.
268                 item.payment_pending = owed;
269                 payment_amount -= owed;
270
271             } else {
272                 // balance owed on the current item matches or exceeds
273                 // the pending payment.  Apply the full remainder of
274                 // the payment to this item.. and we're done.
275                 item.payment_pending = payment_amount;
276                 break;
277             }
278         }
279     }
280
281     // builds payment arrays ([xact_id, ammount]) for all transactions
282     // which have a pending payment amount.
283     function generatePayments() {
284         var payments = [];
285         angular.forEach($scope.gridControls.selectedItems(), function(item) {
286             if (item.payment_pending == 0) return;
287             payments.push([item.id, item.payment_pending]);
288         });
289         return payments;
290     }
291
292     function refreshDisplay() {
293         patronSvc.fetchUserStats();
294         billSvc.fetchSummary().then(function(s) {$scope.summary = s});
295         $scope.payment_amount = null;
296         $scope.gridControls.refresh();
297     }
298
299     // generates payments, collects user note if needed, and sends payment
300     // to server.
301     function sendPayment(note) {
302         var make_payments = generatePayments();
303         billSvc.applyPayment(
304             $scope.payment_type, make_payments, note, $scope.check_number)
305         .then(function(payment_ids) {
306
307             if (!$scope.disable_auto_print && $scope.receipt_on_pay) {
308                 printReceipt(
309                     $scope.payment_type, payment_ids, make_payments, note);
310             }
311
312             refreshDisplay();
313         })
314     }
315
316     function printReceipt(type, payment_ids, payments_made, note) {
317         var payment_blobs = [];
318         angular.forEach(payments_made, function(payment) {
319             var xact_id = payment[0];
320
321             // find the original transaction in the grid..
322             var xact = $scope.gridControls.allItems().filter(
323                 function(item) {return item.id == xact_id})[0];
324
325             payment_blobs.push({
326                 xact : egCore.idl.flatToNestedHash(xact),
327                 amount : payment[1]
328             });
329         });
330
331         console.log(js2JSON(payment_blobs[0]));
332
333         // page data not yet refreshed, capture data from current scope
334         var print_data = {
335             payment_type : type,
336             payment_note : note,
337             previous_balance : Number($scope.summary.balance_owed()),
338             payment_total : Number($scope.payment_amount),
339             payment_applied : $scope.pending_payment(),
340             amount_voided : Number($scope.session_voided),
341             change_given : $scope.pending_change(),
342             payments : payment_blobs,
343             current_location : egCore.idl.toHash(
344                 egCore.org.get(egCore.auth.user().ws_ou()))
345         }
346
347         print_data.new_balance = (
348             print_data.previous_balance * 100 - 
349             print_data.payment_applied * 100) / 100;
350
351         for (var i = 0; i < $scope.receipt_count; i++) {
352             egCore.print.print({
353                 context : 'receipt', 
354                 template : 'bill_payment', 
355                 scope : print_data
356             });
357         }
358     }
359
360     $scope.showHistory = function() {
361         $location.path('/circ/patron/' + 
362             patronSvc.current.id() + '/bill_history/transactions');
363     }
364     
365     // For now, only adds billing to first selected item.
366     // Could do batches later if needed
367     $scope.addBilling = function(all) {
368         if (all[0]) {
369             egBilling.showBillDialog({
370                 xact : egCore.idl.flatToNestedHash(all[0]),
371                 patron : $scope.patron()
372             }).then(refreshDisplay);
373         }
374     }
375
376     $scope.showBillDialog = function($event) {
377         egBilling.showBillDialog({
378             patron : $scope.patron()
379         }).then(refreshDisplay);
380     }
381
382     // Select refunds adds all refunds to the existing selection.
383     // It does not /only/ select refunds
384     $scope.selectRefunds = function() {
385         var ids = $scope.gridControls.selectedItems().map(
386             function(i) { return i.id });
387         angular.forEach($scope.gridControls.allItems(), function(item) {
388             if (Number(item['summary.balance_owed']) < 0)
389                 ids.push(item.id);
390         });
391         $scope.gridControls.selectItems(ids);
392     }
393
394     // -------------
395     // determine on initial page load when all of the grid rows should
396     // be selected.
397     var selectOnLoad = true;
398     billSvc.fetchBillSettings().then(function(s) {
399         if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
400             $scope.focus_payment = false; // de-focus the payment box
401             $scope.gridControls.focusRowSelector = true;
402             selectOnLoad = false;
403             // if somehow the grid finishes rendering before our settings 
404             // arrive, manually de-select everything.
405             $scope.gridControls.selectItems([]);
406         }
407         if (s['ui.circ.billing.amount_warn']) {
408             $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
409         }
410         if (s['ui.circ.billing.amount_limit']) {
411             $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
412         }
413         if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
414             $scope.disable_auto_print = Boolean(
415                 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
416             );
417         }
418     });
419
420     $scope.gridControls.allItemsRetrieved = function() {
421         if (selectOnLoad) {
422             selectOnLoad = false; // only for initial controller load.
423             // select all non-refund items
424             $scope.gridControls.selectItems( 
425                 $scope.gridControls.allItems()
426                 .filter(function(i) {return i['summary.balance_owed'] > 0})
427                 .map(function(i){return i.id})
428             );
429         }
430     }
431     // -------------
432
433
434     $scope.printBills = function(selected) {
435         if (!selected.length) return;
436         // bills print receipt assumes nested hashes, but our grid
437         // stores flattener data.  Fetch the selected xacts as
438         // fleshed pcrud objects and hashify.  
439         // (Consider an alternate approach..)
440         var ids = selected.map(function(t){ return t.id });
441         var xacts = [];
442         egCore.pcrud.search('mbt', 
443             {id : ids},
444             {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
445             {authoritative : true}
446         ).then(
447             function() {
448                 egCore.print.print({
449                     context : 'receipt', 
450                     template : 'bills_current', 
451                     scope : {   
452                         transactions : xacts,
453                         current_location : egCore.idl.toHash(
454                             egCore.org.get(egCore.auth.user().ws_ou()))
455                     }
456                 });
457             }, 
458             null, 
459             function(xact) {
460                 xacts.push(egCore.idl.toHash(xact));
461             }
462         );
463     }
464
465     $scope.applyPayment = function() {
466
467         if ($scope.payment_amount > $scope.max_amount ) {
468             egAlertDialog.open(
469                 egCore.strings.PAYMENT_OVER_MAX,
470                 {   max_amount : ''+$scope.max_amount,
471                     ok : function() {
472                         $scope.payment_amount = 0;
473                     }
474                 }
475             );
476             return;
477         }
478
479         if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
480             egConfirmDialog.open(
481                 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
482                 {   payment_amount : ''+$scope.payment_amount,
483                     ok : function() {
484                         $scope.amount_verfied = true;
485                         $scope.applyPayment();
486                     },
487                     cancel : function() {
488                         $scope.payment_amount = 0;
489                     }
490                 }
491             );
492             return;
493         }
494
495         $scope.amount_verfied = false;
496
497         if ($scope.annotate_payment) {
498             egPromptDialog.open(
499                 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
500                 {ok : function(value) {sendPayment(value)}}
501             );
502         } else {
503             sendPayment();
504         }
505     }
506
507     $scope.voidAllBillings = function(items) {
508         angular.forEach(items, function(item) {
509
510             billSvc.fetchBills(item.id).then(function(bills) {
511                 var bill_ids = [];
512                 var cents = 0;
513                 angular.forEach(bills, function(b) {
514                     if (b.voided() != 't') {
515                         cents += b.amount() * 100;
516                         bill_ids.push(b.id())
517                     }
518                 });
519
520                 $scope.session_voided = 
521                     ($scope.session_voided * 100 + cents) / 100;
522
523                 if (bill_ids.length == 0) {
524                     // TODO: warn
525                     return;
526                 }
527
528                 // TODO: alert of pending voiding
529
530                 billSvc.voidBills(bill_ids).then(function() {
531                     refreshDisplay();
532                 });
533             });
534         });
535     }
536
537     // note this is functionally equivalent to selecting a neg. transaction
538     // then clicking Apply Payment -- this just adds a speed bump (ditto
539     // the XUL client).
540     $scope.refundXact = function(all) {
541         var items = all.filter(function(item) {
542             return item['summary.balance_owed'] < 0
543         });
544
545         if (items.length == 0) return;
546
547         var ids = items.map(function(item) {return item.id});
548             
549         egConfirmDialog.open(
550             egCore.strings.CONFIRM_REFUND_PAYMENT, '', 
551             {   xactIds : ''+ids,
552                 ok : function() {
553                     // reset the received payment amount.  this ensures
554                     // we're not mingling payments with refunds.
555                     $scope.payment_amount = 0;
556                 }
557             }
558         );
559     }
560
561     // direct the user to the transaction details page
562     $scope.showFullDetails = function(all) {
563         if (all[0]) 
564             $location.path('/circ/patron/' + 
565                 patronSvc.current.id() + '/bill/' + all[0].id);
566     }
567
568     $scope.activateBill = function(xact) {
569         $scope.showFullDetails([xact]);
570     }
571
572 }])
573
574 /**
575  * Displays details of a single transaction
576  */
577 .controller('XactDetailsCtrl',
578        ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
579 function($scope,  $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
580
581     $scope.initTab('bills', $routeParams.id);
582     var xact_id = $routeParams.xact_id;
583
584     var xactGrid = $scope.xactGridControls = {
585         setQuery : function() { return {xact : xact_id} },
586         setSort : function() { return ['billing_ts'] }
587     }
588
589     var paymentGrid = $scope.paymentGridControls = {
590         setQuery : function() { return {xact : xact_id} },
591         setSort : function() { return ['payment_ts'] }
592     }
593
594     // -- actions
595     $scope.voidBillings = function(bill_list) {
596         var bill_ids = [];
597         angular.forEach(bill_list, function(b) {
598             if (b.voided != 't') bill_ids.push(b.id);
599         });
600
601         if (bill_ids.length == 0) {
602             // TODO: warn
603             return;
604         }
605
606         billSvc.voidBills(bill_ids).then(function() {
607
608             // refresh bills and summary data
609             // note: no need to update payments
610             patronSvc.fetchUserStats();
611
612             egBilling.fetchXact(xact_id).then(function(xact) {
613                 $scope.xact = xact
614             });
615
616             xactGrid.refresh();
617         });
618     }
619
620     // batch-edit billing and payment notes, depending on 'type'
621     function editNotes(selected, type) {
622         var notes = selected.map(function(b){ return b.note }).join(',');
623         var ids = selected.map(function(b){ return b.id });
624
625         // show the note edit prompt
626         egPromptDialog.open(
627             egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
628                 ids : ''+ids,
629                 ok : function(value) {
630
631                     var func = 'updateBillNotes';
632                     if (type == 'payment') func = 'updatePaymentNotes';
633
634                     billSvc[func](value, ids).then(function() {
635                         if (type == 'payment') {
636                             paymentGrid.refresh();
637                         } else {
638                             xactGrid.refresh();
639                         }
640                     });
641                 }
642             }
643         );
644     }
645
646     $scope.editBillNotes = function(selected) {
647         editNotes(selected, 'bill');
648     }
649
650     $scope.editPaymentNotes = function(selected) {
651         editNotes(selected, 'payment');
652     }
653
654     // -- retrieve our data
655     $scope.total_circs = 0; // start with 0 instead of undefined
656     egBilling.fetchXact(xact_id).then(function(xact) {
657         $scope.xact = xact;
658
659         var copyId = xact.circulation().target_copy().id();
660         var circ_count = 0;
661         egCore.pcrud.search('circbyyr',
662             {copy : copyId}, null, {atomic : true})
663         .then(function(counts) {
664             angular.forEach(counts, function(count) {
665                 circ_count += Number(count.count());
666             });
667             $scope.total_circs = circ_count;
668         });
669         // set the title.  only needs to be done on initial page load
670         if (xact.circulation()) {
671             if (xact.circulation().target_copy().call_number().id() == -1) {
672                 $scope.title = xact.circulation().target_copy().dummy_title();
673             } else  {
674                 // TODO: shared bib service?
675                 $scope.title = xact.circulation().target_copy()
676                     .call_number().record().simple_record().title();
677                 $scope.title_id = xact.circulation().target_copy()
678                     .call_number().record().id();
679             }
680         }
681     });
682 }])
683
684
685 .controller('BillHistoryCtrl',
686        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
687 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
688
689     $scope.initTab('bills', $routeParams.id);
690     billSvc.userId = $routeParams.id;
691     $scope.bill_tab = $routeParams.history_tab;
692     $scope.totals = {};
693
694     // link page controller actions defined by sub-controllers here
695     $scope.actions = {};
696
697     var start = new Date(); // now - 1 year
698     start.setFullYear(start.getFullYear() - 1),
699     $scope.dates = {
700         xact_start : start,
701         xact_finish : new Date()
702     }
703
704     $scope.date_range = function() {
705         var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
706         var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
707         var today = new Date().toISOString().replace(/T.*/,'');
708         if (end == today) end = 'now';
709         return [start, end];
710     }
711 }])
712
713
714 .controller('BillXactHistoryCtrl',
715        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
716 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
717
718     // generate a grid query with the current date widget values.
719     function current_grid_query() {
720         return {
721             '-or' : [
722                 {'summary.balance_owed' : {'<>' : 0}},
723                 {'summary.last_payment_ts' : {'<>' : null}}
724             ],
725             xact_start : {between : $scope.date_range()},
726             usr : billSvc.userId
727         }
728     }
729
730     $scope.gridControls = {
731         selectedItems : function(){return []},
732         activateItem : function(item) {
733             $scope.showFullDetails([item]);
734         },
735         // this sets the query on page load
736         setQuery : current_grid_query
737     }
738
739     $scope.actions.apply_date_range = function() {
740         // tells the grid to re-draw itself with the new query
741         $scope.gridControls.setQuery(current_grid_query());
742     }
743
744     // TODO; move me to service
745     function selected_payment_info() {
746         var info = {owed : 0, billed : 0, paid : 0};
747         angular.forEach($scope.gridControls.selectedItems(), function(item) {
748             info.owed   += Number(item['summary.balance_owed']) * 100;
749             info.billed += Number(item['summary.total_owed']) * 100;
750             info.paid   += Number(item['summary.total_paid']) * 100;
751         });
752         info.owed /= 100;
753         info.billed /= 100;
754         info.paid /= 100;
755         return info;
756     }
757
758     $scope.totals.selected_billed = function() {
759         return selected_payment_info().billed;
760     }
761     $scope.totals.selected_paid = function() {
762         return selected_payment_info().paid;
763     }
764
765     $scope.showFullDetails = function(all) {
766         if (all[0]) 
767             $location.path('/circ/patron/' + 
768                 patronSvc.current.id() + '/bill/' + all[0].id);
769     }
770
771     // For now, only adds billing to first selected item.
772     // Could do batches later if needed
773     $scope.addBilling = function(all) {
774         if (all[0]) {
775             egBilling.showBillDialog({
776                 xact : egCore.idl.flatToNestedHash(all[0]),
777                 patron : $scope.patron()
778             }).then(function() { 
779                 $scope.gridControls.refresh();
780                 patronSvc.fetchUserStats();
781             })
782         }
783     }
784
785     $scope.printBills = function(selected) { // FIXME: refactor me
786         if (!selected.length) return;
787         // bills print receipt assumes nested hashes, but our grid
788         // stores flattener data.  Fetch the selected xacts as
789         // fleshed pcrud objects and hashify.  
790         // (Consider an alternate approach..)
791         var ids = selected.map(function(t){ return t.id });
792         var xacts = [];
793         egCore.pcrud.search('mbt', 
794             {id : ids},
795             {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
796             {authoritative : true}
797         ).then(
798             function() {
799                 egCore.print.print({
800                     context : 'receipt', 
801                     template : 'bills_historical', 
802                     scope : {   
803                         transactions : xacts,
804                         current_location : egCore.idl.toHash(
805                             egCore.org.get(egCore.auth.user().ws_ou()))
806                     }
807                 });
808             }, 
809             null, 
810             function(xact) {
811                 xacts.push(egCore.idl.toHash(xact));
812             }
813         );
814     }
815
816
817 }])
818
819 .controller('BillPaymentHistoryCtrl',
820        ['$scope','$q','egCore','patronSvc','billSvc','$location',
821 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
822
823     // generate a grid query with the current date widget values.
824     function current_grid_query() {
825         return {
826             'payment_ts' : {between : $scope.date_range()},
827             'xact.usr' : billSvc.userId
828         }
829     }
830
831     $scope.gridControls = {
832         selectedItems : function(){return []},
833         activateItem : function(item) {
834             $scope.showFullDetails([item]);
835         },
836         setSort : function() {
837             return [{'payment_ts' : 'DESC'}, 'id'];
838         },
839         setQuery : current_grid_query
840     }
841
842     $scope.actions.apply_date_range = function() {
843         // tells the grid to re-draw itself with the new query
844         $scope.gridControls.setQuery(current_grid_query());
845     }
846
847     $scope.showFullDetails = function(all) {
848         if (all[0]) 
849             $location.path('/circ/patron/' + 
850                 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
851     }
852
853     $scope.totals.selected_paid = function() {
854         var paid = 0;
855         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
856             paid += Number(payment.amount) * 100;
857         });
858         return paid / 100;
859     }
860 }])
861
862
863