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