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