]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/bills.js
b6447189152a2ed50fad0ae48a2d6e3e53727254
[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',
17             'ui.circ.billing.amount_warn', 'ui.circ.billing.amount_limit',
18             'circ.staff_client.do_not_auto_attempt_print',
19             'circ.disable_patron_credit'
20         ]).then(function(s) {return service.settings = s});
21     }
22
23     // user billing summary
24     service.fetchSummary = function() {
25         return egCore.pcrud.retrieve(
26             'mous', service.userId, {}, {authoritative : true})
27         .then(function(summary) {return service.summary = summary})
28     }
29
30     service.applyPayment = function(
31         type, payments, note, check, cc_args, patron_credit) {
32
33         return egCore.net.request(
34             'open-ils.circ',
35             'open-ils.circ.money.payment',
36             egCore.auth.token(), {
37                 userid : service.userId,
38                 note : note || '', 
39                 payment_type : type,
40                 check_number : check,
41                 payments : payments,
42                 patron_credit : patron_credit,
43                 cc_args : cc_args
44             },
45             patronSvc.current.last_xact_id()
46         ).then(function(resp) {
47             console.debug('payments: ' + js2JSON(resp));
48
49             if (evt = egCore.evt.parse(resp)) {
50                 // Ideally, all scenarios that lead to this alert appearing
51                 // will be avoided by the application logic.  Leave the alert
52                 // in place now to root out any that remain to be addressed.
53                 alert(evt);
54                 return $q.reject(''+evt);
55             }
56
57             var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
58             var msg;
59             switch(type) {
60                 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
61                 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
62                 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
63                 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
64                 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
65                 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
66                 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
67             }
68             egWorkLog.record(
69                 msg,{
70                     'action' : 'paid_bill',
71                     'patron_id' : service.userId,
72                     'total_amount' : total
73                 }
74             );
75
76             // payment API returns the update xact id so we can track it
77             // for future payments without having to refresh the user.
78             patronSvc.current.last_xact_id(resp.last_xact_id);
79
80             // reload patron data if credit balance has changed:
81             if(type === 'credit_payment' || patron_credit){ patronSvc.refreshPrimary(); }
82
83             return resp.payments;
84         });
85     }
86
87     service.fetchBills = function(xact_id) {
88         var bills = [];
89         return egCore.pcrud.search('mb',
90             {xact : xact_id}, null,
91             {authoritative : true}
92         ).then(
93             function() {return bills},
94             null,
95             function(bill) {bills.push(bill); return bill}
96         );
97     }
98
99     service.fetchStatement = function(xact_id) {
100         return egCore.net.request(
101             'open-ils.circ',
102             'open-ils.circ.money.statement.retrieve',
103             egCore.auth.token(), xact_id
104         ).then(function(resp) {
105             if (evt = egCore.evt.parse(resp)) return alert(evt);
106             return resp;
107         });
108     }
109
110     // TODO: no longer needed?
111     service.fetchPayments = function(xact_id) {
112         return egCore.net.request(
113             'open-ils.circ',
114             'open-ils.circ.money.payment.retrieve.all.authoritative',
115             egCore.auth.token(), xact_id
116         );
117     }
118
119     service.voidBills = function(bill_ids) {
120         return egCore.net.requestWithParamList(
121             'open-ils.circ',
122             'open-ils.circ.money.billing.void',
123             [egCore.auth.token()].concat(bill_ids)
124         ).then(function(resp) {
125             if (evt = egCore.evt.parse(resp)) return alert(evt);
126             return resp;
127         });
128     }
129
130     service.adjustBillsToZero = function(bill_ids) {
131         return egCore.net.request(
132             'open-ils.circ',
133             'open-ils.circ.money.billable_xact.adjust_to_zero',
134             egCore.auth.token(),
135             bill_ids
136         ).then(function(resp) {
137             if (evt = egCore.evt.parse(resp)) return alert(evt);
138             return resp;
139         });
140     }
141
142     service.updateBillNotes = function(note, ids) {
143         return egCore.net.requestWithParamList(
144             'open-ils.circ',
145             'open-ils.circ.money.billing.note.edit',
146             [egCore.auth.token(), note].concat(ids)
147         ).then(function(resp) {
148             if (evt = egCore.evt.parse(resp)) return alert(evt);
149             return resp;
150         });
151     }
152
153     service.updatePaymentNotes = function(note, ids) {
154         return egCore.net.requestWithParamList(
155             'open-ils.circ',
156             'open-ils.circ.money.payment.note.edit',
157             [egCore.auth.token(), note].concat(ids)
158         ).then(function(resp) {
159             if (evt = egCore.evt.parse(resp)) return alert(evt);
160             return resp;
161         });
162     }
163
164     return service;
165 }])
166
167
168 /**
169  * Manages Bills
170  */
171 .controller('PatronBillsCtrl',
172        ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
173         'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
174         'egBilling','$uibModal',
175 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
176          egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
177          egBilling , $uibModal) {
178
179     $scope.initTab('bills', $routeParams.id);
180     billSvc.userId = $routeParams.id;
181
182     // set up some defaults
183     $scope.check_number = null;
184     $scope.payment_amount = null;
185     $scope.session_voided = 0;
186     $scope.payment_type = 'cash_payment';
187     $scope.focus_payment = true;
188     $scope.annotate_payment = false;
189     $scope.receipt_count = 1;
190     $scope.receipt_on_pay = { isChecked: false };
191     $scope.convert_to_credit = {isChecked: false};
192     $scope.warn_amount = 1000;
193     $scope.max_amount = 100000;
194     $scope.amount_verified = false;
195     $scope.disable_auto_print = false;
196
197     // check receipt_on_pay setting default persisted
198     egCore.hatch.getItem('circ.bills.receiptonpay')
199                 .then(function(rcptOnPay){
200                     if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
201                 });
202
203     // pre-define list-returning funcs in case we access them
204     // before the grid instantiates
205     $scope.gridControls = {
206         focusRowSelector : false,
207         selectedItems : function(){return []},
208         allItems : function(){return []},
209         itemRetrieved : function(item) {
210             item.payment_pending = 0;
211         },
212         activateItem : function(item) {
213             $scope.showFullDetails([item]);
214         },
215         setQuery : function() {    
216             return {
217                 usr : billSvc.userId, 
218                 xact_finish : null,
219                 'summary.balance_owed' : {'<>' : 0}
220             }
221         }, 
222         setSort : function() {
223             return ['xact_start']; 
224         }
225     }
226     // -------------
227     // Apply coloring to rows based on fines stop reason
228     $scope.colorizeBillsList = {
229         apply: function(item) {
230             if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
231                 if (item['circulation.stop_fines'] == 'LOST') {
232                     return 'lost-row';
233                 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
234                     return 'longoverdue-row';
235                 } else {
236                     return 'overdue-row';
237                 }
238             }
239         }
240     }
241
242     // Status Icon Column definition
243     $scope.statusIconColumn = {
244         isEnabled: true,
245         template: function(item) {
246             var icon = '';
247             if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
248                 if (item['circulation.stop_fines'] == "LOST") {
249                     icon = 'glyphicon-question-sign';
250                 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
251                     icon = 'glyphicon-exclamation-sign';
252                 } else {
253                     icon = 'glyphicon-time';
254                 }
255             }
256             return "<i class='glyphicon " + icon + "'></i>"
257         }
258     }
259
260     billSvc.fetchSummary().then(function(s) {$scope.summary = s});
261
262     // given a payment amount, determines how much of that is applied
263     // to selected transactions and how much is left over (change).
264     function pending_payment_info() {
265         var amt = $scope.payment_amount || 0;
266         if (amt >= $scope.owed_selected()) {
267             return {
268                 payment : $scope.owed_selected(),
269                 change : amt - $scope.owed_selected()
270             }
271         } 
272         return {payment : amt, change : 0};
273     }
274
275     // calculates amount owed, billed, and paid for selected items
276     // TODO: move me to service
277     function selected_payment_info() {
278         var info = {owed : 0, billed : 0, paid : 0};
279         angular.forEach($scope.gridControls.selectedItems(), function(item) {
280             info.owed   += Number(item['summary.balance_owed']) * 100;
281             info.billed += Number(item['summary.total_owed']) * 100;
282             info.paid   += Number(item['summary.total_paid']) * 100;
283         });
284         info.owed /= 100;
285         info.billed /= 100;
286         info.paid /= 100;
287         return info;
288     }
289
290     $scope.pending_payment = function() {
291         return pending_payment_info().payment;
292     }
293     $scope.pending_change = function() {
294         return pending_payment_info().change;
295     }
296     $scope.owed_selected = function() {
297         return selected_payment_info().owed; 
298     }
299     $scope.billed_selected = function() {
300         return selected_payment_info().billed;
301     }
302     $scope.paid_selected = function() {
303         return selected_payment_info().paid;
304     }
305     $scope.refunds_available = function() {
306         var amount = 0;
307         angular.forEach($scope.gridControls.allItems(), function(item) {
308             if (item['summary.balance_owed'] < 0) 
309                 amount += item['summary.balance_owed'] * 100;
310         });
311         return -(amount / 100);
312     }
313     $scope.invalid_check_number = function() { 
314         return $scope.payment_type == 'check_payment' && ! $scope.check_number; 
315     }
316
317     // update the item.payment_pending value each time the user
318     // selects different transactions to pay against.
319     $scope.$watch(
320         function() {return $scope.gridControls.selectedItems()},
321         function() {updatePendingColumn()},
322         true
323     );
324
325     // update the item.payment_pending for each (selected) 
326     // transaction any time the user-entered payment amount is modified
327     $scope.$watch('payment_amount', updatePendingColumn);
328
329     // updates the value of the payment_pending column in the grid.
330     // This has to be managed manually since the display value in the grid
331     // is derived from the value on the stored item and not the contents
332     // of our local scope variables.
333     function updatePendingColumn() {
334         // reset all to zero..
335         angular.forEach($scope.gridControls.allItems(), 
336             function(item) {item.payment_pending = 0});
337
338         var payment_amount = $scope.pending_payment();
339
340         var selected = $scope.gridControls.selectedItems();
341         for (var i = 0; i < selected.length; i++) { // for/break
342             var item = selected[i];
343             var owed = Number(item['summary.balance_owed']);
344
345             if (payment_amount > owed) {
346                 // pending payment exceeds balance of current item.
347                 // pay the entire item.
348                 item.payment_pending = owed;
349                 payment_amount -= owed;
350
351             } else {
352                 // balance owed on the current item matches or exceeds
353                 // the pending payment.  Apply the full remainder of
354                 // the payment to this item.. and we're done.
355                 item.payment_pending = payment_amount;
356                 break;
357             }
358         }
359     }
360
361     // builds payment arrays ([xact_id, ammount]) for all transactions
362     // which have a pending payment amount.
363     function generatePayments() {
364         var payments = [];
365         angular.forEach($scope.gridControls.selectedItems(), function(item) {
366             if (item.payment_pending == 0) return;
367             payments.push([item.id, item.payment_pending]);
368         });
369         return payments;
370     }
371
372     function refreshDisplay() {
373         patronSvc.fetchUserStats();
374         billSvc.fetchSummary().then(function(s) {$scope.summary = s});
375         $scope.payment_amount = null;
376         $scope.gridControls.refresh();
377     }
378
379     // generates payments, collects user note if needed, and sends payment
380     // to server.
381     function sendPayment(note, cc_args) {
382         $scope.applyingPayment = true;
383         var make_payments = generatePayments();
384         var patron_credit = $scope.convert_to_credit.isChecked ?
385             $scope.pending_change() : 0; 
386         billSvc.applyPayment($scope.payment_type, 
387             make_payments, note, $scope.check_number, cc_args, patron_credit)
388         .then(
389             function(payment_ids) {
390
391                 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
392                     printReceipt(
393                         $scope.payment_type, payment_ids, make_payments, note);
394                 }
395
396                 refreshDisplay();
397             },
398             function(msg) {
399                 console.error('Payment was rejected: ' + msg);
400             }
401         )
402         .finally(function() { $scope.applyingPayment = false; })
403     }
404
405     $scope.onReceiptOnPayChanged = function(){
406         egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
407     }
408
409     function printReceipt(type, payment_ids, payments_made, note) {
410         var payment_blobs = [];
411         var cusr = patronSvc.current;
412
413         angular.forEach(payments_made, function(payment) {
414             var xact_id = payment[0];
415
416             // find the original transaction in the grid..
417             var xact = $scope.gridControls.allItems().filter(
418                 function(item) {return item.id == xact_id})[0];
419
420             payment_blobs.push({
421                 xact : egCore.idl.flatToNestedHash(xact),
422                 amount : payment[1]
423             });
424         });
425
426         console.log(js2JSON(payment_blobs[0]));
427
428         // page data not yet refreshed, capture data from current scope
429         var print_data = {
430             payment_type : type,
431             payment_note : note,
432             previous_balance : Number($scope.summary.balance_owed()),
433             payment_total : Number($scope.payment_amount),
434             payment_applied : $scope.pending_payment(),
435             amount_voided : Number($scope.session_voided),
436             change_given : $scope.pending_change(),
437             payments : payment_blobs,
438             current_location : egCore.idl.toHash(
439                 egCore.org.get(egCore.auth.user().ws_ou()))
440         };
441
442         // Not a good idea to use patron_stats.fines for this; it's out of date
443         print_data.patron = {
444             prefix : cusr.prefix(),
445             first_given_name : cusr.first_given_name(),
446             second_given_name : cusr.second_given_name(),
447             family_name : cusr.family_name(),
448             suffix : cusr.suffix(),
449             card : { barcode : cusr.card().barcode() },
450             expire_date : cusr.expire_date(),
451             alias : cusr.alias(),
452             has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
453             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
454         };
455
456         print_data.new_balance = (
457             print_data.previous_balance * 100 - 
458             print_data.payment_applied * 100) / 100;
459
460         for (var i = 0; i < $scope.receipt_count; i++) {
461             egCore.print.print({
462                 context : 'receipt', 
463                 template : 'bill_payment', 
464                 scope : print_data
465             });
466         }
467     }
468
469     $scope.showHistory = function() {
470         $location.path('/circ/patron/' + 
471             patronSvc.current.id() + '/bill_history/transactions');
472     }
473     
474     // For now, only adds billing to first selected item.
475     // Could do batches later if needed
476     $scope.addBilling = function(all) {
477         if (all[0]) {
478             egBilling.showBillDialog({
479                 xact : egCore.idl.flatToNestedHash(all[0]),
480                 patron : $scope.patron()
481             }).then(refreshDisplay);
482         }
483     }
484
485     $scope.showBillDialog = function($event) {
486         egBilling.showBillDialog({
487             patron : $scope.patron()
488         }).then(refreshDisplay);
489     }
490
491     // Select refunds adds all refunds to the existing selection.
492     // It does not /only/ select refunds
493     $scope.selectRefunds = function() {
494         var ids = $scope.gridControls.selectedItems().map(
495             function(i) { return i.id });
496         angular.forEach($scope.gridControls.allItems(), function(item) {
497             if (Number(item['summary.balance_owed']) < 0)
498                 ids.push(item.id);
499         });
500         $scope.gridControls.selectItems(ids);
501     }
502
503     // -------------
504     // determine on initial page load when all of the grid rows should
505     // be selected.
506     var selectOnLoad = true;
507     billSvc.fetchBillSettings().then(function(s) {
508         if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
509             $scope.focus_payment = false; // de-focus the payment box
510             $scope.gridControls.focusRowSelector = true;
511             selectOnLoad = false;
512             // if somehow the grid finishes rendering before our settings 
513             // arrive, manually de-select everything.
514             $scope.gridControls.selectItems([]);
515         }
516         if (s['ui.circ.billing.amount_warn']) {
517             $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
518         }
519         if (s['ui.circ.billing.amount_limit']) {
520             $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
521         }
522         if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
523             $scope.disable_auto_print = Boolean(
524                 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
525             );
526         }
527         if (s['circ.disable_patron_credit']) {
528             $scope.disablePatronCredit = true;
529         }
530     });
531
532     $scope.gridControls.allItemsRetrieved = function() {
533         if (selectOnLoad) {
534             selectOnLoad = false; // only for initial controller load.
535             // select all non-refund items
536             $scope.gridControls.selectItems( 
537                 $scope.gridControls.allItems()
538                 .filter(function(i) {return i['summary.balance_owed'] > 0})
539                 .map(function(i){return i.id})
540             );
541         }
542     }
543     // -------------
544
545
546     $scope.printBills = function(selected) {
547         if (!selected.length) return;
548         // bills print receipt assumes nested hashes, but our grid
549         // stores flattener data.  Fetch the selected xacts as
550         // fleshed pcrud objects and hashify.  
551         // (Consider an alternate approach..)
552         var ids = selected.map(function(t){ return t.id });
553         var xacts = [];
554         egCore.pcrud.search('mbt', 
555             {id : ids},
556             {flesh : 5, flesh_fields : {
557                 'mbt' : ['summary', 'circulation'],
558                 'circ' : ['target_copy'],
559                 'acp' : ['call_number'],
560                 'acn' : ['record'],
561                 'bre' : ['simple_record']
562                 }
563             },
564             {authoritative : true}
565         ).then(
566             function() {
567                 var cusr = patronSvc.current;
568                 egCore.print.print({
569                     context : 'receipt', 
570                     template : 'bills_current', 
571                     scope : {   
572                         transactions : xacts,
573                         current_location : egCore.idl.toHash(
574                             egCore.org.get(egCore.auth.user().ws_ou())),
575                         patron : {
576                             prefix : cusr.prefix(),
577                             first_given_name : cusr.first_given_name(),
578                             second_given_name : cusr.second_given_name(),
579                             family_name : cusr.family_name(),
580                             suffix : cusr.suffix(),
581                             card : { barcode : cusr.card().barcode() },
582                             expire_date : cusr.expire_date(),
583                             alias : cusr.alias(),
584                             has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
585                             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
586                         }
587                     }
588                 });
589             }, 
590             null, 
591             function(xact) {
592                 newXact = {
593                     billing_total : xact.billing_total(),
594                     billings : xact.billings(),
595                     grocery : xact.grocery(),
596                     id : xact.id(),
597                     payment_total : xact.payment_total(),
598                     payments : xact.payments(),
599                     summary : egCore.idl.toHash(xact.summary()),
600                     unrecovered : xact.unrecovered(),
601                     xact_finish : xact.xact_finish(),
602                     xact_start : xact.xact_start(),
603                 }
604                 if (xact.circulation()) {
605                     newXact.copy_barcode = xact.circulation().target_copy().barcode(),
606                     newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
607                 }
608                 xacts.push(newXact);
609             }
610         );
611     }
612
613     $scope.applyPayment = function() {
614
615         if ($scope.payment_amount > $scope.max_amount ) {
616             egAlertDialog.open(
617                 egCore.strings.PAYMENT_OVER_MAX,
618                 {   max_amount : ''+$scope.max_amount,
619                     ok : function() {
620                         $scope.payment_amount = 0;
621                     }
622                 }
623             );
624             return;
625         }
626
627         verify_payment_amount().then(
628             function() { // amount confirmed
629                 add_payment_note().then(function(pay_note) {
630                     add_cc_args().then(function(cc_args) {
631                         var note_text = pay_note ? pay_note.value || '' : null;
632                         sendPayment(note_text, cc_args);
633                     })
634                 });
635             },
636             function() { // amount rejected
637                 console.warn('payment amount rejected');
638                 $scope.payment_amount = 0;
639             }
640         );
641     }
642
643     function verify_payment_amount() {
644         if ($scope.payment_amount < $scope.warn_amount)
645             return $q.when();
646
647         return egConfirmDialog.open(
648             egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, 
649             egCore.strings.PAYMENT_WARN_AMOUNT,
650             {payment_amount : ''+$scope.payment_amount}
651         ).result;
652     }
653
654     function add_payment_note() {
655         if (!$scope.annotate_payment) return $q.when();
656         return egPromptDialog.open(
657             egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
658     }
659
660     function add_cc_args() {
661         if ($scope.payment_type != 'credit_card_payment') 
662             return $q.when();
663
664         return $uibModal.open({
665             templateUrl : './circ/patron/t_cc_payment_dialog',
666             backdrop: 'static',
667             controller : [
668                         '$scope','$uibModalInstance',
669                 function($scope , $uibModalInstance) {
670
671                     $scope.context = {
672                         cc : {
673                             where_process : '1', // internal=1 ; external=0
674                             type : 'VISA', // external only
675                             billing_first : patronSvc.current.first_given_name(),
676                             billing_last : patronSvc.current.family_name()
677                         }
678                     }
679
680                     var addr = patronSvc.current.billing_address() ||
681                         patronSvc.current.mailing_address();
682                     if (addr) {
683                         var cc = $scope.context.cc;
684                         cc.billing_address = addr.street1() + 
685                             (addr.street2() ? ' ' + addr.street2() : '');
686                         cc.billing_city = addr.city();
687                         cc.billing_state = addr.state();
688                         cc.billing_zip = addr.post_code();
689                     }
690
691                     $scope.ok = function() {
692                         // CC payment form is not a <form>, 
693                         // so apply validation manually.
694                         if ( $scope.context.cc.where_process == 0 && 
695                             !$scope.context.cc.approval_code)
696                             return;
697
698                         $uibModalInstance.close($scope.context.cc);
699                     }
700
701                     $scope.cancel = function() {
702                         $uibModalInstance.dismiss();
703                     }
704                 }
705             ]
706         }).result;
707     }
708
709     $scope.voidAllBillings = function(items) {
710         var promises = [];
711         var bill_ids = [];
712         var cents = 0;
713         angular.forEach(items, function(item) {
714             promises.push(
715                 billSvc.fetchBills(item.id).then(function(bills) {
716                     angular.forEach(bills, function(b) {
717                         if (b.voided() != 't') {
718                             cents += b.amount() * 100;
719                             bill_ids.push(b.id())
720                         }
721                     });
722
723                     if (bill_ids.length == 0) {
724                         // TODO: warn
725                         return;
726                     }
727
728                 })
729             );
730         });
731
732         $q.all(promises).then(function(){
733             egCore.audio.play('warning.circ.void_billings_confirmation');
734             egConfirmDialog.open(
735                 egCore.strings.CONFIRM_VOID_BILLINGS, '', 
736                 {   billIds : ''+bill_ids,
737                     amount : ''+(cents/100),
738                     ok : function() {
739                         billSvc.voidBills(bill_ids).then(function() {
740                             $scope.session_voided = 
741                                 ($scope.session_voided * 100 + cents) / 100;
742                             refreshDisplay();
743                         });
744                     }
745                 }
746             );
747         });
748     }
749
750     $scope.adjustToZero = function(items) {
751         if (items.length == 0) return;
752
753         var ids = items.map(function(item) {return item.id});
754
755         egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
756         egConfirmDialog.open(
757             egCore.strings.CONFIRM_ADJUST_TO_ZERO, '', 
758             {   xactIds : ''+ids,
759                 ok : function() {
760                     billSvc.adjustBillsToZero(ids).then(function() {
761                         refreshDisplay();
762                     });
763                 }
764             }
765         );
766
767     }
768
769     // note this is functionally equivalent to selecting a neg. transaction
770     // then clicking Apply Payment -- this just adds a speed bump (ditto
771     // the XUL client).
772     $scope.refundXact = function(all) {
773         var items = all.filter(function(item) {
774             return item['summary.balance_owed'] < 0
775         });
776
777         if (items.length == 0) return;
778
779         var ids = items.map(function(item) {return item.id});
780
781         egCore.audio.play('warning.circ.refund_confirmation');
782         egConfirmDialog.open(
783             egCore.strings.CONFIRM_REFUND_PAYMENT, '', 
784             {   xactIds : ''+ids,
785                 ok : function() {
786                     // reset the received payment amount.  this ensures
787                     // we're not mingling payments with refunds.
788                     $scope.payment_amount = 0;
789                 }
790             }
791         );
792     }
793
794     // direct the user to the transaction details page
795     $scope.showFullDetails = function(all) {
796         if (all[0]) 
797             $location.path('/circ/patron/' + 
798                 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
799     }
800
801     $scope.activateBill = function(xact) {
802         $scope.showFullDetails([xact]);
803     }
804
805 }])
806
807 /**
808  * Displays details of a single transaction
809  */
810 .controller('XactDetailsCtrl',
811        ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
812 function($scope,  $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
813
814     $scope.initTab('bills', $routeParams.id);
815     var xact_id = $routeParams.xact_id;
816     $scope.xact_tab = $routeParams.xact_tab;
817
818     var xactGrid = $scope.xactGridControls = {
819         setQuery : function() { return {xact : xact_id} },
820         setSort : function() { return ['billing_ts'] }
821     }
822
823     var paymentGrid = $scope.paymentGridControls = {
824         setQuery : function() { return {xact : xact_id} },
825         setSort : function() { return ['payment_ts'] }
826     }
827
828     // -- actions
829     $scope.voidBillings = function(bill_list) {
830         var bill_ids = [];
831         var cents = 0;
832         angular.forEach(bill_list, function(b) {
833             if (b.voided != 't') {
834                 cents += b.amount * 100;
835                 bill_ids.push(b.id)
836             }
837         });
838
839         if (bill_ids.length == 0) {
840             // TODO: warn
841             return;
842         }
843
844         egCore.audio.play('warning.circ.void_billings_confirmation');
845         egConfirmDialog.open(
846             egCore.strings.CONFIRM_VOID_BILLINGS, '', 
847             {   billIds : ''+bill_ids,
848                 amount : ''+(cents/100),
849                 ok : function() {
850                     billSvc.voidBills(bill_ids).then(function() {
851                         // TODO? $scope.session_voided = ...
852
853                         // refresh bills and summary data
854                         // note: no need to update payments
855                         patronSvc.fetchUserStats();
856
857                         egBilling.fetchXact(xact_id).then(function(xact) {
858                             $scope.xact = xact
859                         });
860
861                         xactGrid.refresh();
862                     });
863                 }
864             }
865         );
866     }
867
868     // batch-edit billing and payment notes, depending on 'type'
869     function editNotes(selected, type) {
870         var notes = selected.map(function(b){ return b.note }).join(',');
871         var ids = selected.map(function(b){ return b.id });
872
873         // show the note edit prompt
874         egPromptDialog.open(
875             egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
876                 ids : ''+ids,
877                 ok : function(value) {
878
879                     var func = 'updateBillNotes';
880                     if (type == 'payment') func = 'updatePaymentNotes';
881
882                     billSvc[func](value, ids).then(function() {
883                         if (type == 'payment') {
884                             paymentGrid.refresh();
885                         } else {
886                             xactGrid.refresh();
887                         }
888                     });
889                 }
890             }
891         );
892     }
893
894     $scope.editBillNotes = function(selected) {
895         editNotes(selected, 'bill');
896     }
897
898     $scope.editPaymentNotes = function(selected) {
899         editNotes(selected, 'payment');
900     }
901
902     // -- retrieve our data
903     if ($scope.xact_tab == 'statement') {
904         //fetch combined billing statement data
905         billSvc.fetchStatement(xact_id).then(function(statement) {
906             //console.log(statement);
907             $scope.statement_data = statement;
908         });
909     }
910     $scope.total_circs = 0; // start with 0 instead of undefined
911     egBilling.fetchXact(xact_id).then(function(xact) {
912         $scope.xact = xact;
913
914         var copyId = xact.circulation().target_copy().id();
915         var circ_count = 0;
916         egCore.pcrud.search('circbyyr',
917             {copy : copyId}, null, {atomic : true})
918         .then(function(counts) {
919             angular.forEach(counts, function(count) {
920                 circ_count += Number(count.count());
921             });
922             $scope.total_circs = circ_count;
923         });
924         // set the title.  only needs to be done on initial page load
925         if (xact.circulation()) {
926             if (xact.circulation().target_copy().call_number().id() == -1) {
927                 $scope.title = xact.circulation().target_copy().dummy_title();
928             } else  {
929                 // TODO: shared bib service?
930                 $scope.title = xact.circulation().target_copy()
931                     .call_number().record().simple_record().title();
932                 $scope.title_id = xact.circulation().target_copy()
933                     .call_number().record().id();
934             }
935         }
936     });
937 }])
938
939
940 .controller('BillHistoryCtrl',
941        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
942 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
943
944     $scope.initTab('bills', $routeParams.id);
945     billSvc.userId = $routeParams.id;
946     $scope.bill_tab = $routeParams.history_tab;
947     $scope.totals = {};
948
949     // link page controller actions defined by sub-controllers here
950     $scope.actions = {};
951
952     var start = new Date(); // now - 1 year
953     start.setFullYear(start.getFullYear() - 1),
954     $scope.dates = {
955         xact_start : start,
956         xact_finish : new Date()
957     }
958
959     $scope.date_range = function() {
960         var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
961         var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
962         var today = new Date().toISOString().replace(/T.*/,'');
963         if (end == today) end = 'now';
964         return [start, end];
965     }
966 }])
967
968
969 .controller('BillXactHistoryCtrl',
970        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
971 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
972
973     // generate a grid query with the current date widget values.
974     function current_grid_query() {
975         return {
976             '-or' : [
977                 {'summary.balance_owed' : {'<>' : 0}},
978                 {'summary.last_payment_ts' : {'<>' : null}}
979             ],
980             xact_start : {between : $scope.date_range()},
981             usr : billSvc.userId
982         }
983     }
984
985     $scope.gridControls = {
986         selectedItems : function(){return []},
987         activateItem : function(item) {
988             $scope.showFullDetails([item]);
989         },
990         // this sets the query on page load
991         setQuery : current_grid_query
992     }
993
994     $scope.actions.apply_date_range = function() {
995         // tells the grid to re-draw itself with the new query
996         $scope.gridControls.setQuery(current_grid_query());
997     }
998
999     // TODO; move me to service
1000     function selected_payment_info() {
1001         var info = {owed : 0, billed : 0, paid : 0};
1002         angular.forEach($scope.gridControls.selectedItems(), function(item) {
1003             info.owed   += Number(item['summary.balance_owed']) * 100;
1004             info.billed += Number(item['summary.total_owed']) * 100;
1005             info.paid   += Number(item['summary.total_paid']) * 100;
1006         });
1007         info.owed /= 100;
1008         info.billed /= 100;
1009         info.paid /= 100;
1010         return info;
1011     }
1012
1013     $scope.totals.selected_billed = function() {
1014         return selected_payment_info().billed;
1015     }
1016     $scope.totals.selected_paid = function() {
1017         return selected_payment_info().paid;
1018     }
1019
1020     $scope.showFullDetails = function(all) {
1021         if (all[0]) 
1022             $location.path('/circ/patron/' + 
1023                 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1024     }
1025
1026     // For now, only adds billing to first selected item.
1027     // Could do batches later if needed
1028     $scope.addBilling = function(all) {
1029         if (all[0]) {
1030             egBilling.showBillDialog({
1031                 xact : egCore.idl.flatToNestedHash(all[0]),
1032                 patron : $scope.patron()
1033             }).then(function() { 
1034                 $scope.gridControls.refresh();
1035                 patronSvc.fetchUserStats();
1036             })
1037         }
1038     }
1039
1040     $scope.printBills = function(selected) { // FIXME: refactor me
1041         if (!selected.length) return;
1042         // bills print receipt assumes nested hashes, but our grid
1043         // stores flattener data.  Fetch the selected xacts as
1044         // fleshed pcrud objects and hashify.  
1045         // (Consider an alternate approach..)
1046         var ids = selected.map(function(t){ return t.id });
1047         var xacts = [];
1048         egCore.pcrud.search('mbt', 
1049             {id : ids},
1050             {flesh : 5, flesh_fields : {
1051                 'mbt' : ['summary', 'circulation'],
1052                 'circ' : ['target_copy'],
1053                 'acp' : ['call_number'],
1054                 'acn' : ['record'],
1055                 'bre' : ['simple_record']
1056                 }
1057             },
1058             {authoritative : true}
1059         ).then(
1060             function() {
1061                 var cusr = patronSvc.current;
1062                 egCore.print.print({
1063                     context : 'receipt', 
1064                     template : 'bills_historical', 
1065                     scope : {   
1066                         transactions : xacts,
1067                         current_location : egCore.idl.toHash(
1068                             egCore.org.get(egCore.auth.user().ws_ou())),
1069                         patron : {
1070                             prefix : cusr.prefix(),
1071                             first_given_name : cusr.first_given_name(),
1072                             second_given_name : cusr.second_given_name(),
1073                             family_name : cusr.family_name(),
1074                             suffix : cusr.suffix(),
1075                             card : { barcode : cusr.card().barcode() },
1076                             expire_date : cusr.expire_date(),
1077                             alias : cusr.alias(),
1078                             has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1079                             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1080                         }
1081                     }
1082                 });
1083             }, 
1084             null, 
1085             function(xact) {
1086                 newXact = {
1087                     billing_total : xact.billing_total(),
1088                     billings : xact.billings(),
1089                     grocery : xact.grocery(),
1090                     id : xact.id(),
1091                     payment_total : xact.payment_total(),
1092                     payments : xact.payments(),
1093                     summary : egCore.idl.toHash(xact.summary()),
1094                     unrecovered : xact.unrecovered(),
1095                     xact_finish : xact.xact_finish(),
1096                     xact_start : xact.xact_start(),
1097                 }
1098                 if (xact.circulation()) {
1099                     newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1100                     newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1101                 }
1102                 xacts.push(newXact);
1103             }
1104         );
1105     }
1106 }])
1107
1108 .controller('BillPaymentHistoryCtrl',
1109        ['$scope','$q','egCore','patronSvc','billSvc','$location',
1110 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
1111
1112     // generate a grid query with the current date widget values.
1113     function current_grid_query() {
1114         return {
1115             'payment_ts' : {between : $scope.date_range()},
1116             'xact.usr' : billSvc.userId
1117         }
1118     }
1119
1120     $scope.gridControls = {
1121         selectedItems : function(){return []},
1122         activateItem : function(item) {
1123             $scope.showFullDetails([item]);
1124         },
1125         setSort : function() {
1126             return [{'payment_ts' : 'DESC'}, 'id'];
1127         },
1128         setQuery : current_grid_query
1129     }
1130
1131     $scope.actions.apply_date_range = function() {
1132         // tells the grid to re-draw itself with the new query
1133         $scope.gridControls.setQuery(current_grid_query());
1134     }
1135
1136     $scope.showFullDetails = function(all) {
1137         if (all[0]) 
1138             $location.path('/circ/patron/' + 
1139                 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1140     }
1141
1142     $scope.totals.selected_paid = function() {
1143         var paid = 0;
1144         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1145             paid += Number(payment.amount) * 100;
1146         });
1147         return paid / 100;
1148     }
1149 }])
1150
1151
1152