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('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('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 card : { barcode : cusr.card().barcode() },
459 expire_date : cusr.expire_date(),
460 alias : cusr.alias(),
461 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
462 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
465 print_data.new_balance = (
466 print_data.previous_balance * 100 -
467 print_data.payment_applied * 100) / 100;
469 for (var i = 0; i < $scope.receipt_count; i++) {
472 template : 'bill_payment',
478 $scope.showHistory = function() {
479 $location.path('/circ/patron/' +
480 patronSvc.current.id() + '/bill_history/transactions');
483 // For now, only adds billing to first selected item.
484 // Could do batches later if needed
485 $scope.addBilling = function(all) {
487 egBilling.showBillDialog({
488 xact : egCore.idl.flatToNestedHash(all[0]),
489 patron : $scope.patron()
490 }).then(refreshDisplay);
494 $scope.showBillDialog = function($event) {
495 egBilling.showBillDialog({
496 patron : $scope.patron()
497 }).then(refreshDisplay);
500 // Select refunds adds all refunds to the existing selection.
501 // It does not /only/ select refunds
502 $scope.selectRefunds = function() {
503 var ids = $scope.gridControls.selectedItems().map(
504 function(i) { return i.id });
505 angular.forEach($scope.gridControls.allItems(), function(item) {
506 if (Number(item['summary.balance_owed']) < 0)
509 $scope.gridControls.selectItems(ids);
513 // determine on initial page load when all of the grid rows should
515 var selectOnLoad = true;
516 billSvc.fetchBillSettings().then(function(s) {
517 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
518 $scope.focus_payment = false; // de-focus the payment box
519 $scope.gridControls.focusRowSelector = true;
520 selectOnLoad = false;
521 // if somehow the grid finishes rendering before our settings
522 // arrive, manually de-select everything.
523 $scope.gridControls.selectItems([]);
525 if (s['ui.circ.billing.amount_warn']) {
526 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
528 if (s['ui.circ.billing.amount_limit']) {
529 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
531 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
532 $scope.disable_auto_print = Boolean(
533 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
536 if (s['circ.disable_patron_credit']) {
537 $scope.disablePatronCredit = true;
541 $scope.gridControls.allItemsRetrieved = function() {
543 selectOnLoad = false; // only for initial controller load.
544 // select all non-refund items
545 $scope.gridControls.selectItems(
546 $scope.gridControls.allItems()
547 .filter(function(i) {return i['summary.balance_owed'] > 0})
548 .map(function(i){return i.id})
555 $scope.printBills = function(selected) {
556 if (!selected.length) return;
557 // bills print receipt assumes nested hashes, but our grid
558 // stores flattener data. Fetch the selected xacts as
559 // fleshed pcrud objects and hashify.
560 // (Consider an alternate approach..)
561 var ids = selected.map(function(t){ return t.id });
563 egCore.pcrud.search('mbt',
565 {flesh : 5, flesh_fields : {
566 'mbt' : ['summary', 'circulation'],
567 'circ' : ['target_copy'],
568 'acp' : ['call_number'],
570 'bre' : ['simple_record']
573 {authoritative : true}
576 var cusr = patronSvc.current;
579 template : 'bills_current',
581 transactions : xacts,
582 current_location : egCore.idl.toHash(
583 egCore.org.get(egCore.auth.user().ws_ou())),
585 prefix : cusr.prefix(),
586 first_given_name : cusr.first_given_name(),
587 second_given_name : cusr.second_given_name(),
588 family_name : cusr.family_name(),
589 suffix : cusr.suffix(),
590 card : { barcode : cusr.card().barcode() },
591 expire_date : cusr.expire_date(),
592 alias : cusr.alias(),
593 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
594 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
602 billing_total : xact.billing_total(),
603 billings : xact.billings(),
604 grocery : xact.grocery(),
606 payment_total : xact.payment_total(),
607 payments : xact.payments(),
608 summary : egCore.idl.toHash(xact.summary()),
609 unrecovered : xact.unrecovered(),
610 xact_finish : xact.xact_finish(),
611 xact_start : xact.xact_start(),
613 if (xact.circulation()) {
614 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
615 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
622 $scope.applyPayment = function() {
624 if ($scope.payment_amount > $scope.max_amount ) {
626 egCore.strings.PAYMENT_OVER_MAX,
627 { max_amount : ''+$scope.max_amount,
629 $scope.payment_amount = 0;
636 verify_payment_amount().then(
637 function() { // amount confirmed
638 add_payment_note().then(function(pay_note) {
639 add_cc_args().then(function(cc_args) {
640 var note_text = pay_note ? pay_note.value || '' : null;
641 sendPayment(note_text, cc_args);
645 function() { // amount rejected
646 console.warn('payment amount rejected');
647 $scope.payment_amount = 0;
652 function verify_payment_amount() {
653 if ($scope.payment_amount < $scope.warn_amount)
656 return egConfirmDialog.open(
657 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
658 egCore.strings.PAYMENT_WARN_AMOUNT,
659 {payment_amount : ''+$scope.payment_amount}
663 function add_payment_note() {
664 if (!$scope.annotate_payment) return $q.when();
665 return egPromptDialog.open(
666 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
669 function add_cc_args() {
670 if ($scope.payment_type != 'credit_card_payment')
673 return $uibModal.open({
674 templateUrl : './circ/patron/t_cc_payment_dialog',
677 '$scope','$uibModalInstance',
678 function($scope , $uibModalInstance) {
682 where_process : '1', // internal=1 ; external=0
683 type : 'VISA', // external only
684 billing_first : patronSvc.current.first_given_name(),
685 billing_last : patronSvc.current.family_name()
689 var addr = patronSvc.current.billing_address() ||
690 patronSvc.current.mailing_address();
692 var cc = $scope.context.cc;
693 cc.billing_address = addr.street1() +
694 (addr.street2() ? ' ' + addr.street2() : '');
695 cc.billing_city = addr.city();
696 cc.billing_state = addr.state();
697 cc.billing_zip = addr.post_code();
700 $scope.ok = function() {
701 // CC payment form is not a <form>,
702 // so apply validation manually.
703 if ( $scope.context.cc.where_process == 0 &&
704 !$scope.context.cc.approval_code)
707 $uibModalInstance.close($scope.context.cc);
710 $scope.cancel = function() {
711 $uibModalInstance.dismiss();
718 $scope.voidAllBillings = function(items) {
722 angular.forEach(items, function(item) {
724 billSvc.fetchBills(item.id).then(function(bills) {
725 angular.forEach(bills, function(b) {
726 if (b.voided() != 't') {
727 cents += b.amount() * 100;
728 bill_ids.push(b.id())
732 if (bill_ids.length == 0) {
741 $q.all(promises).then(function(){
742 egCore.audio.play('warning.circ.void_billings_confirmation');
743 egConfirmDialog.open(
744 egCore.strings.CONFIRM_VOID_BILLINGS, '',
745 { billIds : ''+bill_ids,
746 amount : ''+(cents/100),
748 billSvc.voidBills(bill_ids).then(function() {
749 $scope.session_voided =
750 ($scope.session_voided * 100 + cents) / 100;
759 $scope.adjustToZero = function(items) {
760 if (items.length == 0) return;
762 var ids = items.map(function(item) {return item.id});
764 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
765 egConfirmDialog.open(
766 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
769 billSvc.adjustBillsToZero(ids).then(function() {
778 // note this is functionally equivalent to selecting a neg. transaction
779 // then clicking Apply Payment -- this just adds a speed bump (ditto
781 $scope.refundXact = function(all) {
782 var items = all.filter(function(item) {
783 return item['summary.balance_owed'] < 0
786 if (items.length == 0) return;
788 var ids = items.map(function(item) {return item.id});
790 egCore.audio.play('warning.circ.refund_confirmation');
791 egConfirmDialog.open(
792 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
795 // reset the received payment amount. this ensures
796 // we're not mingling payments with refunds.
797 $scope.payment_amount = 0;
803 // direct the user to the transaction details page
804 $scope.showFullDetails = function(all) {
806 $location.path('/circ/patron/' +
807 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
810 $scope.activateBill = function(xact) {
811 $scope.showFullDetails([xact]);
817 * Displays details of a single transaction
819 .controller('XactDetailsCtrl',
820 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
821 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
823 $scope.initTab('bills', $routeParams.id);
824 var xact_id = $routeParams.xact_id;
825 $scope.xact_tab = $routeParams.xact_tab;
827 var xactGrid = $scope.xactGridControls = {
828 setQuery : function() { return {xact : xact_id} },
829 setSort : function() { return ['billing_ts'] }
832 var paymentGrid = $scope.paymentGridControls = {
833 setQuery : function() { return {xact : xact_id} },
834 setSort : function() { return ['payment_ts'] }
838 $scope.voidBillings = function(bill_list) {
841 angular.forEach(bill_list, function(b) {
842 if (b.voided != 't') {
843 cents += b.amount * 100;
848 if (bill_ids.length == 0) {
853 egCore.audio.play('warning.circ.void_billings_confirmation');
854 egConfirmDialog.open(
855 egCore.strings.CONFIRM_VOID_BILLINGS, '',
856 { billIds : ''+bill_ids,
857 amount : ''+(cents/100),
859 billSvc.voidBills(bill_ids).then(function() {
860 // TODO? $scope.session_voided = ...
862 // refresh bills and summary data
863 // note: no need to update payments
864 patronSvc.fetchUserStats();
866 egBilling.fetchXact(xact_id).then(function(xact) {
877 // batch-edit billing and payment notes, depending on 'type'
878 function editNotes(selected, type) {
879 var notes = selected.map(function(b){ return b.note }).join(',');
880 var ids = selected.map(function(b){ return b.id });
882 // show the note edit prompt
884 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
886 ok : function(value) {
888 var func = 'updateBillNotes';
889 if (type == 'payment') func = 'updatePaymentNotes';
891 billSvc[func](value, ids).then(function() {
892 if (type == 'payment') {
893 paymentGrid.refresh();
903 $scope.editBillNotes = function(selected) {
904 editNotes(selected, 'bill');
907 $scope.editPaymentNotes = function(selected) {
908 editNotes(selected, 'payment');
911 // -- retrieve our data
912 if ($scope.xact_tab == 'statement') {
913 //fetch combined billing statement data
914 billSvc.fetchStatement(xact_id).then(function(statement) {
915 //console.log(statement);
916 $scope.statement_data = statement;
919 $scope.total_circs = 0; // start with 0 instead of undefined
920 egBilling.fetchXact(xact_id).then(function(xact) {
923 var copyId = xact.circulation().target_copy().id();
925 egCore.pcrud.search('circbyyr',
926 {copy : copyId}, null, {atomic : true})
927 .then(function(counts) {
928 angular.forEach(counts, function(count) {
929 circ_count += Number(count.count());
931 $scope.total_circs = circ_count;
933 // set the title. only needs to be done on initial page load
934 if (xact.circulation()) {
935 if (xact.circulation().target_copy().call_number().id() == -1) {
936 $scope.title = xact.circulation().target_copy().dummy_title();
938 // TODO: shared bib service?
939 $scope.title = xact.circulation().target_copy()
940 .call_number().record().simple_record().title();
941 $scope.title_id = xact.circulation().target_copy()
942 .call_number().record().id();
949 .controller('BillHistoryCtrl',
950 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
951 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
953 $scope.initTab('bills', $routeParams.id);
954 billSvc.userId = $routeParams.id;
955 $scope.bill_tab = $routeParams.history_tab;
958 // link page controller actions defined by sub-controllers here
961 var start = new Date(); // now - 1 year
962 start.setFullYear(start.getFullYear() - 1),
965 xact_finish : new Date()
968 $scope.date_range = function() {
969 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
970 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
971 var today = new Date().toISOString().replace(/T.*/,'');
972 if (end == today) end = 'now';
978 .controller('BillXactHistoryCtrl',
979 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
980 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
982 // generate a grid query with the current date widget values.
983 function current_grid_query() {
986 {'summary.balance_owed' : {'<>' : 0}},
987 {'summary.last_payment_ts' : {'<>' : null}}
989 xact_start : {between : $scope.date_range()},
994 $scope.gridControls = {
995 selectedItems : function(){return []},
996 activateItem : function(item) {
997 $scope.showFullDetails([item]);
999 // this sets the query on page load
1000 setQuery : current_grid_query
1003 $scope.actions.apply_date_range = function() {
1004 // tells the grid to re-draw itself with the new query
1005 $scope.gridControls.setQuery(current_grid_query());
1008 // TODO; move me to service
1009 function selected_payment_info() {
1010 var info = {owed : 0, billed : 0, paid : 0};
1011 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1012 info.owed += Number(item['summary.balance_owed']) * 100;
1013 info.billed += Number(item['summary.total_owed']) * 100;
1014 info.paid += Number(item['summary.total_paid']) * 100;
1022 $scope.totals.selected_billed = function() {
1023 return selected_payment_info().billed;
1025 $scope.totals.selected_paid = function() {
1026 return selected_payment_info().paid;
1029 $scope.showFullDetails = function(all) {
1031 $location.path('/circ/patron/' +
1032 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1035 // For now, only adds billing to first selected item.
1036 // Could do batches later if needed
1037 $scope.addBilling = function(all) {
1039 egBilling.showBillDialog({
1040 xact : egCore.idl.flatToNestedHash(all[0]),
1041 patron : $scope.patron()
1042 }).then(function() {
1043 $scope.gridControls.refresh();
1044 patronSvc.fetchUserStats();
1049 $scope.printBills = function(selected) { // FIXME: refactor me
1050 if (!selected.length) return;
1051 // bills print receipt assumes nested hashes, but our grid
1052 // stores flattener data. Fetch the selected xacts as
1053 // fleshed pcrud objects and hashify.
1054 // (Consider an alternate approach..)
1055 var ids = selected.map(function(t){ return t.id });
1057 egCore.pcrud.search('mbt',
1059 {flesh : 5, flesh_fields : {
1060 'mbt' : ['summary', 'circulation'],
1061 'circ' : ['target_copy'],
1062 'acp' : ['call_number'],
1064 'bre' : ['simple_record']
1067 {authoritative : true}
1070 var cusr = patronSvc.current;
1071 egCore.print.print({
1072 context : 'receipt',
1073 template : 'bills_historical',
1075 transactions : xacts,
1076 current_location : egCore.idl.toHash(
1077 egCore.org.get(egCore.auth.user().ws_ou())),
1079 prefix : cusr.prefix(),
1080 first_given_name : cusr.first_given_name(),
1081 second_given_name : cusr.second_given_name(),
1082 family_name : cusr.family_name(),
1083 suffix : cusr.suffix(),
1084 card : { barcode : cusr.card().barcode() },
1085 expire_date : cusr.expire_date(),
1086 alias : cusr.alias(),
1087 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1088 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1096 billing_total : xact.billing_total(),
1097 billings : xact.billings(),
1098 grocery : xact.grocery(),
1100 payment_total : xact.payment_total(),
1101 payments : xact.payments(),
1102 summary : egCore.idl.toHash(xact.summary()),
1103 unrecovered : xact.unrecovered(),
1104 xact_finish : xact.xact_finish(),
1105 xact_start : xact.xact_start(),
1107 if (xact.circulation()) {
1108 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1109 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1111 xacts.push(newXact);
1117 .controller('BillPaymentHistoryCtrl',
1118 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1119 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1121 // generate a grid query with the current date widget values.
1122 function current_grid_query() {
1124 'payment_ts' : {between : $scope.date_range()},
1125 'xact.usr' : billSvc.userId
1129 $scope.gridControls = {
1130 selectedItems : function(){return []},
1131 activateItem : function(item) {
1132 $scope.showFullDetails([item]);
1134 setSort : function() {
1135 return [{'payment_ts' : 'DESC'}, 'id'];
1137 setQuery : current_grid_query
1140 $scope.actions.apply_date_range = function() {
1141 // tells the grid to re-draw itself with the new query
1142 $scope.gridControls.setQuery(current_grid_query());
1145 $scope.showFullDetails = function(all) {
1147 $location.path('/circ/patron/' +
1148 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1151 $scope.totals.selected_paid = function() {
1153 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1154 paid += Number(payment.amount) * 100;