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 'debit_card_payment' : msg = egCore.strings.EG_WORK_LOG_DEBIT_CARD_PAYMENT; break;
64 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
65 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
66 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
67 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
71 'action' : 'paid_bill',
72 'patron_id' : service.userId,
73 'total_amount' : total
77 // payment API returns the update xact id so we can track it
78 // for future payments without having to refresh the user.
79 patronSvc.current.last_xact_id(resp.last_xact_id);
81 // reload patron data if credit balance has changed:
82 if(type === 'credit_payment' || patron_credit){ patronSvc.refreshPrimary(); }
88 service.fetchBills = function(xact_id) {
90 return egCore.pcrud.search('mb',
91 {xact : xact_id}, null,
92 {authoritative : true}
94 function() {return bills},
96 function(bill) {bills.push(bill); return bill}
100 service.fetchStatement = function(xact_id) {
101 return egCore.net.request(
103 'open-ils.circ.money.statement.retrieve',
104 egCore.auth.token(), xact_id
105 ).then(function(resp) {
106 if (evt = egCore.evt.parse(resp)) return alert(evt);
111 // TODO: no longer needed?
112 service.fetchPayments = function(xact_id) {
113 return egCore.net.request(
115 'open-ils.circ.money.payment.retrieve.all.authoritative',
116 egCore.auth.token(), xact_id
120 service.voidBills = function(bill_ids) {
121 return egCore.net.requestWithParamList(
123 'open-ils.circ.money.billing.void',
124 [egCore.auth.token()].concat(bill_ids)
125 ).then(function(resp) {
126 if (evt = egCore.evt.parse(resp)) return alert(evt);
131 service.adjustBillsToZero = function(bill_ids) {
132 return egCore.net.request(
134 'open-ils.circ.money.billable_xact.adjust_to_zero',
137 ).then(function(resp) {
138 if (evt = egCore.evt.parse(resp)) return alert(evt);
143 service.updateBillNotes = function(note, ids) {
144 return egCore.net.requestWithParamList(
146 'open-ils.circ.money.billing.note.edit',
147 [egCore.auth.token(), note].concat(ids)
148 ).then(function(resp) {
149 if (evt = egCore.evt.parse(resp)) return alert(evt);
154 service.updatePaymentNotes = function(note, ids) {
155 return egCore.net.requestWithParamList(
157 'open-ils.circ.money.payment.note.edit',
158 [egCore.auth.token(), note].concat(ids)
159 ).then(function(resp) {
160 if (evt = egCore.evt.parse(resp)) return alert(evt);
172 .controller('PatronBillsCtrl',
173 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
174 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
175 'egBilling','$uibModal',
176 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
177 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
178 egBilling , $uibModal) {
180 $scope.initTab('bills', $routeParams.id);
181 billSvc.userId = $routeParams.id;
183 // set up some defaults
184 $scope.check_number = null;
185 $scope.payment_amount = null;
186 $scope.session_voided = 0;
187 $scope.payment_type = 'cash_payment';
188 $scope.focus_payment = true;
189 $scope.annotate_payment = false;
190 $scope.receipt_count = 1;
191 $scope.receipt_on_pay = { isChecked: false };
192 $scope.convert_to_credit = {isChecked: false};
193 $scope.warn_amount = 1000;
194 $scope.max_amount = 100000;
195 $scope.amount_verified = false;
196 $scope.disable_auto_print = false;
198 // Load persistant settings
199 egCore.hatch.getItem('circ.bills.receiptonpay')
200 .then(function(rcptOnPay){
201 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
204 egCore.hatch.getItem('eg.circ.bills.annotatepayment')
205 .then(function(annoPay){
206 if (annoPay) $scope.annotate_payment = annoPay;
209 // pre-define list-returning funcs in case we access them
210 // before the grid instantiates
211 $scope.gridControls = {
212 focusRowSelector : false,
213 selectedItems : function(){return []},
214 allItems : function(){return []},
215 itemRetrieved : function(item) {
216 item.payment_pending = 0;
218 activateItem : function(item) {
219 $scope.showFullDetails([item]);
221 setQuery : function() {
223 usr : billSvc.userId,
225 'summary.balance_owed' : {'<>' : 0}
228 setSort : function() {
229 return ['xact_start'];
233 // Apply coloring to rows based on fines stop reason
234 $scope.colorizeBillsList = {
235 apply: function(item) {
236 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
237 if (item['circulation.stop_fines'] == 'LOST') {
239 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
240 return 'longoverdue-row';
242 return 'overdue-row';
248 // Status Icon Column definition
249 $scope.statusIconColumn = {
251 template: function(item) {
253 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
254 if (item['circulation.stop_fines'] == "LOST") {
255 icon = 'glyphicon-question-sign';
256 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
257 icon = 'glyphicon-exclamation-sign';
259 icon = 'glyphicon-time';
262 return "<i class='glyphicon " + icon + "'></i>"
266 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
268 // given a payment amount, determines how much of that is applied
269 // to selected transactions and how much is left over (change).
270 function pending_payment_info() {
271 var amt = $scope.payment_amount || 0;
272 if (amt >= $scope.owed_selected()) {
274 payment : $scope.owed_selected(),
275 change : amt - $scope.owed_selected()
278 return {payment : amt, change : 0};
281 // calculates amount owed, billed, and paid for selected items
282 // TODO: move me to service
283 function selected_payment_info() {
284 var info = {owed : 0, billed : 0, paid : 0};
285 angular.forEach($scope.gridControls.selectedItems(), function(item) {
286 info.owed += Number(item['summary.balance_owed']) * 100;
287 info.billed += Number(item['summary.total_owed']) * 100;
288 info.paid += Number(item['summary.total_paid']) * 100;
296 $scope.pending_payment = function() {
297 return pending_payment_info().payment;
299 $scope.pending_change = function() {
300 return pending_payment_info().change;
302 $scope.owed_selected = function() {
303 return selected_payment_info().owed;
305 $scope.billed_selected = function() {
306 return selected_payment_info().billed;
308 $scope.paid_selected = function() {
309 return selected_payment_info().paid;
311 $scope.refunds_available = function() {
313 angular.forEach($scope.gridControls.allItems(), function(item) {
314 if (item['summary.balance_owed'] < 0)
315 amount += item['summary.balance_owed'] * 100;
317 return -(amount / 100);
319 $scope.invalid_check_number = function() {
320 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
323 // update the item.payment_pending value each time the user
324 // selects different transactions to pay against.
326 function() {return $scope.gridControls.selectedItems()},
327 function() {updatePendingColumn()},
331 // update the item.payment_pending for each (selected)
332 // transaction any time the user-entered payment amount is modified
333 $scope.$watch('payment_amount', updatePendingColumn);
335 // updates the value of the payment_pending column in the grid.
336 // This has to be managed manually since the display value in the grid
337 // is derived from the value on the stored item and not the contents
338 // of our local scope variables.
339 function updatePendingColumn() {
340 // reset all to zero..
341 angular.forEach($scope.gridControls.allItems(),
342 function(item) {item.payment_pending = 0});
344 var payment_amount = $scope.pending_payment();
346 var selected = $scope.gridControls.selectedItems();
347 for (var i = 0; i < selected.length; i++) { // for/break
348 var item = selected[i];
349 var owed = Number(item['summary.balance_owed']);
351 if (payment_amount > owed) {
352 // pending payment exceeds balance of current item.
353 // pay the entire item.
354 item.payment_pending = owed;
355 payment_amount -= owed;
358 // balance owed on the current item matches or exceeds
359 // the pending payment. Apply the full remainder of
360 // the payment to this item.. and we're done.
361 item.payment_pending = payment_amount;
367 // builds payment arrays ([xact_id, ammount]) for all transactions
368 // which have a pending payment amount.
369 function generatePayments() {
371 angular.forEach($scope.gridControls.selectedItems(), function(item) {
372 if (item.payment_pending == 0) return;
373 payments.push([item.id, item.payment_pending]);
378 function refreshDisplay() {
379 patronSvc.fetchUserStats();
380 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
381 $scope.payment_amount = null;
382 $scope.gridControls.refresh();
385 // generates payments, collects user note if needed, and sends payment
387 function sendPayment(note, cc_args) {
388 $scope.applyingPayment = true;
389 var make_payments = generatePayments();
390 var patron_credit = $scope.convert_to_credit.isChecked ?
391 $scope.pending_change() : 0;
392 billSvc.applyPayment($scope.payment_type,
393 make_payments, note, $scope.check_number, cc_args, patron_credit)
395 function(payment_ids) {
397 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
399 $scope.payment_type, payment_ids, make_payments, note);
405 console.error('Payment was rejected: ' + msg);
408 .finally(function() { $scope.applyingPayment = false; })
411 $scope.onReceiptOnPayChanged = function(){
412 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
415 $scope.onAnnotatePaymentChanged = function(){
416 egCore.hatch.setItem('eg.circ.bills.annotatepayment', $scope.annotate_payment);
419 function printReceipt(type, payment_ids, payments_made, note) {
420 var payment_blobs = [];
421 var cusr = patronSvc.current;
423 angular.forEach(payments_made, function(payment) {
424 var xact_id = payment[0];
426 // find the original transaction in the grid..
427 var xact = $scope.gridControls.allItems().filter(
428 function(item) {return item.id == xact_id})[0];
431 xact : egCore.idl.flatToNestedHash(xact),
436 console.log(js2JSON(payment_blobs[0]));
438 // page data not yet refreshed, capture data from current scope
442 previous_balance : Number($scope.summary.balance_owed()),
443 payment_total : Number($scope.payment_amount),
444 payment_applied : $scope.pending_payment(),
445 amount_voided : Number($scope.session_voided),
446 change_given : $scope.pending_change(),
447 payments : payment_blobs,
448 current_location : egCore.idl.toHash(
449 egCore.org.get(egCore.auth.user().ws_ou()))
452 // Not a good idea to use patron_stats.fines for this; it's out of date
453 print_data.patron = {
454 prefix : cusr.prefix(),
455 first_given_name : cusr.first_given_name(),
456 second_given_name : cusr.second_given_name(),
457 family_name : cusr.family_name(),
458 suffix : cusr.suffix(),
459 pref_prefix : cusr.pref_prefix(),
460 pref_first_given_name : cusr.pref_first_given_name(),
461 pref_second_given_name : cusr.pref_second_given_name(),
462 pref_family_name : cusr.pref_family_name(),
463 pref_suffix : cusr.pref_suffix(),
464 card : { barcode : cusr.card().barcode() },
465 expire_date : cusr.expire_date(),
466 alias : cusr.alias(),
467 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
468 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
471 print_data.new_balance = (
472 print_data.previous_balance * 100 -
473 print_data.payment_applied * 100) / 100;
475 for (var i = 0; i < $scope.receipt_count; i++) {
478 template : 'bill_payment',
484 $scope.showHistory = function() {
485 $location.path('/circ/patron/' +
486 patronSvc.current.id() + '/bill_history/transactions');
489 // For now, only adds billing to first selected item.
490 // Could do batches later if needed
491 $scope.addBilling = function(all) {
493 egBilling.showBillDialog({
494 xact : egCore.idl.flatToNestedHash(all[0]),
495 patron : $scope.patron()
496 }).then(refreshDisplay);
500 $scope.showBillDialog = function($event) {
501 egBilling.showBillDialog({
502 patron : $scope.patron()
503 }).then(refreshDisplay);
506 // Select refunds adds all refunds to the existing selection.
507 // It does not /only/ select refunds
508 $scope.selectRefunds = function() {
509 var ids = $scope.gridControls.selectedItems().map(
510 function(i) { return i.id });
511 angular.forEach($scope.gridControls.allItems(), function(item) {
512 if (Number(item['summary.balance_owed']) < 0)
515 $scope.gridControls.selectItems(ids);
519 // determine on initial page load when all of the grid rows should
521 var selectOnLoad = true;
522 billSvc.fetchBillSettings().then(function(s) {
523 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
524 $scope.focus_payment = false; // de-focus the payment box
525 $scope.gridControls.focusRowSelector = true;
526 selectOnLoad = false;
527 // if somehow the grid finishes rendering before our settings
528 // arrive, manually de-select everything.
529 $scope.gridControls.selectItems([]);
531 if (s['ui.circ.billing.amount_warn']) {
532 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
534 if (s['ui.circ.billing.amount_limit']) {
535 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
537 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
538 $scope.disable_auto_print = Boolean(
539 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
542 if (s['circ.disable_patron_credit']) {
543 $scope.disablePatronCredit = true;
547 $scope.gridControls.allItemsRetrieved = function() {
549 selectOnLoad = false; // only for initial controller load.
550 // select all non-refund items
551 $scope.gridControls.selectItems(
552 $scope.gridControls.allItems()
553 .filter(function(i) {return i['summary.balance_owed'] > 0})
554 .map(function(i){return i.id})
561 $scope.printBills = function(selected) {
562 if (!selected.length) return;
563 // bills print receipt assumes nested hashes, but our grid
564 // stores flattener data. Fetch the selected xacts as
565 // fleshed pcrud objects and hashify.
566 // (Consider an alternate approach..)
567 var ids = selected.map(function(t){ return t.id });
569 egCore.pcrud.search('mbt',
571 {flesh : 5, flesh_fields : {
572 'mbt' : ['summary', 'circulation'],
573 'circ' : ['target_copy'],
574 'acp' : ['call_number'],
576 'bre' : ['simple_record']
579 {authoritative : true}
582 var cusr = patronSvc.current;
585 template : 'bills_current',
587 transactions : xacts,
588 current_location : egCore.idl.toHash(
589 egCore.org.get(egCore.auth.user().ws_ou())),
591 prefix : cusr.prefix(),
592 first_given_name : cusr.first_given_name(),
593 second_given_name : cusr.second_given_name(),
594 family_name : cusr.family_name(),
595 suffix : cusr.suffix(),
596 pref_prefix : cusr.pref_prefix(),
597 pref_first_given_name : cusr.pref_first_given_name(),
598 pref_second_given_name : cusr.pref_second_given_name(),
599 pref_family_name : cusr.pref_family_name(),
600 pref_suffix : cusr.pref_suffix(),
601 card : { barcode : cusr.card().barcode() },
602 expire_date : cusr.expire_date(),
603 alias : cusr.alias(),
604 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
605 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
613 billing_total : xact.billing_total(),
614 billings : xact.billings(),
615 grocery : xact.grocery(),
617 payment_total : xact.payment_total(),
618 payments : xact.payments(),
619 summary : egCore.idl.toHash(xact.summary()),
620 unrecovered : xact.unrecovered(),
621 xact_finish : xact.xact_finish(),
622 xact_start : xact.xact_start(),
624 if (xact.circulation()) {
625 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
626 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
633 $scope.applyPayment = function() {
635 if ($scope.payment_amount > $scope.max_amount ) {
637 egCore.strings.PAYMENT_OVER_MAX,
638 { max_amount : ''+$scope.max_amount,
640 $scope.payment_amount = 0;
647 verify_payment_amount().then(
648 function() { // amount confirmed
649 add_payment_note().then(function(pay_note) {
650 add_cc_args().then(function(cc_args) {
651 var note_text = pay_note ? pay_note.value || '' : null;
652 sendPayment(note_text, cc_args);
656 function() { // amount rejected
657 console.warn('payment amount rejected');
658 $scope.payment_amount = 0;
663 function verify_payment_amount() {
664 if ($scope.payment_amount < $scope.warn_amount)
667 return egConfirmDialog.open(
668 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
669 egCore.strings.PAYMENT_WARN_AMOUNT,
670 {payment_amount : ''+$scope.payment_amount}
674 function add_payment_note() {
675 if (!$scope.annotate_payment) return $q.when();
676 return egPromptDialog.open(
677 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
680 function add_cc_args() {
681 if ($scope.payment_type != 'credit_card_payment')
684 return $uibModal.open({
685 templateUrl : './circ/patron/t_cc_payment_dialog',
688 '$scope','$uibModalInstance',
689 function($scope , $uibModalInstance) {
693 where_process : '1', // internal=1 ; external=0
694 type : 'VISA', // external only
695 billing_first : patronSvc.current.first_given_name(),
696 billing_last : patronSvc.current.family_name()
700 var addr = patronSvc.current.billing_address() ||
701 patronSvc.current.mailing_address();
703 var cc = $scope.context.cc;
704 cc.billing_address = addr.street1() +
705 (addr.street2() ? ' ' + addr.street2() : '');
706 cc.billing_city = addr.city();
707 cc.billing_state = addr.state();
708 cc.billing_zip = addr.post_code();
711 $scope.ok = function() {
712 // CC payment form is not a <form>,
713 // so apply validation manually.
714 if ( $scope.context.cc.where_process == 0 &&
715 !$scope.context.cc.approval_code)
718 $uibModalInstance.close($scope.context.cc);
721 $scope.cancel = function() {
722 $uibModalInstance.dismiss();
729 $scope.voidAllBillings = function(items) {
733 angular.forEach(items, function(item) {
735 billSvc.fetchBills(item.id).then(function(bills) {
736 angular.forEach(bills, function(b) {
737 if (b.voided() != 't') {
738 cents += b.amount() * 100;
739 bill_ids.push(b.id())
743 if (bill_ids.length == 0) {
752 $q.all(promises).then(function(){
753 egCore.audio.play('warning.circ.void_billings_confirmation');
754 egConfirmDialog.open(
755 egCore.strings.CONFIRM_VOID_BILLINGS, '',
756 { billIds : ''+bill_ids,
757 amount : ''+(cents/100),
759 billSvc.voidBills(bill_ids).then(function() {
760 $scope.session_voided =
761 ($scope.session_voided * 100 + cents) / 100;
770 $scope.adjustToZero = function(items) {
771 if (items.length == 0) return;
773 var ids = items.map(function(item) {return item.id});
775 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
776 egConfirmDialog.open(
777 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
780 billSvc.adjustBillsToZero(ids).then(function() {
789 // note this is functionally equivalent to selecting a neg. transaction
790 // then clicking Apply Payment -- this just adds a speed bump (ditto
792 $scope.refundXact = function(all) {
793 var items = all.filter(function(item) {
794 return item['summary.balance_owed'] < 0
797 if (items.length == 0) return;
799 var ids = items.map(function(item) {return item.id});
801 egCore.audio.play('warning.circ.refund_confirmation');
802 egConfirmDialog.open(
803 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
806 // reset the received payment amount. this ensures
807 // we're not mingling payments with refunds.
808 $scope.payment_amount = 0;
814 // direct the user to the transaction details page
815 $scope.showFullDetails = function(all) {
816 var lastClicked = $scope.gridControls.contextMenuItem();
818 $location.path('/circ/patron/' +
819 patronSvc.current.id() + '/bill/' + lastClicked + '/statement');
821 $location.path('/circ/patron/' +
822 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
827 $scope.activateBill = function(xact) {
828 $scope.showFullDetails([xact]);
834 * Displays details of a single transaction
836 .controller('XactDetailsCtrl',
837 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
838 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
840 $scope.initTab('bills', $routeParams.id);
841 var xact_id = $routeParams.xact_id;
842 $scope.xact_tab = $routeParams.xact_tab;
844 var xactGrid = $scope.xactGridControls = {
845 setQuery : function() { return {xact : xact_id} },
846 setSort : function() { return ['billing_ts'] }
849 var paymentGrid = $scope.paymentGridControls = {
850 setQuery : function() { return {xact : xact_id} },
851 setSort : function() { return ['payment_ts'] }
855 $scope.voidBillings = function(bill_list) {
858 angular.forEach(bill_list, function(b) {
859 if (b.voided != 't') {
860 cents += b.amount * 100;
865 if (bill_ids.length == 0) {
870 egCore.audio.play('warning.circ.void_billings_confirmation');
871 egConfirmDialog.open(
872 egCore.strings.CONFIRM_VOID_BILLINGS, '',
873 { billIds : ''+bill_ids,
874 amount : ''+(cents/100),
876 billSvc.voidBills(bill_ids).then(function() {
877 // TODO? $scope.session_voided = ...
879 // refresh bills and summary data
880 // note: no need to update payments
881 patronSvc.fetchUserStats();
883 egBilling.fetchXact(xact_id).then(function(xact) {
894 // batch-edit billing and payment notes, depending on 'type'
895 function editNotes(selected, type) {
896 var notes = selected.map(function(b){ return b.note }).join(',');
897 var ids = selected.map(function(b){ return b.id });
899 // show the note edit prompt
901 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
903 ok : function(value) {
905 var func = 'updateBillNotes';
906 if (type == 'payment') func = 'updatePaymentNotes';
908 billSvc[func](value, ids).then(function() {
909 if (type == 'payment') {
910 paymentGrid.refresh();
920 $scope.editBillNotes = function(selected) {
921 editNotes(selected, 'bill');
924 $scope.editPaymentNotes = function(selected) {
925 editNotes(selected, 'payment');
928 // -- retrieve our data
929 if ($scope.xact_tab == 'statement') {
930 //fetch combined billing statement data
931 billSvc.fetchStatement(xact_id).then(function(statement) {
932 //console.log(statement);
933 $scope.statement_data = statement;
936 $scope.total_circs = 0; // start with 0 instead of undefined
937 egBilling.fetchXact(xact_id).then(function(xact) {
940 var copyId = xact.circulation().target_copy().id();
942 egCore.pcrud.search('circbyyr',
943 {copy : copyId}, null, {atomic : true})
944 .then(function(counts) {
945 angular.forEach(counts, function(count) {
946 circ_count += Number(count.count());
948 $scope.total_circs = circ_count;
950 // set the title. only needs to be done on initial page load
951 if (xact.circulation()) {
952 if (xact.circulation().target_copy().call_number().id() == -1) {
953 $scope.title = xact.circulation().target_copy().dummy_title();
955 // TODO: shared bib service?
956 $scope.title = xact.circulation().target_copy()
957 .call_number().record().simple_record().title();
958 $scope.title_id = xact.circulation().target_copy()
959 .call_number().record().id();
966 .controller('BillHistoryCtrl',
967 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
968 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
970 $scope.initTab('bills', $routeParams.id);
971 billSvc.userId = $routeParams.id;
972 $scope.bill_tab = $routeParams.history_tab;
975 // link page controller actions defined by sub-controllers here
978 var start = new Date(); // now - 1 year
979 start.setFullYear(start.getFullYear() - 1),
982 xact_finish : new Date()
985 $scope.date_range = function() {
986 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
987 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
988 var today = new Date().toISOString().replace(/T.*/,'');
989 if (end == today) end = 'now';
995 .controller('BillXactHistoryCtrl',
996 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
997 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
999 // generate a grid query with the current date widget values.
1000 function current_grid_query() {
1003 {'summary.balance_owed' : {'<>' : 0}},
1004 {'summary.last_payment_ts' : {'<>' : null}}
1006 xact_start : {between : $scope.date_range()},
1007 usr : billSvc.userId
1011 $scope.gridControls = {
1012 selectedItems : function(){return []},
1013 activateItem : function(item) {
1014 $scope.showFullDetails([item]);
1016 // this sets the query on page load
1017 setQuery : current_grid_query
1020 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1021 if (new_date !== old_date && new_date) {
1022 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1023 $scope.dates.xact_finish = new_date;
1025 $scope.actions.apply_date_range();
1029 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1030 if (new_date !== old_date && new_date) {
1031 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1032 $scope.dates.xact_start = new_date;
1034 $scope.actions.apply_date_range();
1039 $scope.actions.apply_date_range = function() {
1040 // tells the grid to re-draw itself with the new query
1041 $scope.gridControls.setQuery(current_grid_query());
1044 // TODO; move me to service
1045 function selected_payment_info() {
1046 var info = {owed : 0, billed : 0, paid : 0};
1047 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1048 info.owed += Number(item['summary.balance_owed']) * 100;
1049 info.billed += Number(item['summary.total_owed']) * 100;
1050 info.paid += Number(item['summary.total_paid']) * 100;
1058 $scope.totals.selected_billed = function() {
1059 return selected_payment_info().billed;
1061 $scope.totals.selected_paid = function() {
1062 return selected_payment_info().paid;
1065 $scope.showFullDetails = function(all) {
1067 $location.path('/circ/patron/' +
1068 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1071 // For now, only adds billing to first selected item.
1072 // Could do batches later if needed
1073 $scope.addBilling = function(all) {
1075 egBilling.showBillDialog({
1076 xact : egCore.idl.flatToNestedHash(all[0]),
1077 patron : $scope.patron()
1078 }).then(function() {
1079 $scope.gridControls.refresh();
1080 patronSvc.fetchUserStats();
1085 $scope.printBills = function(selected) { // FIXME: refactor me
1086 if (!selected.length) return;
1087 // bills print receipt assumes nested hashes, but our grid
1088 // stores flattener data. Fetch the selected xacts as
1089 // fleshed pcrud objects and hashify.
1090 // (Consider an alternate approach..)
1091 var ids = selected.map(function(t){ return t.id });
1093 egCore.pcrud.search('mbt',
1095 {flesh : 5, flesh_fields : {
1096 'mbt' : ['summary', 'circulation'],
1097 'circ' : ['target_copy'],
1098 'acp' : ['call_number'],
1100 'bre' : ['simple_record']
1103 {authoritative : true}
1106 var cusr = patronSvc.current;
1107 egCore.print.print({
1108 context : 'receipt',
1109 template : 'bills_historical',
1111 transactions : xacts,
1112 current_location : egCore.idl.toHash(
1113 egCore.org.get(egCore.auth.user().ws_ou())),
1115 prefix : cusr.prefix(),
1116 pref_prefix : cusr.pref_prefix(),
1117 pref_first_given_name : cusr.pref_first_given_name(),
1118 pref_second_given_name : cusr.pref_second_given_name(),
1119 pref_family_name : cusr.pref_family_name(),
1120 pref_suffix : cusr.pref_suffix(),
1121 first_given_name : cusr.first_given_name(),
1122 second_given_name : cusr.second_given_name(),
1123 family_name : cusr.family_name(),
1124 suffix : cusr.suffix(),
1125 card : { barcode : cusr.card().barcode() },
1126 expire_date : cusr.expire_date(),
1127 alias : cusr.alias(),
1128 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1129 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1137 billing_total : xact.billing_total(),
1138 billings : xact.billings(),
1139 grocery : xact.grocery(),
1141 payment_total : xact.payment_total(),
1142 payments : xact.payments(),
1143 summary : egCore.idl.toHash(xact.summary()),
1144 unrecovered : xact.unrecovered(),
1145 xact_finish : xact.xact_finish(),
1146 xact_start : xact.xact_start(),
1148 if (xact.circulation()) {
1149 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1150 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1152 xacts.push(newXact);
1158 .controller('BillPaymentHistoryCtrl',
1159 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1160 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1162 // generate a grid query with the current date widget values.
1163 function current_grid_query() {
1165 'payment_ts' : {between : $scope.date_range()},
1166 'xact.usr' : billSvc.userId
1170 $scope.gridControls = {
1171 selectedItems : function(){return []},
1172 activateItem : function(item) {
1173 $scope.showFullDetails([item]);
1175 setSort : function() {
1176 return [{'payment_ts' : 'DESC'}, 'id'];
1178 setQuery : current_grid_query
1181 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1182 if (new_date !== old_date && new_date) {
1183 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1184 $scope.dates.xact_finish = new_date;
1186 $scope.actions.apply_date_range();
1190 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1191 if (new_date !== old_date && new_date) {
1192 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1193 $scope.dates.xact_start = new_date;
1195 $scope.actions.apply_date_range();
1200 $scope.actions.apply_date_range = function() {
1201 // tells the grid to re-draw itself with the new query
1202 $scope.gridControls.setQuery(current_grid_query());
1205 $scope.showFullDetails = function(all) {
1207 $location.path('/circ/patron/' +
1208 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1211 $scope.totals.selected_paid = function() {
1213 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1214 paid += Number(payment.amount) * 100;