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