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