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