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