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