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