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