]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/bills.js
LP#1772955: Only include xacts with balance in summary
[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
399                 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
400                     printReceipt(
401                         $scope.payment_type, payment_ids, make_payments, note);
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) {
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             previous_balance : Number($scope.summary.balance_owed()),
445             payment_total : Number($scope.payment_amount),
446             payment_applied : $scope.pending_payment(),
447             amount_voided : Number($scope.session_voided),
448             change_given : $scope.pending_change(),
449             payments : payment_blobs,
450             current_location : egCore.idl.toHash(
451                 egCore.org.get(egCore.auth.user().ws_ou()))
452         };
453
454         // Not a good idea to use patron_stats.fines for this; it's out of date
455         print_data.patron = {
456             prefix : cusr.prefix(),
457             first_given_name : cusr.first_given_name(),
458             second_given_name : cusr.second_given_name(),
459             family_name : cusr.family_name(),
460             suffix : cusr.suffix(),
461             pref_prefix : cusr.pref_prefix(),
462             pref_first_given_name : cusr.pref_first_given_name(),
463             pref_second_given_name : cusr.pref_second_given_name(),
464             pref_family_name : cusr.pref_family_name(),
465             pref_suffix : cusr.pref_suffix(),
466             card : { barcode : cusr.card().barcode() },
467             expire_date : cusr.expire_date(),
468             alias : cusr.alias(),
469             has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
470             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
471         };
472
473         print_data.new_balance = (
474             print_data.previous_balance * 100 - 
475             print_data.payment_applied * 100) / 100;
476
477         for (var i = 0; i < $scope.receipt_count; i++) {
478             egCore.print.print({
479                 context : 'receipt', 
480                 template : 'bill_payment', 
481                 scope : print_data
482             });
483         }
484     }
485
486     $scope.showHistory = function() {
487         $location.path('/circ/patron/' + 
488             patronSvc.current.id() + '/bill_history/transactions');
489     }
490     
491     // For now, only adds billing to first selected item.
492     // Could do batches later if needed
493     $scope.addBilling = function(all) {
494         if (all[0]) {
495             egBilling.showBillDialog({
496                 xact : egCore.idl.flatToNestedHash(all[0]),
497                 patron : $scope.patron()
498             }).then(refreshDisplay);
499         }
500     }
501
502     $scope.showBillDialog = function($event) {
503         egBilling.showBillDialog({
504             patron : $scope.patron()
505         }).then(refreshDisplay);
506     }
507
508     // Select refunds adds all refunds to the existing selection.
509     // It does not /only/ select refunds
510     $scope.selectRefunds = function() {
511         var ids = $scope.gridControls.selectedItems().map(
512             function(i) { return i.id });
513         angular.forEach($scope.gridControls.allItems(), function(item) {
514             if (Number(item['summary.balance_owed']) < 0)
515                 ids.push(item.id);
516         });
517         $scope.gridControls.selectItems(ids);
518     }
519
520     // -------------
521     // determine on initial page load when all of the grid rows should
522     // be selected.
523     var selectOnLoad = true;
524     billSvc.fetchBillSettings().then(function(s) {
525         if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
526             $scope.focus_payment = false; // de-focus the payment box
527             $scope.gridControls.focusRowSelector = true;
528             selectOnLoad = false;
529             // if somehow the grid finishes rendering before our settings 
530             // arrive, manually de-select everything.
531             $scope.gridControls.selectItems([]);
532         }
533         if (s['ui.circ.billing.amount_warn']) {
534             $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
535         }
536         if (s['ui.circ.billing.amount_limit']) {
537             $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
538         }
539         if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
540             $scope.disable_auto_print = Boolean(
541                 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
542             );
543         }
544         if (s['circ.disable_patron_credit']) {
545             $scope.disablePatronCredit = true;
546         }
547         if (!s['credit.processor.default']) {
548             // If we don't have a CC processor, we should disable the "internal" CC form
549             $scope.disableCreditCardForm = true;
550         } else {
551             // Stripe isn't supported in the staff client currently, so disable here too
552             $scope.disableCreditCardForm = (s['credit.processor.default'] == 'Stripe');
553         }
554     });
555
556     $scope.gridControls.allItemsRetrieved = function() {
557         if (selectOnLoad) {
558             selectOnLoad = false; // only for initial controller load.
559             // select all non-refund items
560             $scope.gridControls.selectItems( 
561                 $scope.gridControls.allItems()
562                 .filter(function(i) {return i['summary.balance_owed'] > 0})
563                 .map(function(i){return i.id})
564             );
565         }
566     }
567     // -------------
568
569
570     $scope.printBills = function(selected) {
571         if (!selected.length) return;
572         // bills print receipt assumes nested hashes, but our grid
573         // stores flattener data.  Fetch the selected xacts as
574         // fleshed pcrud objects and hashify.  
575         // (Consider an alternate approach..)
576         var ids = selected.map(function(t){ return t.id });
577         var xacts = [];
578         egCore.pcrud.search('mbt', 
579             {id : ids},
580             {flesh : 5, flesh_fields : {
581                 'mbt' : ['summary', 'circulation'],
582                 'circ' : ['target_copy'],
583                 'acp' : ['call_number'],
584                 'acn' : ['record','owning_lib','prefix','suffix'],
585                 'bre' : ['simple_record']
586                 }
587             },
588             {authoritative : true}
589         ).then(
590             function() {
591                 var cusr = patronSvc.current;
592                 egCore.print.print({
593                     context : 'receipt', 
594                     template : 'bills_current', 
595                     scope : {   
596                         transactions : xacts,
597                         current_location : egCore.idl.toHash(
598                             egCore.org.get(egCore.auth.user().ws_ou())),
599                         patron : {
600                             prefix : cusr.prefix(),
601                             first_given_name : cusr.first_given_name(),
602                             second_given_name : cusr.second_given_name(),
603                             family_name : cusr.family_name(),
604                             suffix : cusr.suffix(),
605                             pref_prefix : cusr.pref_prefix(),
606                             pref_first_given_name : cusr.pref_first_given_name(),
607                             pref_second_given_name : cusr.pref_second_given_name(),
608                             pref_family_name : cusr.pref_family_name(),
609                             pref_suffix : cusr.pref_suffix(),
610                             card : { barcode : cusr.card().barcode() },
611                             expire_date : cusr.expire_date(),
612                             alias : cusr.alias(),
613                             has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
614                             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
615                         }
616                     }
617                 });
618             }, 
619             null, 
620             function(xact) {
621                 newXact = {
622                     billing_total : xact.billing_total(),
623                     billings : xact.billings(),
624                     grocery : xact.grocery(),
625                     id : xact.id(),
626                     payment_total : xact.payment_total(),
627                     payments : xact.payments(),
628                     summary : egCore.idl.toHash(xact.summary()),
629                     unrecovered : xact.unrecovered(),
630                     xact_finish : xact.xact_finish(),
631                     xact_start : xact.xact_start(),
632                 }
633                 if (xact.circulation()) {
634                     newXact.copy_barcode = xact.circulation().target_copy().barcode();
635                     newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
636                     newXact.call_number = {
637                         label : xact.circulation().target_copy().call_number().label(),
638                                     prefix : xact.circulation().target_copy().call_number().prefix().label(),
639                                     suffix : xact.circulation().target_copy().call_number().suffix().label(),
640                         owning_lib : {
641                             name : xact.circulation().target_copy().call_number().owning_lib().name(),
642                             shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
643                         }
644                     }
645                 }
646                 xacts.push(newXact);
647             }
648         );
649     }
650
651     $scope.applyPayment = function() {
652
653         if ($scope.payment_amount > $scope.max_amount ) {
654             egAlertDialog.open(
655                 egCore.strings.PAYMENT_OVER_MAX,
656                 {   max_amount : ''+$scope.max_amount,
657                     ok : function() {
658                         $scope.payment_amount = 0;
659                     }
660                 }
661             );
662             return;
663         }
664
665         verify_payment_amount().then(
666             function() { // amount confirmed
667                 add_payment_note().then(function(pay_note) {
668                     add_cc_args().then(function(cc_args) {
669                         var note_text = pay_note ? pay_note.value || '' : null;
670                         sendPayment(note_text, cc_args);
671                     })
672                 });
673             },
674             function() { // amount rejected
675                 console.warn('payment amount rejected');
676                 $scope.payment_amount = 0;
677             }
678         );
679     }
680
681     function verify_payment_amount() {
682         if ($scope.payment_amount < $scope.warn_amount)
683             return $q.when();
684
685         return egConfirmDialog.open(
686             egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, 
687             egCore.strings.PAYMENT_WARN_AMOUNT,
688             {payment_amount : ''+$scope.payment_amount}
689         ).result;
690     }
691
692     function add_payment_note() {
693         if (!$scope.annotate_payment) return $q.when();
694         return egPromptDialog.open(
695             egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
696     }
697
698     function add_cc_args() {
699         if ($scope.payment_type != 'credit_card_payment') 
700             return $q.when();
701
702         var disableCreditCardForm = $scope.disableCreditCardForm;
703
704         return $uibModal.open({
705             templateUrl : './circ/patron/t_cc_payment_dialog',
706             backdrop: 'static',
707             controller : [
708                         '$scope','$uibModalInstance',
709                 function($scope , $uibModalInstance) {
710
711                     $scope.context = {
712                         cc : {
713                             where_process : disableCreditCardForm ? '0' : '1', // internal=1 ; external=0
714                             disable_internal : disableCreditCardForm,
715                             type : 'VISA', // external only
716                             billing_first : patronSvc.current.first_given_name(),
717                             billing_last : patronSvc.current.family_name()
718                         }
719                     }
720
721                     var addr = patronSvc.current.billing_address() ||
722                         patronSvc.current.mailing_address();
723                     if (addr) {
724                         var cc = $scope.context.cc;
725                         cc.billing_address = addr.street1() + 
726                             (addr.street2() ? ' ' + addr.street2() : '');
727                         cc.billing_city = addr.city();
728                         cc.billing_state = addr.state();
729                         cc.billing_zip = addr.post_code();
730                     }
731
732                     $scope.ok = function() {
733                         // CC payment form is not a <form>, 
734                         // so apply validation manually.
735                         if ( $scope.context.cc.where_process == 0 && 
736                             !$scope.context.cc.approval_code)
737                             return;
738
739                         $uibModalInstance.close($scope.context.cc);
740                     }
741
742                     $scope.cancel = function() {
743                         $uibModalInstance.dismiss();
744                     }
745                 }
746             ]
747         }).result;
748     }
749
750     $scope.voidAllBillings = function(items) {
751         var promises = [];
752         var bill_ids = [];
753         var cents = 0;
754         angular.forEach(items, function(item) {
755             promises.push(
756                 billSvc.fetchBills(item.id).then(function(bills) {
757                     angular.forEach(bills, function(b) {
758                         if (b.voided() != 't') {
759                             cents += b.amount() * 100;
760                             bill_ids.push(b.id())
761                         }
762                     });
763
764                     if (bill_ids.length == 0) {
765                         // TODO: warn
766                         return;
767                     }
768
769                 })
770             );
771         });
772
773         $q.all(promises).then(function(){
774             egCore.audio.play('warning.circ.void_billings_confirmation');
775             egConfirmDialog.open(
776                 egCore.strings.CONFIRM_VOID_BILLINGS, '', 
777                 {   billIds : ''+bill_ids,
778                     amount : ''+(cents/100),
779                     ok : function() {
780                         billSvc.voidBills(bill_ids).then(function() {
781                             $scope.session_voided = 
782                                 ($scope.session_voided * 100 + cents) / 100;
783                             refreshDisplay();
784                         });
785                     }
786                 }
787             );
788         });
789     }
790
791     $scope.adjustToZero = function(items) {
792         if (items.length == 0) return;
793
794         var ids = items.map(function(item) {return item.id});
795
796         egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
797         egConfirmDialog.open(
798             egCore.strings.CONFIRM_ADJUST_TO_ZERO, '', 
799             {   xactIds : ''+ids,
800                 ok : function() {
801                     billSvc.adjustBillsToZero(ids).then(function() {
802                         refreshDisplay();
803                     });
804                 }
805             }
806         );
807
808     }
809
810     // note this is functionally equivalent to selecting a neg. transaction
811     // then clicking Apply Payment -- this just adds a speed bump (ditto
812     // the XUL client).
813     $scope.refundXact = function(all) {
814         var items = all.filter(function(item) {
815             return item['summary.balance_owed'] < 0
816         });
817
818         if (items.length == 0) return;
819
820         var ids = items.map(function(item) {return item.id});
821
822         egCore.audio.play('warning.circ.refund_confirmation');
823         egConfirmDialog.open(
824             egCore.strings.CONFIRM_REFUND_PAYMENT, '', 
825             {   xactIds : ''+ids,
826                 ok : function() {
827                     // reset the received payment amount.  this ensures
828                     // we're not mingling payments with refunds.
829                     $scope.payment_amount = 0;
830                 }
831             }
832         );
833     }
834
835     // direct the user to the transaction details page
836     $scope.showFullDetails = function(all) {
837         var lastClicked = $scope.gridControls.contextMenuItem();
838         if (lastClicked) {
839             $location.path('/circ/patron/' + 
840                 patronSvc.current.id() + '/bill/' + lastClicked + '/statement');
841         } else if (all[0]) {
842             $location.path('/circ/patron/' + 
843                 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
844         }
845             
846     }
847
848     $scope.activateBill = function(xact) {
849         $scope.showFullDetails([xact]);
850     }
851
852 }])
853
854 /**
855  * Displays details of a single transaction
856  */
857 .controller('XactDetailsCtrl',
858        ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
859 function($scope,  $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
860
861     $scope.initTab('bills', $routeParams.id);
862     var xact_id = $routeParams.xact_id;
863     $scope.xact_tab = $routeParams.xact_tab;
864
865     var xactGrid = $scope.xactGridControls = {
866         setQuery : function() { return {xact : xact_id} },
867         setSort : function() { return ['billing_ts'] }
868     }
869
870     var paymentGrid = $scope.paymentGridControls = {
871         setQuery : function() { return {xact : xact_id} },
872         setSort : function() { return ['payment_ts'] }
873     }
874
875     // -- actions
876     $scope.voidBillings = function(bill_list) {
877         var bill_ids = [];
878         var cents = 0;
879         angular.forEach(bill_list, function(b) {
880             if (b.voided != 't') {
881                 cents += b.amount * 100;
882                 bill_ids.push(b.id)
883             }
884         });
885
886         if (bill_ids.length == 0) {
887             // TODO: warn
888             return;
889         }
890
891         egCore.audio.play('warning.circ.void_billings_confirmation');
892         egConfirmDialog.open(
893             egCore.strings.CONFIRM_VOID_BILLINGS, '', 
894             {   billIds : ''+bill_ids,
895                 amount : ''+(cents/100),
896                 ok : function() {
897                     billSvc.voidBills(bill_ids).then(function() {
898                         // TODO? $scope.session_voided = ...
899
900                         // refresh bills and summary data
901                         // note: no need to update payments
902                         patronSvc.fetchUserStats();
903
904                         egBilling.fetchXact(xact_id).then(function(xact) {
905                             $scope.xact = xact
906                         });
907
908                         xactGrid.refresh();
909                     });
910                 }
911             }
912         );
913     }
914
915     // batch-edit billing and payment notes, depending on 'type'
916     function editNotes(selected, type) {
917         var notes = selected.map(function(b){ return b.note }).join(',');
918         var ids = selected.map(function(b){ return b.id });
919
920         // show the note edit prompt
921         egPromptDialog.open(
922             egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
923                 ids : ''+ids,
924                 ok : function(value) {
925
926                     var func = 'updateBillNotes';
927                     if (type == 'payment') func = 'updatePaymentNotes';
928
929                     billSvc[func](value, ids).then(function() {
930                         if (type == 'payment') {
931                             paymentGrid.refresh();
932                         } else {
933                             xactGrid.refresh();
934                         }
935                     });
936                 }
937             }
938         );
939     }
940
941     $scope.editBillNotes = function(selected) {
942         editNotes(selected, 'bill');
943     }
944
945     $scope.editPaymentNotes = function(selected) {
946         editNotes(selected, 'payment');
947     }
948
949     // -- retrieve our data
950     if ($scope.xact_tab == 'statement') {
951         //fetch combined billing statement data
952         billSvc.fetchStatement(xact_id).then(function(statement) {
953             //console.log(statement);
954             $scope.statement_data = statement;
955         });
956     }
957     $scope.total_circs = 0; // start with 0 instead of undefined
958     egBilling.fetchXact(xact_id).then(function(xact) {
959         $scope.xact = xact;
960
961         var copyId = xact.circulation().target_copy().id();
962         var circ_count = 0;
963         egCore.pcrud.search('circbyyr',
964             {copy : copyId}, null, {atomic : true})
965         .then(function(counts) {
966             angular.forEach(counts, function(count) {
967                 circ_count += Number(count.count());
968             });
969             $scope.total_circs = circ_count;
970         });
971         // set the title.  only needs to be done on initial page load
972         if (xact.circulation()) {
973             if (xact.circulation().target_copy().call_number().id() == -1) {
974                 $scope.title = xact.circulation().target_copy().dummy_title();
975             } else  {
976                 // TODO: shared bib service?
977                 $scope.title = xact.circulation().target_copy()
978                     .call_number().record().simple_record().title();
979                 $scope.title_id = xact.circulation().target_copy()
980                     .call_number().record().id();
981             }
982         }
983     });
984 }])
985
986
987 .controller('BillHistoryCtrl',
988        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
989 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
990
991     $scope.initTab('bills', $routeParams.id);
992     billSvc.userId = $routeParams.id;
993     $scope.bill_tab = $routeParams.history_tab;
994     $scope.totals = {};
995
996     // link page controller actions defined by sub-controllers here
997     $scope.actions = {};
998
999     var start = new Date(); // now - 1 year
1000     start.setFullYear(start.getFullYear() - 1),
1001     $scope.dates = {
1002         xact_start : start,
1003         xact_finish : new Date()
1004     }
1005
1006     $scope.date_range = function() {
1007         var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
1008         var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
1009         var today = new Date().toISOString().replace(/T.*/,'');
1010         if (end == today) end = 'now';
1011         return [start, end];
1012     }
1013 }])
1014
1015
1016 .controller('BillXactHistoryCtrl',
1017        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
1018 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
1019
1020     // generate a grid query with the current date widget values.
1021     function current_grid_query() {
1022         return {
1023             '-or' : [
1024                 {'summary.balance_owed' : {'<>' : 0}},
1025                 {'summary.last_payment_ts' : {'<>' : null}}
1026             ],
1027             xact_start : {between : $scope.date_range()},
1028             usr : billSvc.userId
1029         }
1030     }
1031
1032     $scope.gridControls = {
1033         selectedItems : function(){return []},
1034         activateItem : function(item) {
1035             $scope.showFullDetails([item]);
1036         },
1037         // this sets the query on page load
1038         setQuery : current_grid_query
1039     }
1040
1041     $scope.$watch('dates.xact_start', function(new_date, old_date) {
1042         if (new_date !== old_date && new_date) {
1043             if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1044                 $scope.dates.xact_finish = new_date;
1045             } else {
1046                 $scope.actions.apply_date_range();
1047             }
1048         }
1049     });
1050     $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1051         if (new_date !== old_date && new_date) {
1052             if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1053                 $scope.dates.xact_start = new_date;
1054             } else {
1055                 $scope.actions.apply_date_range();
1056             }
1057         }
1058     });
1059
1060     $scope.actions.apply_date_range = function() {
1061         // tells the grid to re-draw itself with the new query
1062         $scope.gridControls.setQuery(current_grid_query());
1063     }
1064
1065     // TODO; move me to service
1066     function selected_payment_info() {
1067         var info = {owed : 0, billed : 0, paid : 0};
1068         angular.forEach($scope.gridControls.selectedItems(), function(item) {
1069             info.owed   += Number(item['summary.balance_owed']) * 100;
1070             info.billed += Number(item['summary.total_owed']) * 100;
1071             info.paid   += Number(item['summary.total_paid']) * 100;
1072         });
1073         info.owed /= 100;
1074         info.billed /= 100;
1075         info.paid /= 100;
1076         return info;
1077     }
1078
1079     $scope.totals.selected_billed = function() {
1080         return selected_payment_info().billed;
1081     }
1082     $scope.totals.selected_paid = function() {
1083         return selected_payment_info().paid;
1084     }
1085
1086     $scope.showFullDetails = function(all) {
1087         if (all[0]) 
1088             $location.path('/circ/patron/' + 
1089                 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1090     }
1091
1092     // For now, only adds billing to first selected item.
1093     // Could do batches later if needed
1094     $scope.addBilling = function(all) {
1095         if (all[0]) {
1096             egBilling.showBillDialog({
1097                 xact : egCore.idl.flatToNestedHash(all[0]),
1098                 patron : $scope.patron()
1099             }).then(function() { 
1100                 $scope.gridControls.refresh();
1101                 patronSvc.fetchUserStats();
1102             })
1103         }
1104     }
1105
1106     $scope.printBills = function(selected) { // FIXME: refactor me
1107         if (!selected.length) return;
1108         // bills print receipt assumes nested hashes, but our grid
1109         // stores flattener data.  Fetch the selected xacts as
1110         // fleshed pcrud objects and hashify.  
1111         // (Consider an alternate approach..)
1112         var ids = selected.map(function(t){ return t.id });
1113         var xacts = [];
1114         egCore.pcrud.search('mbt', 
1115             {id : ids},
1116             {flesh : 5, flesh_fields : {
1117                 'mbt' : ['summary', 'circulation'],
1118                 'circ' : ['target_copy'],
1119                 'acp' : ['call_number'],
1120                 'acn' : ['record','owning_lib','prefix','suffix'],
1121                 'bre' : ['simple_record']
1122                 }
1123             },
1124             {authoritative : true}
1125         ).then(
1126             function() {
1127                 var cusr = patronSvc.current;
1128                 egCore.print.print({
1129                     context : 'receipt', 
1130                     template : 'bills_historical', 
1131                     scope : {   
1132                         transactions : xacts,
1133                         current_location : egCore.idl.toHash(
1134                             egCore.org.get(egCore.auth.user().ws_ou())),
1135                         patron : {
1136                             prefix : cusr.prefix(),
1137                             pref_prefix : cusr.pref_prefix(),
1138                             pref_first_given_name : cusr.pref_first_given_name(),
1139                             pref_second_given_name : cusr.pref_second_given_name(),
1140                             pref_family_name : cusr.pref_family_name(),
1141                             pref_suffix : cusr.pref_suffix(),
1142                             first_given_name : cusr.first_given_name(),
1143                             second_given_name : cusr.second_given_name(),
1144                             family_name : cusr.family_name(),
1145                             suffix : cusr.suffix(),
1146                             card : { barcode : cusr.card().barcode() },
1147                             expire_date : cusr.expire_date(),
1148                             alias : cusr.alias(),
1149                             has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1150                             has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1151                         }
1152                     }
1153                 });
1154             }, 
1155             null, 
1156             function(xact) {
1157                 newXact = {
1158                     billing_total : xact.billing_total(),
1159                     billings : xact.billings(),
1160                     grocery : xact.grocery(),
1161                     id : xact.id(),
1162                     payment_total : xact.payment_total(),
1163                     payments : xact.payments(),
1164                     summary : egCore.idl.toHash(xact.summary()),
1165                     unrecovered : xact.unrecovered(),
1166                     xact_finish : xact.xact_finish(),
1167                     xact_start : xact.xact_start(),
1168                 }
1169                 if (xact.circulation()) {
1170                     newXact.copy_barcode = xact.circulation().target_copy().barcode();
1171                     newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
1172                     newXact.call_number = {
1173                         label : xact.circulation().target_copy().call_number().label(),
1174                                     prefix : xact.circulation().target_copy().call_number().prefix().label(),
1175                                     suffix : xact.circulation().target_copy().call_number().suffix().label(),
1176                         owning_lib : {
1177                             name : xact.circulation().target_copy().call_number().owning_lib().name(),
1178                             shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
1179                         }
1180                     }
1181                 }
1182                 xacts.push(newXact);
1183             }
1184         );
1185     }
1186 }])
1187
1188 .controller('BillPaymentHistoryCtrl',
1189        ['$scope','$q','egCore','patronSvc','billSvc','$location',
1190 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
1191
1192     // generate a grid query with the current date widget values.
1193     function current_grid_query() {
1194         return {
1195             'payment_ts' : {between : $scope.date_range()},
1196             'xact.usr' : billSvc.userId
1197         }
1198     }
1199
1200     $scope.gridControls = {
1201         selectedItems : function(){return []},
1202         activateItem : function(item) {
1203             $scope.showFullDetails([item]);
1204         },
1205         setSort : function() {
1206             return [{'payment_ts' : 'DESC'}, 'id'];
1207         },
1208         setQuery : current_grid_query
1209     }
1210
1211     $scope.$watch('dates.xact_start', function(new_date, old_date) {
1212         if (new_date !== old_date && new_date) {
1213             if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1214                 $scope.dates.xact_finish = new_date;
1215             } else {
1216                 $scope.actions.apply_date_range();
1217             }
1218         }
1219     });
1220     $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1221         if (new_date !== old_date && new_date) {
1222             if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1223                 $scope.dates.xact_start = new_date;
1224             } else {
1225                 $scope.actions.apply_date_range();
1226             }
1227         }
1228     });
1229
1230     $scope.actions.apply_date_range = function() {
1231         // tells the grid to re-draw itself with the new query
1232         $scope.gridControls.setQuery(current_grid_query());
1233     }
1234
1235     $scope.showFullDetails = function(all) {
1236         if (all[0]) 
1237             $location.path('/circ/patron/' + 
1238                 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1239     }
1240
1241     $scope.totals.selected_paid = function() {
1242         var paid = 0;
1243         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1244             paid += Number(payment.amount) * 100;
1245         });
1246         return paid / 100;
1247     }
1248 }])
1249
1250
1251