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