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