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