4 angular.module('egPatronApp')
7 ['$q','egCore','egWorkLog','patronSvc',
8 function($q , egCore , egWorkLog , patronSvc) {
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});
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})
30 service.applyPayment = function(
31 type, payments, note, check, cc_args, patron_credit) {
33 return egCore.net.request(
35 'open-ils.circ.money.payment',
36 egCore.auth.token(), {
37 userid : service.userId,
42 patron_credit : patron_credit,
45 patronSvc.current.last_xact_id()
46 ).then(function(resp) {
47 console.debug('payments: ' + js2JSON(resp));
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.
54 return $q.reject(''+evt);
57 var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
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;
70 'action' : 'paid_bill',
71 'patron_id' : service.userId,
72 'total_amount' : total
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);
80 // reload patron data if credit balance has changed:
81 if(type === 'credit_payment' || patron_credit){ patronSvc.refreshPrimary(); }
87 service.fetchBills = function(xact_id) {
89 return egCore.pcrud.search('mb',
90 {xact : xact_id}, null,
91 {authoritative : true}
93 function() {return bills},
95 function(bill) {bills.push(bill); return bill}
99 service.fetchStatement = function(xact_id) {
100 return egCore.net.request(
102 'open-ils.circ.money.statement.retrieve',
103 egCore.auth.token(), xact_id
104 ).then(function(resp) {
105 if (evt = egCore.evt.parse(resp)) return alert(evt);
110 // TODO: no longer needed?
111 service.fetchPayments = function(xact_id) {
112 return egCore.net.request(
114 'open-ils.circ.money.payment.retrieve.all.authoritative',
115 egCore.auth.token(), xact_id
119 service.voidBills = function(bill_ids) {
120 return egCore.net.requestWithParamList(
122 'open-ils.circ.money.billing.void',
123 [egCore.auth.token()].concat(bill_ids)
124 ).then(function(resp) {
125 if (evt = egCore.evt.parse(resp)) return alert(evt);
130 service.adjustBillsToZero = function(bill_ids) {
131 return egCore.net.request(
133 'open-ils.circ.money.billable_xact.adjust_to_zero',
136 ).then(function(resp) {
137 if (evt = egCore.evt.parse(resp)) return alert(evt);
142 service.updateBillNotes = function(note, ids) {
143 return egCore.net.requestWithParamList(
145 'open-ils.circ.money.billing.note.edit',
146 [egCore.auth.token(), note].concat(ids)
147 ).then(function(resp) {
148 if (evt = egCore.evt.parse(resp)) return alert(evt);
153 service.updatePaymentNotes = function(note, ids) {
154 return egCore.net.requestWithParamList(
156 'open-ils.circ.money.payment.note.edit',
157 [egCore.auth.token(), note].concat(ids)
158 ).then(function(resp) {
159 if (evt = egCore.evt.parse(resp)) return alert(evt);
171 .controller('PatronBillsCtrl',
172 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
173 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
174 'egBilling','$uibModal',
175 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
176 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
177 egBilling , $uibModal) {
179 $scope.initTab('bills', $routeParams.id);
180 billSvc.userId = $routeParams.id;
182 // set up some defaults
183 $scope.check_number = null;
184 $scope.payment_amount = null;
185 $scope.session_voided = 0;
186 $scope.payment_type = 'cash_payment';
187 $scope.focus_payment = true;
188 $scope.annotate_payment = false;
189 $scope.receipt_count = 1;
190 $scope.receipt_on_pay = { isChecked: false };
191 $scope.convert_to_credit = {isChecked: false};
192 $scope.warn_amount = 1000;
193 $scope.max_amount = 100000;
194 $scope.amount_verified = false;
195 $scope.disable_auto_print = false;
197 // Load persistant settings
198 egCore.hatch.getItem('circ.bills.receiptonpay')
199 .then(function(rcptOnPay){
200 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
203 egCore.hatch.getItem('eg.circ.bills.annotatepayment')
204 .then(function(annoPay){
205 if (annoPay) $scope.annotate_payment = annoPay;
208 // pre-define list-returning funcs in case we access them
209 // before the grid instantiates
210 $scope.gridControls = {
211 focusRowSelector : false,
212 selectedItems : function(){return []},
213 allItems : function(){return []},
214 itemRetrieved : function(item) {
215 item.payment_pending = 0;
217 activateItem : function(item) {
218 $scope.showFullDetails([item]);
220 setQuery : function() {
222 usr : billSvc.userId,
224 'summary.balance_owed' : {'<>' : 0}
227 setSort : function() {
228 return ['xact_start'];
232 // Apply coloring to rows based on fines stop reason
233 $scope.colorizeBillsList = {
234 apply: function(item) {
235 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
236 if (item['circulation.stop_fines'] == 'LOST') {
238 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
239 return 'longoverdue-row';
241 return 'overdue-row';
247 // Status Icon Column definition
248 $scope.statusIconColumn = {
250 template: function(item) {
252 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
253 if (item['circulation.stop_fines'] == "LOST") {
254 icon = 'glyphicon-question-sign';
255 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
256 icon = 'glyphicon-exclamation-sign';
258 icon = 'glyphicon-time';
261 return "<i class='glyphicon " + icon + "'></i>"
265 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
267 // given a payment amount, determines how much of that is applied
268 // to selected transactions and how much is left over (change).
269 function pending_payment_info() {
270 var amt = $scope.payment_amount || 0;
271 if (amt >= $scope.owed_selected()) {
273 payment : $scope.owed_selected(),
274 change : amt - $scope.owed_selected()
277 return {payment : amt, change : 0};
280 // calculates amount owed, billed, and paid for selected items
281 // TODO: move me to service
282 function selected_payment_info() {
283 var info = {owed : 0, billed : 0, paid : 0};
284 angular.forEach($scope.gridControls.selectedItems(), function(item) {
285 info.owed += Number(item['summary.balance_owed']) * 100;
286 info.billed += Number(item['summary.total_owed']) * 100;
287 info.paid += Number(item['summary.total_paid']) * 100;
295 $scope.pending_payment = function() {
296 return pending_payment_info().payment;
298 $scope.pending_change = function() {
299 return pending_payment_info().change;
301 $scope.owed_selected = function() {
302 return selected_payment_info().owed;
304 $scope.billed_selected = function() {
305 return selected_payment_info().billed;
307 $scope.paid_selected = function() {
308 return selected_payment_info().paid;
310 $scope.refunds_available = function() {
312 angular.forEach($scope.gridControls.allItems(), function(item) {
313 if (item['summary.balance_owed'] < 0)
314 amount += item['summary.balance_owed'] * 100;
316 return -(amount / 100);
318 $scope.invalid_check_number = function() {
319 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
322 // update the item.payment_pending value each time the user
323 // selects different transactions to pay against.
325 function() {return $scope.gridControls.selectedItems()},
326 function() {updatePendingColumn()},
330 // update the item.payment_pending for each (selected)
331 // transaction any time the user-entered payment amount is modified
332 $scope.$watch('payment_amount', updatePendingColumn);
334 // updates the value of the payment_pending column in the grid.
335 // This has to be managed manually since the display value in the grid
336 // is derived from the value on the stored item and not the contents
337 // of our local scope variables.
338 function updatePendingColumn() {
339 // reset all to zero..
340 angular.forEach($scope.gridControls.allItems(),
341 function(item) {item.payment_pending = 0});
343 var payment_amount = $scope.pending_payment();
345 var selected = $scope.gridControls.selectedItems();
346 for (var i = 0; i < selected.length; i++) { // for/break
347 var item = selected[i];
348 var owed = Number(item['summary.balance_owed']);
350 if (payment_amount > owed) {
351 // pending payment exceeds balance of current item.
352 // pay the entire item.
353 item.payment_pending = owed;
354 payment_amount -= owed;
357 // balance owed on the current item matches or exceeds
358 // the pending payment. Apply the full remainder of
359 // the payment to this item.. and we're done.
360 item.payment_pending = payment_amount;
366 // builds payment arrays ([xact_id, ammount]) for all transactions
367 // which have a pending payment amount.
368 function generatePayments() {
370 angular.forEach($scope.gridControls.selectedItems(), function(item) {
371 if (item.payment_pending == 0) return;
372 payments.push([item.id, item.payment_pending]);
377 function refreshDisplay() {
378 patronSvc.fetchUserStats();
379 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
380 $scope.payment_amount = null;
381 $scope.gridControls.refresh();
384 // generates payments, collects user note if needed, and sends payment
386 function sendPayment(note, cc_args) {
387 $scope.applyingPayment = true;
388 var make_payments = generatePayments();
389 var patron_credit = $scope.convert_to_credit.isChecked ?
390 $scope.pending_change() : 0;
391 billSvc.applyPayment($scope.payment_type,
392 make_payments, note, $scope.check_number, cc_args, patron_credit)
394 function(payment_ids) {
396 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
398 $scope.payment_type, payment_ids, make_payments, note);
404 console.error('Payment was rejected: ' + msg);
407 .finally(function() { $scope.applyingPayment = false; })
410 $scope.onReceiptOnPayChanged = function(){
411 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
414 $scope.onAnnotatePaymentChanged = function(){
415 egCore.hatch.setItem('eg.circ.bills.annotatepayment', $scope.annotate_payment);
418 function printReceipt(type, payment_ids, payments_made, note) {
419 var payment_blobs = [];
420 var cusr = patronSvc.current;
422 angular.forEach(payments_made, function(payment) {
423 var xact_id = payment[0];
425 // find the original transaction in the grid..
426 var xact = $scope.gridControls.allItems().filter(
427 function(item) {return item.id == xact_id})[0];
430 xact : egCore.idl.flatToNestedHash(xact),
435 console.log(js2JSON(payment_blobs[0]));
437 // page data not yet refreshed, capture data from current scope
441 previous_balance : Number($scope.summary.balance_owed()),
442 payment_total : Number($scope.payment_amount),
443 payment_applied : $scope.pending_payment(),
444 amount_voided : Number($scope.session_voided),
445 change_given : $scope.pending_change(),
446 payments : payment_blobs,
447 current_location : egCore.idl.toHash(
448 egCore.org.get(egCore.auth.user().ws_ou()))
451 // Not a good idea to use patron_stats.fines for this; it's out of date
452 print_data.patron = {
453 prefix : cusr.prefix(),
454 first_given_name : cusr.first_given_name(),
455 second_given_name : cusr.second_given_name(),
456 family_name : cusr.family_name(),
457 suffix : cusr.suffix(),
458 pref_prefix : cusr.pref_prefix(),
459 pref_first_given_name : cusr.pref_first_given_name(),
460 pref_second_given_name : cusr.pref_second_given_name(),
461 pref_family_name : cusr.pref_family_name(),
462 pref_suffix : cusr.pref_suffix(),
463 card : { barcode : cusr.card().barcode() },
464 expire_date : cusr.expire_date(),
465 alias : cusr.alias(),
466 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
467 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
470 print_data.new_balance = (
471 print_data.previous_balance * 100 -
472 print_data.payment_applied * 100) / 100;
474 for (var i = 0; i < $scope.receipt_count; i++) {
477 template : 'bill_payment',
483 $scope.showHistory = function() {
484 $location.path('/circ/patron/' +
485 patronSvc.current.id() + '/bill_history/transactions');
488 // For now, only adds billing to first selected item.
489 // Could do batches later if needed
490 $scope.addBilling = function(all) {
492 egBilling.showBillDialog({
493 xact : egCore.idl.flatToNestedHash(all[0]),
494 patron : $scope.patron()
495 }).then(refreshDisplay);
499 $scope.showBillDialog = function($event) {
500 egBilling.showBillDialog({
501 patron : $scope.patron()
502 }).then(refreshDisplay);
505 // Select refunds adds all refunds to the existing selection.
506 // It does not /only/ select refunds
507 $scope.selectRefunds = function() {
508 var ids = $scope.gridControls.selectedItems().map(
509 function(i) { return i.id });
510 angular.forEach($scope.gridControls.allItems(), function(item) {
511 if (Number(item['summary.balance_owed']) < 0)
514 $scope.gridControls.selectItems(ids);
518 // determine on initial page load when all of the grid rows should
520 var selectOnLoad = true;
521 billSvc.fetchBillSettings().then(function(s) {
522 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
523 $scope.focus_payment = false; // de-focus the payment box
524 $scope.gridControls.focusRowSelector = true;
525 selectOnLoad = false;
526 // if somehow the grid finishes rendering before our settings
527 // arrive, manually de-select everything.
528 $scope.gridControls.selectItems([]);
530 if (s['ui.circ.billing.amount_warn']) {
531 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
533 if (s['ui.circ.billing.amount_limit']) {
534 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
536 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
537 $scope.disable_auto_print = Boolean(
538 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
541 if (s['circ.disable_patron_credit']) {
542 $scope.disablePatronCredit = true;
546 $scope.gridControls.allItemsRetrieved = function() {
548 selectOnLoad = false; // only for initial controller load.
549 // select all non-refund items
550 $scope.gridControls.selectItems(
551 $scope.gridControls.allItems()
552 .filter(function(i) {return i['summary.balance_owed'] > 0})
553 .map(function(i){return i.id})
560 $scope.printBills = function(selected) {
561 if (!selected.length) return;
562 // bills print receipt assumes nested hashes, but our grid
563 // stores flattener data. Fetch the selected xacts as
564 // fleshed pcrud objects and hashify.
565 // (Consider an alternate approach..)
566 var ids = selected.map(function(t){ return t.id });
568 egCore.pcrud.search('mbt',
570 {flesh : 5, flesh_fields : {
571 'mbt' : ['summary', 'circulation'],
572 'circ' : ['target_copy'],
573 'acp' : ['call_number'],
575 'bre' : ['simple_record']
578 {authoritative : true}
581 var cusr = patronSvc.current;
584 template : 'bills_current',
586 transactions : xacts,
587 current_location : egCore.idl.toHash(
588 egCore.org.get(egCore.auth.user().ws_ou())),
590 prefix : cusr.prefix(),
591 first_given_name : cusr.first_given_name(),
592 second_given_name : cusr.second_given_name(),
593 family_name : cusr.family_name(),
594 suffix : cusr.suffix(),
595 pref_prefix : cusr.pref_prefix(),
596 pref_first_given_name : cusr.pref_first_given_name(),
597 pref_second_given_name : cusr.pref_second_given_name(),
598 pref_family_name : cusr.pref_family_name(),
599 pref_suffix : cusr.pref_suffix(),
600 card : { barcode : cusr.card().barcode() },
601 expire_date : cusr.expire_date(),
602 alias : cusr.alias(),
603 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
604 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
612 billing_total : xact.billing_total(),
613 billings : xact.billings(),
614 grocery : xact.grocery(),
616 payment_total : xact.payment_total(),
617 payments : xact.payments(),
618 summary : egCore.idl.toHash(xact.summary()),
619 unrecovered : xact.unrecovered(),
620 xact_finish : xact.xact_finish(),
621 xact_start : xact.xact_start(),
623 if (xact.circulation()) {
624 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
625 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
632 $scope.applyPayment = function() {
634 if ($scope.payment_amount > $scope.max_amount ) {
636 egCore.strings.PAYMENT_OVER_MAX,
637 { max_amount : ''+$scope.max_amount,
639 $scope.payment_amount = 0;
646 verify_payment_amount().then(
647 function() { // amount confirmed
648 add_payment_note().then(function(pay_note) {
649 add_cc_args().then(function(cc_args) {
650 var note_text = pay_note ? pay_note.value || '' : null;
651 sendPayment(note_text, cc_args);
655 function() { // amount rejected
656 console.warn('payment amount rejected');
657 $scope.payment_amount = 0;
662 function verify_payment_amount() {
663 if ($scope.payment_amount < $scope.warn_amount)
666 return egConfirmDialog.open(
667 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
668 egCore.strings.PAYMENT_WARN_AMOUNT,
669 {payment_amount : ''+$scope.payment_amount}
673 function add_payment_note() {
674 if (!$scope.annotate_payment) return $q.when();
675 return egPromptDialog.open(
676 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
679 function add_cc_args() {
680 if ($scope.payment_type != 'credit_card_payment')
683 return $uibModal.open({
684 templateUrl : './circ/patron/t_cc_payment_dialog',
687 '$scope','$uibModalInstance',
688 function($scope , $uibModalInstance) {
692 where_process : '1', // internal=1 ; external=0
693 type : 'VISA', // external only
694 billing_first : patronSvc.current.first_given_name(),
695 billing_last : patronSvc.current.family_name()
699 var addr = patronSvc.current.billing_address() ||
700 patronSvc.current.mailing_address();
702 var cc = $scope.context.cc;
703 cc.billing_address = addr.street1() +
704 (addr.street2() ? ' ' + addr.street2() : '');
705 cc.billing_city = addr.city();
706 cc.billing_state = addr.state();
707 cc.billing_zip = addr.post_code();
710 $scope.ok = function() {
711 // CC payment form is not a <form>,
712 // so apply validation manually.
713 if ( $scope.context.cc.where_process == 0 &&
714 !$scope.context.cc.approval_code)
717 $uibModalInstance.close($scope.context.cc);
720 $scope.cancel = function() {
721 $uibModalInstance.dismiss();
728 $scope.voidAllBillings = function(items) {
732 angular.forEach(items, function(item) {
734 billSvc.fetchBills(item.id).then(function(bills) {
735 angular.forEach(bills, function(b) {
736 if (b.voided() != 't') {
737 cents += b.amount() * 100;
738 bill_ids.push(b.id())
742 if (bill_ids.length == 0) {
751 $q.all(promises).then(function(){
752 egCore.audio.play('warning.circ.void_billings_confirmation');
753 egConfirmDialog.open(
754 egCore.strings.CONFIRM_VOID_BILLINGS, '',
755 { billIds : ''+bill_ids,
756 amount : ''+(cents/100),
758 billSvc.voidBills(bill_ids).then(function() {
759 $scope.session_voided =
760 ($scope.session_voided * 100 + cents) / 100;
769 $scope.adjustToZero = function(items) {
770 if (items.length == 0) return;
772 var ids = items.map(function(item) {return item.id});
774 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
775 egConfirmDialog.open(
776 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
779 billSvc.adjustBillsToZero(ids).then(function() {
788 // note this is functionally equivalent to selecting a neg. transaction
789 // then clicking Apply Payment -- this just adds a speed bump (ditto
791 $scope.refundXact = function(all) {
792 var items = all.filter(function(item) {
793 return item['summary.balance_owed'] < 0
796 if (items.length == 0) return;
798 var ids = items.map(function(item) {return item.id});
800 egCore.audio.play('warning.circ.refund_confirmation');
801 egConfirmDialog.open(
802 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
805 // reset the received payment amount. this ensures
806 // we're not mingling payments with refunds.
807 $scope.payment_amount = 0;
813 // direct the user to the transaction details page
814 $scope.showFullDetails = function(all) {
816 $location.path('/circ/patron/' +
817 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
820 $scope.activateBill = function(xact) {
821 $scope.showFullDetails([xact]);
827 * Displays details of a single transaction
829 .controller('XactDetailsCtrl',
830 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
831 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
833 $scope.initTab('bills', $routeParams.id);
834 var xact_id = $routeParams.xact_id;
835 $scope.xact_tab = $routeParams.xact_tab;
837 var xactGrid = $scope.xactGridControls = {
838 setQuery : function() { return {xact : xact_id} },
839 setSort : function() { return ['billing_ts'] }
842 var paymentGrid = $scope.paymentGridControls = {
843 setQuery : function() { return {xact : xact_id} },
844 setSort : function() { return ['payment_ts'] }
848 $scope.voidBillings = function(bill_list) {
851 angular.forEach(bill_list, function(b) {
852 if (b.voided != 't') {
853 cents += b.amount * 100;
858 if (bill_ids.length == 0) {
863 egCore.audio.play('warning.circ.void_billings_confirmation');
864 egConfirmDialog.open(
865 egCore.strings.CONFIRM_VOID_BILLINGS, '',
866 { billIds : ''+bill_ids,
867 amount : ''+(cents/100),
869 billSvc.voidBills(bill_ids).then(function() {
870 // TODO? $scope.session_voided = ...
872 // refresh bills and summary data
873 // note: no need to update payments
874 patronSvc.fetchUserStats();
876 egBilling.fetchXact(xact_id).then(function(xact) {
887 // batch-edit billing and payment notes, depending on 'type'
888 function editNotes(selected, type) {
889 var notes = selected.map(function(b){ return b.note }).join(',');
890 var ids = selected.map(function(b){ return b.id });
892 // show the note edit prompt
894 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
896 ok : function(value) {
898 var func = 'updateBillNotes';
899 if (type == 'payment') func = 'updatePaymentNotes';
901 billSvc[func](value, ids).then(function() {
902 if (type == 'payment') {
903 paymentGrid.refresh();
913 $scope.editBillNotes = function(selected) {
914 editNotes(selected, 'bill');
917 $scope.editPaymentNotes = function(selected) {
918 editNotes(selected, 'payment');
921 // -- retrieve our data
922 if ($scope.xact_tab == 'statement') {
923 //fetch combined billing statement data
924 billSvc.fetchStatement(xact_id).then(function(statement) {
925 //console.log(statement);
926 $scope.statement_data = statement;
929 $scope.total_circs = 0; // start with 0 instead of undefined
930 egBilling.fetchXact(xact_id).then(function(xact) {
933 var copyId = xact.circulation().target_copy().id();
935 egCore.pcrud.search('circbyyr',
936 {copy : copyId}, null, {atomic : true})
937 .then(function(counts) {
938 angular.forEach(counts, function(count) {
939 circ_count += Number(count.count());
941 $scope.total_circs = circ_count;
943 // set the title. only needs to be done on initial page load
944 if (xact.circulation()) {
945 if (xact.circulation().target_copy().call_number().id() == -1) {
946 $scope.title = xact.circulation().target_copy().dummy_title();
948 // TODO: shared bib service?
949 $scope.title = xact.circulation().target_copy()
950 .call_number().record().simple_record().title();
951 $scope.title_id = xact.circulation().target_copy()
952 .call_number().record().id();
959 .controller('BillHistoryCtrl',
960 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
961 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
963 $scope.initTab('bills', $routeParams.id);
964 billSvc.userId = $routeParams.id;
965 $scope.bill_tab = $routeParams.history_tab;
968 // link page controller actions defined by sub-controllers here
971 var start = new Date(); // now - 1 year
972 start.setFullYear(start.getFullYear() - 1),
975 xact_finish : new Date()
978 $scope.date_range = function() {
979 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
980 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
981 var today = new Date().toISOString().replace(/T.*/,'');
982 if (end == today) end = 'now';
988 .controller('BillXactHistoryCtrl',
989 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
990 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
992 // generate a grid query with the current date widget values.
993 function current_grid_query() {
996 {'summary.balance_owed' : {'<>' : 0}},
997 {'summary.last_payment_ts' : {'<>' : null}}
999 xact_start : {between : $scope.date_range()},
1000 usr : billSvc.userId
1004 $scope.gridControls = {
1005 selectedItems : function(){return []},
1006 activateItem : function(item) {
1007 $scope.showFullDetails([item]);
1009 // this sets the query on page load
1010 setQuery : current_grid_query
1013 $scope.actions.apply_date_range = function() {
1014 // tells the grid to re-draw itself with the new query
1015 $scope.gridControls.setQuery(current_grid_query());
1018 // TODO; move me to service
1019 function selected_payment_info() {
1020 var info = {owed : 0, billed : 0, paid : 0};
1021 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1022 info.owed += Number(item['summary.balance_owed']) * 100;
1023 info.billed += Number(item['summary.total_owed']) * 100;
1024 info.paid += Number(item['summary.total_paid']) * 100;
1032 $scope.totals.selected_billed = function() {
1033 return selected_payment_info().billed;
1035 $scope.totals.selected_paid = function() {
1036 return selected_payment_info().paid;
1039 $scope.showFullDetails = function(all) {
1041 $location.path('/circ/patron/' +
1042 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1045 // For now, only adds billing to first selected item.
1046 // Could do batches later if needed
1047 $scope.addBilling = function(all) {
1049 egBilling.showBillDialog({
1050 xact : egCore.idl.flatToNestedHash(all[0]),
1051 patron : $scope.patron()
1052 }).then(function() {
1053 $scope.gridControls.refresh();
1054 patronSvc.fetchUserStats();
1059 $scope.printBills = function(selected) { // FIXME: refactor me
1060 if (!selected.length) return;
1061 // bills print receipt assumes nested hashes, but our grid
1062 // stores flattener data. Fetch the selected xacts as
1063 // fleshed pcrud objects and hashify.
1064 // (Consider an alternate approach..)
1065 var ids = selected.map(function(t){ return t.id });
1067 egCore.pcrud.search('mbt',
1069 {flesh : 5, flesh_fields : {
1070 'mbt' : ['summary', 'circulation'],
1071 'circ' : ['target_copy'],
1072 'acp' : ['call_number'],
1074 'bre' : ['simple_record']
1077 {authoritative : true}
1080 var cusr = patronSvc.current;
1081 egCore.print.print({
1082 context : 'receipt',
1083 template : 'bills_historical',
1085 transactions : xacts,
1086 current_location : egCore.idl.toHash(
1087 egCore.org.get(egCore.auth.user().ws_ou())),
1089 prefix : cusr.prefix(),
1090 pref_prefix : cusr.pref_prefix(),
1091 pref_first_given_name : cusr.pref_first_given_name(),
1092 pref_second_given_name : cusr.pref_second_given_name(),
1093 pref_family_name : cusr.pref_family_name(),
1094 pref_suffix : cusr.pref_suffix(),
1095 first_given_name : cusr.first_given_name(),
1096 second_given_name : cusr.second_given_name(),
1097 family_name : cusr.family_name(),
1098 suffix : cusr.suffix(),
1099 card : { barcode : cusr.card().barcode() },
1100 expire_date : cusr.expire_date(),
1101 alias : cusr.alias(),
1102 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1103 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1111 billing_total : xact.billing_total(),
1112 billings : xact.billings(),
1113 grocery : xact.grocery(),
1115 payment_total : xact.payment_total(),
1116 payments : xact.payments(),
1117 summary : egCore.idl.toHash(xact.summary()),
1118 unrecovered : xact.unrecovered(),
1119 xact_finish : xact.xact_finish(),
1120 xact_start : xact.xact_start(),
1122 if (xact.circulation()) {
1123 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1124 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1126 xacts.push(newXact);
1132 .controller('BillPaymentHistoryCtrl',
1133 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1134 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1136 // generate a grid query with the current date widget values.
1137 function current_grid_query() {
1139 'payment_ts' : {between : $scope.date_range()},
1140 'xact.usr' : billSvc.userId
1144 $scope.gridControls = {
1145 selectedItems : function(){return []},
1146 activateItem : function(item) {
1147 $scope.showFullDetails([item]);
1149 setSort : function() {
1150 return [{'payment_ts' : 'DESC'}, 'id'];
1152 setQuery : current_grid_query
1155 $scope.actions.apply_date_range = function() {
1156 // tells the grid to re-draw itself with the new query
1157 $scope.gridControls.setQuery(current_grid_query());
1160 $scope.showFullDetails = function(all) {
1162 $location.path('/circ/patron/' +
1163 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1166 $scope.totals.selected_paid = function() {
1168 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1169 paid += Number(payment.amount) * 100;