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