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