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