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