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