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