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 // check receipt_on_pay setting default persisted
198 egCore.hatch.getItem('circ.bills.receiptonpay')
199 .then(function(rcptOnPay){
200 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
203 // pre-define list-returning funcs in case we access them
204 // before the grid instantiates
205 $scope.gridControls = {
206 focusRowSelector : false,
207 selectedItems : function(){return []},
208 allItems : function(){return []},
209 itemRetrieved : function(item) {
210 item.payment_pending = 0;
212 activateItem : function(item) {
213 $scope.showFullDetails([item]);
215 setQuery : function() {
217 usr : billSvc.userId,
219 'summary.balance_owed' : {'<>' : 0}
222 setSort : function() {
223 return ['xact_start'];
227 // Apply coloring to rows based on fines stop reason
228 $scope.colorizeBillsList = {
229 apply: function(item) {
230 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
231 if (item['circulation.stop_fines'] == 'LOST') {
233 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
234 return 'longoverdue-row';
236 return 'overdue-row';
242 // Status Icon Column definition
243 $scope.statusIconColumn = {
245 template: function(item) {
247 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
248 if (item['circulation.stop_fines'] == "LOST") {
249 icon = 'glyphicon-question-sign';
250 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
251 icon = 'glyphicon-exclamation-sign';
253 icon = 'glyphicon-time';
256 return "<i class='glyphicon " + icon + "'></i>"
260 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
262 // given a payment amount, determines how much of that is applied
263 // to selected transactions and how much is left over (change).
264 function pending_payment_info() {
265 var amt = $scope.payment_amount || 0;
266 if (amt >= $scope.owed_selected()) {
268 payment : $scope.owed_selected(),
269 change : amt - $scope.owed_selected()
272 return {payment : amt, change : 0};
275 // calculates amount owed, billed, and paid for selected items
276 // TODO: move me to service
277 function selected_payment_info() {
278 var info = {owed : 0, billed : 0, paid : 0};
279 angular.forEach($scope.gridControls.selectedItems(), function(item) {
280 info.owed += Number(item['summary.balance_owed']) * 100;
281 info.billed += Number(item['summary.total_owed']) * 100;
282 info.paid += Number(item['summary.total_paid']) * 100;
290 $scope.pending_payment = function() {
291 return pending_payment_info().payment;
293 $scope.pending_change = function() {
294 return pending_payment_info().change;
296 $scope.owed_selected = function() {
297 return selected_payment_info().owed;
299 $scope.billed_selected = function() {
300 return selected_payment_info().billed;
302 $scope.paid_selected = function() {
303 return selected_payment_info().paid;
305 $scope.refunds_available = function() {
307 angular.forEach($scope.gridControls.allItems(), function(item) {
308 if (item['summary.balance_owed'] < 0)
309 amount += item['summary.balance_owed'] * 100;
311 return -(amount / 100);
313 $scope.invalid_check_number = function() {
314 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
317 // update the item.payment_pending value each time the user
318 // selects different transactions to pay against.
320 function() {return $scope.gridControls.selectedItems()},
321 function() {updatePendingColumn()},
325 // update the item.payment_pending for each (selected)
326 // transaction any time the user-entered payment amount is modified
327 $scope.$watch('payment_amount', updatePendingColumn);
329 // updates the value of the payment_pending column in the grid.
330 // This has to be managed manually since the display value in the grid
331 // is derived from the value on the stored item and not the contents
332 // of our local scope variables.
333 function updatePendingColumn() {
334 // reset all to zero..
335 angular.forEach($scope.gridControls.allItems(),
336 function(item) {item.payment_pending = 0});
338 var payment_amount = $scope.pending_payment();
340 var selected = $scope.gridControls.selectedItems();
341 for (var i = 0; i < selected.length; i++) { // for/break
342 var item = selected[i];
343 var owed = Number(item['summary.balance_owed']);
345 if (payment_amount > owed) {
346 // pending payment exceeds balance of current item.
347 // pay the entire item.
348 item.payment_pending = owed;
349 payment_amount -= owed;
352 // balance owed on the current item matches or exceeds
353 // the pending payment. Apply the full remainder of
354 // the payment to this item.. and we're done.
355 item.payment_pending = payment_amount;
361 // builds payment arrays ([xact_id, ammount]) for all transactions
362 // which have a pending payment amount.
363 function generatePayments() {
365 angular.forEach($scope.gridControls.selectedItems(), function(item) {
366 if (item.payment_pending == 0) return;
367 payments.push([item.id, item.payment_pending]);
372 function refreshDisplay() {
373 patronSvc.fetchUserStats();
374 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
375 $scope.payment_amount = null;
376 $scope.gridControls.refresh();
379 // generates payments, collects user note if needed, and sends payment
381 function sendPayment(note, cc_args) {
382 $scope.applyingPayment = true;
383 var make_payments = generatePayments();
384 var patron_credit = $scope.convert_to_credit.isChecked ?
385 $scope.pending_change() : 0;
386 billSvc.applyPayment($scope.payment_type,
387 make_payments, note, $scope.check_number, cc_args, patron_credit)
389 function(payment_ids) {
391 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
393 $scope.payment_type, payment_ids, make_payments, note);
399 console.error('Payment was rejected: ' + msg);
402 .finally(function() { $scope.applyingPayment = false; })
405 $scope.onReceiptOnPayChanged = function(){
406 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
409 function printReceipt(type, payment_ids, payments_made, note) {
410 var payment_blobs = [];
411 var cusr = patronSvc.current;
413 angular.forEach(payments_made, function(payment) {
414 var xact_id = payment[0];
416 // find the original transaction in the grid..
417 var xact = $scope.gridControls.allItems().filter(
418 function(item) {return item.id == xact_id})[0];
421 xact : egCore.idl.flatToNestedHash(xact),
426 console.log(js2JSON(payment_blobs[0]));
428 // page data not yet refreshed, capture data from current scope
432 previous_balance : Number($scope.summary.balance_owed()),
433 payment_total : Number($scope.payment_amount),
434 payment_applied : $scope.pending_payment(),
435 amount_voided : Number($scope.session_voided),
436 change_given : $scope.pending_change(),
437 payments : payment_blobs,
438 current_location : egCore.idl.toHash(
439 egCore.org.get(egCore.auth.user().ws_ou()))
442 // Not a good idea to use patron_stats.fines for this; it's out of date
443 print_data.patron = {
444 prefix : cusr.prefix(),
445 first_given_name : cusr.first_given_name(),
446 second_given_name : cusr.second_given_name(),
447 family_name : cusr.family_name(),
448 suffix : cusr.suffix(),
449 pref_prefix : cusr.pref_prefix(),
450 pref_first_given_name : cusr.pref_first_given_name(),
451 pref_second_given_name : cusr.pref_second_given_name(),
452 pref_family_name : cusr.pref_family_name(),
453 pref_suffix : cusr.pref_suffix(),
454 card : { barcode : cusr.card().barcode() },
455 expire_date : cusr.expire_date(),
456 alias : cusr.alias(),
457 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
458 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
461 print_data.new_balance = (
462 print_data.previous_balance * 100 -
463 print_data.payment_applied * 100) / 100;
465 for (var i = 0; i < $scope.receipt_count; i++) {
468 template : 'bill_payment',
474 $scope.showHistory = function() {
475 $location.path('/circ/patron/' +
476 patronSvc.current.id() + '/bill_history/transactions');
479 // For now, only adds billing to first selected item.
480 // Could do batches later if needed
481 $scope.addBilling = function(all) {
483 egBilling.showBillDialog({
484 xact : egCore.idl.flatToNestedHash(all[0]),
485 patron : $scope.patron()
486 }).then(refreshDisplay);
490 $scope.showBillDialog = function($event) {
491 egBilling.showBillDialog({
492 patron : $scope.patron()
493 }).then(refreshDisplay);
496 // Select refunds adds all refunds to the existing selection.
497 // It does not /only/ select refunds
498 $scope.selectRefunds = function() {
499 var ids = $scope.gridControls.selectedItems().map(
500 function(i) { return i.id });
501 angular.forEach($scope.gridControls.allItems(), function(item) {
502 if (Number(item['summary.balance_owed']) < 0)
505 $scope.gridControls.selectItems(ids);
509 // determine on initial page load when all of the grid rows should
511 var selectOnLoad = true;
512 billSvc.fetchBillSettings().then(function(s) {
513 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
514 $scope.focus_payment = false; // de-focus the payment box
515 $scope.gridControls.focusRowSelector = true;
516 selectOnLoad = false;
517 // if somehow the grid finishes rendering before our settings
518 // arrive, manually de-select everything.
519 $scope.gridControls.selectItems([]);
521 if (s['ui.circ.billing.amount_warn']) {
522 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
524 if (s['ui.circ.billing.amount_limit']) {
525 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
527 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
528 $scope.disable_auto_print = Boolean(
529 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
532 if (s['circ.disable_patron_credit']) {
533 $scope.disablePatronCredit = true;
537 $scope.gridControls.allItemsRetrieved = function() {
539 selectOnLoad = false; // only for initial controller load.
540 // select all non-refund items
541 $scope.gridControls.selectItems(
542 $scope.gridControls.allItems()
543 .filter(function(i) {return i['summary.balance_owed'] > 0})
544 .map(function(i){return i.id})
551 $scope.printBills = function(selected) {
552 if (!selected.length) return;
553 // bills print receipt assumes nested hashes, but our grid
554 // stores flattener data. Fetch the selected xacts as
555 // fleshed pcrud objects and hashify.
556 // (Consider an alternate approach..)
557 var ids = selected.map(function(t){ return t.id });
559 egCore.pcrud.search('mbt',
561 {flesh : 5, flesh_fields : {
562 'mbt' : ['summary', 'circulation'],
563 'circ' : ['target_copy'],
564 'acp' : ['call_number'],
566 'bre' : ['simple_record']
569 {authoritative : true}
572 var cusr = patronSvc.current;
575 template : 'bills_current',
577 transactions : xacts,
578 current_location : egCore.idl.toHash(
579 egCore.org.get(egCore.auth.user().ws_ou())),
581 prefix : cusr.prefix(),
582 first_given_name : cusr.first_given_name(),
583 second_given_name : cusr.second_given_name(),
584 family_name : cusr.family_name(),
585 suffix : cusr.suffix(),
586 pref_prefix : cusr.pref_prefix(),
587 pref_first_given_name : cusr.pref_first_given_name(),
588 pref_second_given_name : cusr.pref_second_given_name(),
589 pref_family_name : cusr.pref_family_name(),
590 pref_suffix : cusr.pref_suffix(),
591 card : { barcode : cusr.card().barcode() },
592 expire_date : cusr.expire_date(),
593 alias : cusr.alias(),
594 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
595 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
603 billing_total : xact.billing_total(),
604 billings : xact.billings(),
605 grocery : xact.grocery(),
607 payment_total : xact.payment_total(),
608 payments : xact.payments(),
609 summary : egCore.idl.toHash(xact.summary()),
610 unrecovered : xact.unrecovered(),
611 xact_finish : xact.xact_finish(),
612 xact_start : xact.xact_start(),
614 if (xact.circulation()) {
615 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
616 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
623 $scope.applyPayment = function() {
625 if ($scope.payment_amount > $scope.max_amount ) {
627 egCore.strings.PAYMENT_OVER_MAX,
628 { max_amount : ''+$scope.max_amount,
630 $scope.payment_amount = 0;
637 verify_payment_amount().then(
638 function() { // amount confirmed
639 add_payment_note().then(function(pay_note) {
640 add_cc_args().then(function(cc_args) {
641 var note_text = pay_note ? pay_note.value || '' : null;
642 sendPayment(note_text, cc_args);
646 function() { // amount rejected
647 console.warn('payment amount rejected');
648 $scope.payment_amount = 0;
653 function verify_payment_amount() {
654 if ($scope.payment_amount < $scope.warn_amount)
657 return egConfirmDialog.open(
658 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
659 egCore.strings.PAYMENT_WARN_AMOUNT,
660 {payment_amount : ''+$scope.payment_amount}
664 function add_payment_note() {
665 if (!$scope.annotate_payment) return $q.when();
666 return egPromptDialog.open(
667 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
670 function add_cc_args() {
671 if ($scope.payment_type != 'credit_card_payment')
674 return $uibModal.open({
675 templateUrl : './circ/patron/t_cc_payment_dialog',
678 '$scope','$uibModalInstance',
679 function($scope , $uibModalInstance) {
683 where_process : '1', // internal=1 ; external=0
684 type : 'VISA', // external only
685 billing_first : patronSvc.current.first_given_name(),
686 billing_last : patronSvc.current.family_name()
690 var addr = patronSvc.current.billing_address() ||
691 patronSvc.current.mailing_address();
693 var cc = $scope.context.cc;
694 cc.billing_address = addr.street1() +
695 (addr.street2() ? ' ' + addr.street2() : '');
696 cc.billing_city = addr.city();
697 cc.billing_state = addr.state();
698 cc.billing_zip = addr.post_code();
701 $scope.ok = function() {
702 // CC payment form is not a <form>,
703 // so apply validation manually.
704 if ( $scope.context.cc.where_process == 0 &&
705 !$scope.context.cc.approval_code)
708 $uibModalInstance.close($scope.context.cc);
711 $scope.cancel = function() {
712 $uibModalInstance.dismiss();
719 $scope.voidAllBillings = function(items) {
723 angular.forEach(items, function(item) {
725 billSvc.fetchBills(item.id).then(function(bills) {
726 angular.forEach(bills, function(b) {
727 if (b.voided() != 't') {
728 cents += b.amount() * 100;
729 bill_ids.push(b.id())
733 if (bill_ids.length == 0) {
742 $q.all(promises).then(function(){
743 egCore.audio.play('warning.circ.void_billings_confirmation');
744 egConfirmDialog.open(
745 egCore.strings.CONFIRM_VOID_BILLINGS, '',
746 { billIds : ''+bill_ids,
747 amount : ''+(cents/100),
749 billSvc.voidBills(bill_ids).then(function() {
750 $scope.session_voided =
751 ($scope.session_voided * 100 + cents) / 100;
760 $scope.adjustToZero = function(items) {
761 if (items.length == 0) return;
763 var ids = items.map(function(item) {return item.id});
765 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
766 egConfirmDialog.open(
767 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
770 billSvc.adjustBillsToZero(ids).then(function() {
779 // note this is functionally equivalent to selecting a neg. transaction
780 // then clicking Apply Payment -- this just adds a speed bump (ditto
782 $scope.refundXact = function(all) {
783 var items = all.filter(function(item) {
784 return item['summary.balance_owed'] < 0
787 if (items.length == 0) return;
789 var ids = items.map(function(item) {return item.id});
791 egCore.audio.play('warning.circ.refund_confirmation');
792 egConfirmDialog.open(
793 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
796 // reset the received payment amount. this ensures
797 // we're not mingling payments with refunds.
798 $scope.payment_amount = 0;
804 // direct the user to the transaction details page
805 $scope.showFullDetails = function(all) {
807 $location.path('/circ/patron/' +
808 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
811 $scope.activateBill = function(xact) {
812 $scope.showFullDetails([xact]);
818 * Displays details of a single transaction
820 .controller('XactDetailsCtrl',
821 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
822 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
824 $scope.initTab('bills', $routeParams.id);
825 var xact_id = $routeParams.xact_id;
826 $scope.xact_tab = $routeParams.xact_tab;
828 var xactGrid = $scope.xactGridControls = {
829 setQuery : function() { return {xact : xact_id} },
830 setSort : function() { return ['billing_ts'] }
833 var paymentGrid = $scope.paymentGridControls = {
834 setQuery : function() { return {xact : xact_id} },
835 setSort : function() { return ['payment_ts'] }
839 $scope.voidBillings = function(bill_list) {
842 angular.forEach(bill_list, function(b) {
843 if (b.voided != 't') {
844 cents += b.amount * 100;
849 if (bill_ids.length == 0) {
854 egCore.audio.play('warning.circ.void_billings_confirmation');
855 egConfirmDialog.open(
856 egCore.strings.CONFIRM_VOID_BILLINGS, '',
857 { billIds : ''+bill_ids,
858 amount : ''+(cents/100),
860 billSvc.voidBills(bill_ids).then(function() {
861 // TODO? $scope.session_voided = ...
863 // refresh bills and summary data
864 // note: no need to update payments
865 patronSvc.fetchUserStats();
867 egBilling.fetchXact(xact_id).then(function(xact) {
878 // batch-edit billing and payment notes, depending on 'type'
879 function editNotes(selected, type) {
880 var notes = selected.map(function(b){ return b.note }).join(',');
881 var ids = selected.map(function(b){ return b.id });
883 // show the note edit prompt
885 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
887 ok : function(value) {
889 var func = 'updateBillNotes';
890 if (type == 'payment') func = 'updatePaymentNotes';
892 billSvc[func](value, ids).then(function() {
893 if (type == 'payment') {
894 paymentGrid.refresh();
904 $scope.editBillNotes = function(selected) {
905 editNotes(selected, 'bill');
908 $scope.editPaymentNotes = function(selected) {
909 editNotes(selected, 'payment');
912 // -- retrieve our data
913 if ($scope.xact_tab == 'statement') {
914 //fetch combined billing statement data
915 billSvc.fetchStatement(xact_id).then(function(statement) {
916 //console.log(statement);
917 $scope.statement_data = statement;
920 $scope.total_circs = 0; // start with 0 instead of undefined
921 egBilling.fetchXact(xact_id).then(function(xact) {
924 var copyId = xact.circulation().target_copy().id();
926 egCore.pcrud.search('circbyyr',
927 {copy : copyId}, null, {atomic : true})
928 .then(function(counts) {
929 angular.forEach(counts, function(count) {
930 circ_count += Number(count.count());
932 $scope.total_circs = circ_count;
934 // set the title. only needs to be done on initial page load
935 if (xact.circulation()) {
936 if (xact.circulation().target_copy().call_number().id() == -1) {
937 $scope.title = xact.circulation().target_copy().dummy_title();
939 // TODO: shared bib service?
940 $scope.title = xact.circulation().target_copy()
941 .call_number().record().simple_record().title();
942 $scope.title_id = xact.circulation().target_copy()
943 .call_number().record().id();
950 .controller('BillHistoryCtrl',
951 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
952 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
954 $scope.initTab('bills', $routeParams.id);
955 billSvc.userId = $routeParams.id;
956 $scope.bill_tab = $routeParams.history_tab;
959 // link page controller actions defined by sub-controllers here
962 var start = new Date(); // now - 1 year
963 start.setFullYear(start.getFullYear() - 1),
966 xact_finish : new Date()
969 $scope.date_range = function() {
970 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
971 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
972 var today = new Date().toISOString().replace(/T.*/,'');
973 if (end == today) end = 'now';
979 .controller('BillXactHistoryCtrl',
980 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
981 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
983 // generate a grid query with the current date widget values.
984 function current_grid_query() {
987 {'summary.balance_owed' : {'<>' : 0}},
988 {'summary.last_payment_ts' : {'<>' : null}}
990 xact_start : {between : $scope.date_range()},
995 $scope.gridControls = {
996 selectedItems : function(){return []},
997 activateItem : function(item) {
998 $scope.showFullDetails([item]);
1000 // this sets the query on page load
1001 setQuery : current_grid_query
1004 $scope.actions.apply_date_range = function() {
1005 // tells the grid to re-draw itself with the new query
1006 $scope.gridControls.setQuery(current_grid_query());
1009 // TODO; move me to service
1010 function selected_payment_info() {
1011 var info = {owed : 0, billed : 0, paid : 0};
1012 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1013 info.owed += Number(item['summary.balance_owed']) * 100;
1014 info.billed += Number(item['summary.total_owed']) * 100;
1015 info.paid += Number(item['summary.total_paid']) * 100;
1023 $scope.totals.selected_billed = function() {
1024 return selected_payment_info().billed;
1026 $scope.totals.selected_paid = function() {
1027 return selected_payment_info().paid;
1030 $scope.showFullDetails = function(all) {
1032 $location.path('/circ/patron/' +
1033 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1036 // For now, only adds billing to first selected item.
1037 // Could do batches later if needed
1038 $scope.addBilling = function(all) {
1040 egBilling.showBillDialog({
1041 xact : egCore.idl.flatToNestedHash(all[0]),
1042 patron : $scope.patron()
1043 }).then(function() {
1044 $scope.gridControls.refresh();
1045 patronSvc.fetchUserStats();
1050 $scope.printBills = function(selected) { // FIXME: refactor me
1051 if (!selected.length) return;
1052 // bills print receipt assumes nested hashes, but our grid
1053 // stores flattener data. Fetch the selected xacts as
1054 // fleshed pcrud objects and hashify.
1055 // (Consider an alternate approach..)
1056 var ids = selected.map(function(t){ return t.id });
1058 egCore.pcrud.search('mbt',
1060 {flesh : 5, flesh_fields : {
1061 'mbt' : ['summary', 'circulation'],
1062 'circ' : ['target_copy'],
1063 'acp' : ['call_number'],
1065 'bre' : ['simple_record']
1068 {authoritative : true}
1071 var cusr = patronSvc.current;
1072 egCore.print.print({
1073 context : 'receipt',
1074 template : 'bills_historical',
1076 transactions : xacts,
1077 current_location : egCore.idl.toHash(
1078 egCore.org.get(egCore.auth.user().ws_ou())),
1080 prefix : cusr.prefix(),
1081 pref_prefix : cusr.pref_prefix(),
1082 pref_first_given_name : cusr.pref_first_given_name(),
1083 pref_second_given_name : cusr.pref_second_given_name(),
1084 pref_family_name : cusr.pref_family_name(),
1085 pref_suffix : cusr.pref_suffix(),
1086 first_given_name : cusr.first_given_name(),
1087 second_given_name : cusr.second_given_name(),
1088 family_name : cusr.family_name(),
1089 suffix : cusr.suffix(),
1090 card : { barcode : cusr.card().barcode() },
1091 expire_date : cusr.expire_date(),
1092 alias : cusr.alias(),
1093 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1094 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1102 billing_total : xact.billing_total(),
1103 billings : xact.billings(),
1104 grocery : xact.grocery(),
1106 payment_total : xact.payment_total(),
1107 payments : xact.payments(),
1108 summary : egCore.idl.toHash(xact.summary()),
1109 unrecovered : xact.unrecovered(),
1110 xact_finish : xact.xact_finish(),
1111 xact_start : xact.xact_start(),
1113 if (xact.circulation()) {
1114 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1115 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1117 xacts.push(newXact);
1123 .controller('BillPaymentHistoryCtrl',
1124 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1125 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1127 // generate a grid query with the current date widget values.
1128 function current_grid_query() {
1130 'payment_ts' : {between : $scope.date_range()},
1131 'xact.usr' : billSvc.userId
1135 $scope.gridControls = {
1136 selectedItems : function(){return []},
1137 activateItem : function(item) {
1138 $scope.showFullDetails([item]);
1140 setSort : function() {
1141 return [{'payment_ts' : 'DESC'}, 'id'];
1143 setQuery : current_grid_query
1146 $scope.actions.apply_date_range = function() {
1147 // tells the grid to re-draw itself with the new query
1148 $scope.gridControls.setQuery(current_grid_query());
1151 $scope.showFullDetails = function(all) {
1153 $location.path('/circ/patron/' +
1154 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1157 $scope.totals.selected_paid = function() {
1159 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1160 paid += Number(payment.amount) * 100;