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 'credit.processor.default'
21 ]).then(function(s) {return service.settings = s});
24 // user billing summary
25 service.fetchSummary = function() {
26 return egCore.pcrud.retrieve(
27 'mowbus', service.userId, {}, {authoritative : true})
28 .then(function(summary) {return service.summary = summary})
31 service.applyPayment = function(
32 type, payments, note, check, cc_args, patron_credit) {
34 return egCore.net.request(
36 'open-ils.circ.money.payment',
37 egCore.auth.token(), {
38 userid : service.userId,
43 patron_credit : patron_credit,
46 patronSvc.current.last_xact_id()
47 ).then(function(resp) {
48 console.debug('payments: ' + js2JSON(resp));
50 if (evt = egCore.evt.parse(resp)) {
51 // Ideally, all scenarios that lead to this alert appearing
52 // will be avoided by the application logic. Leave the alert
53 // in place now to root out any that remain to be addressed.
55 return $q.reject(''+evt);
58 var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
61 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
62 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
63 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
64 case 'debit_card_payment' : msg = egCore.strings.EG_WORK_LOG_DEBIT_CARD_PAYMENT; break;
65 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
66 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
67 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
68 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
72 'action' : 'paid_bill',
73 'patron_id' : service.userId,
74 'total_amount' : total
78 // payment API returns the update xact id so we can track it
79 // for future payments without having to refresh the user.
80 patronSvc.current.last_xact_id(resp.last_xact_id);
82 // reload patron data if credit balance has changed:
83 if(type === 'credit_payment' || patron_credit){ patronSvc.refreshPrimary(); }
89 service.fetchBills = function(xact_id) {
91 return egCore.pcrud.search('mb',
92 {xact : xact_id}, null,
93 {authoritative : true}
95 function() {return bills},
97 function(bill) {bills.push(bill); return bill}
101 service.fetchStatement = function(xact_id) {
102 return egCore.net.request(
104 'open-ils.circ.money.statement.retrieve',
105 egCore.auth.token(), xact_id
106 ).then(function(resp) {
107 if (evt = egCore.evt.parse(resp)) return alert(evt);
112 // TODO: no longer needed?
113 service.fetchPayments = function(xact_id) {
114 return egCore.net.request(
116 'open-ils.circ.money.payment.retrieve.all.authoritative',
117 egCore.auth.token(), xact_id
121 service.voidBills = function(bill_ids) {
122 return egCore.net.requestWithParamList(
124 'open-ils.circ.money.billing.void',
125 [egCore.auth.token()].concat(bill_ids)
126 ).then(function(resp) {
127 if (evt = egCore.evt.parse(resp)) return alert(evt);
132 service.adjustBillsToZero = function(bill_ids) {
133 return egCore.net.request(
135 'open-ils.circ.money.billable_xact.adjust_to_zero',
138 ).then(function(resp) {
139 if (evt = egCore.evt.parse(resp)) return alert(evt);
144 service.updateBillNotes = function(note, ids) {
145 return egCore.net.requestWithParamList(
147 'open-ils.circ.money.billing.note.edit',
148 [egCore.auth.token(), note].concat(ids)
149 ).then(function(resp) {
150 if (evt = egCore.evt.parse(resp)) return alert(evt);
155 service.updatePaymentNotes = function(note, ids) {
156 return egCore.net.requestWithParamList(
158 'open-ils.circ.money.payment.note.edit',
159 [egCore.auth.token(), note].concat(ids)
160 ).then(function(resp) {
161 if (evt = egCore.evt.parse(resp)) return alert(evt);
173 .controller('PatronBillsCtrl',
174 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
175 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
176 'egBilling','$uibModal',
177 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
178 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
179 egBilling , $uibModal) {
181 $scope.initTab('bills', $routeParams.id);
182 billSvc.userId = $routeParams.id;
184 // set up some defaults
185 $scope.check_number = null;
186 $scope.payment_amount = null;
187 $scope.session_voided = 0;
188 $scope.payment_type = 'cash_payment';
189 $scope.focus_payment = true;
190 $scope.annotate_payment = false;
191 $scope.receipt_count = 1;
192 $scope.receipt_on_pay = { isChecked: false };
193 $scope.convert_to_credit = {isChecked: false};
194 $scope.warn_amount = 1000;
195 $scope.max_amount = 100000;
196 $scope.amount_verified = false;
197 $scope.disable_auto_print = false;
199 // Load persistant settings
200 egCore.hatch.getItem('circ.bills.receiptonpay')
201 .then(function(rcptOnPay){
202 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
205 egCore.hatch.getItem('eg.circ.bills.annotatepayment')
206 .then(function(annoPay){
207 if (annoPay) $scope.annotate_payment = annoPay;
210 // pre-define list-returning funcs in case we access them
211 // before the grid instantiates
212 $scope.gridControls = {
213 focusRowSelector : false,
214 selectedItems : function(){return []},
215 allItems : function(){return []},
216 itemRetrieved : function(item) {
217 item.payment_pending = 0;
219 activateItem : function(item) {
220 $scope.showFullDetails([item]);
222 setQuery : function() {
224 usr : billSvc.userId,
226 'summary.balance_owed' : {'<>' : 0}
229 setSort : function() {
230 return ['xact_start'];
234 // Apply coloring to rows based on fines stop reason
235 $scope.colorizeBillsList = {
236 apply: function(item) {
237 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
238 if (item['circulation.stop_fines'] == 'LOST') {
240 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
241 return 'longoverdue-row';
243 return 'overdue-row';
249 // Status Icon Column definition
250 $scope.statusIconColumn = {
252 template: function(item) {
254 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
255 if (item['circulation.stop_fines'] == "LOST") {
256 icon = 'glyphicon-question-sign';
257 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
258 icon = 'glyphicon-exclamation-sign';
260 icon = 'glyphicon-time';
263 return "<i class='glyphicon " + icon + "'></i>"
267 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
269 // given a payment amount, determines how much of that is applied
270 // to selected transactions and how much is left over (change).
271 function pending_payment_info() {
272 var amt = $scope.payment_amount || 0;
273 if (amt >= $scope.owed_selected()) {
275 payment : $scope.owed_selected(),
276 change : amt - $scope.owed_selected()
279 return {payment : amt, change : 0};
282 // calculates amount owed, billed, and paid for selected items
283 // TODO: move me to service
284 function selected_payment_info() {
285 var info = {owed : 0, billed : 0, paid : 0};
286 angular.forEach($scope.gridControls.selectedItems(), function(item) {
287 info.owed += Number(item['summary.balance_owed']) * 100;
288 info.billed += Number(item['summary.total_owed']) * 100;
289 info.paid += Number(item['summary.total_paid']) * 100;
297 $scope.pending_payment = function() {
298 return pending_payment_info().payment;
300 $scope.pending_change = function() {
301 return pending_payment_info().change;
303 $scope.owed_selected = function() {
304 return selected_payment_info().owed;
306 $scope.billed_selected = function() {
307 return selected_payment_info().billed;
309 $scope.paid_selected = function() {
310 return selected_payment_info().paid;
312 $scope.refunds_available = function() {
314 angular.forEach($scope.gridControls.allItems(), function(item) {
315 if (item['summary.balance_owed'] < 0)
316 amount += item['summary.balance_owed'] * 100;
318 return -(amount / 100);
320 $scope.invalid_check_number = function() {
321 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
324 // update the item.payment_pending value each time the user
325 // selects different transactions to pay against.
327 function() {return $scope.gridControls.selectedItems()},
328 function() {updatePendingColumn()},
332 // update the item.payment_pending for each (selected)
333 // transaction any time the user-entered payment amount is modified
334 $scope.$watch('payment_amount', updatePendingColumn);
336 // updates the value of the payment_pending column in the grid.
337 // This has to be managed manually since the display value in the grid
338 // is derived from the value on the stored item and not the contents
339 // of our local scope variables.
340 function updatePendingColumn() {
341 // reset all to zero..
342 angular.forEach($scope.gridControls.allItems(),
343 function(item) {item.payment_pending = 0});
345 var payment_amount = $scope.pending_payment();
347 var selected = $scope.gridControls.selectedItems();
348 for (var i = 0; i < selected.length; i++) { // for/break
349 var item = selected[i];
350 var owed = Number(item['summary.balance_owed']);
352 if (payment_amount > owed) {
353 // pending payment exceeds balance of current item.
354 // pay the entire item.
355 item.payment_pending = owed;
356 payment_amount -= owed;
359 // balance owed on the current item matches or exceeds
360 // the pending payment. Apply the full remainder of
361 // the payment to this item.. and we're done.
362 // Limit to two decimal places to avoid floating point issues
363 item.payment_pending = payment_amount.toFixed(2);
369 // builds payment arrays ([xact_id, ammount]) for all transactions
370 // which have a pending payment amount.
371 function generatePayments() {
373 angular.forEach($scope.gridControls.selectedItems(), function(item) {
374 if (item.payment_pending == 0) return;
375 payments.push([item.id, item.payment_pending]);
380 function refreshDisplay() {
381 patronSvc.fetchUserStats();
382 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
383 $scope.payment_amount = null;
384 $scope.gridControls.refresh();
387 // generates payments, collects user note if needed, and sends payment
389 function sendPayment(note, cc_args) {
390 $scope.applyingPayment = true;
391 var make_payments = generatePayments();
392 var patron_credit = $scope.convert_to_credit.isChecked ?
393 $scope.pending_change() : 0;
394 billSvc.applyPayment($scope.payment_type,
395 make_payments, note, $scope.check_number, cc_args, patron_credit)
397 function(payment_ids) {
399 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
401 $scope.payment_type, payment_ids, make_payments, note);
407 console.error('Payment was rejected: ' + msg);
410 .finally(function() { $scope.applyingPayment = false; })
413 $scope.onReceiptOnPayChanged = function(){
414 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
417 $scope.onAnnotatePaymentChanged = function(){
418 egCore.hatch.setItem('eg.circ.bills.annotatepayment', $scope.annotate_payment);
421 function printReceipt(type, payment_ids, payments_made, note) {
422 var payment_blobs = [];
423 var cusr = patronSvc.current;
425 angular.forEach(payments_made, function(payment) {
426 var xact_id = payment[0];
428 // find the original transaction in the grid..
429 var xact = $scope.gridControls.allItems().filter(
430 function(item) {return item.id == xact_id})[0];
433 xact : egCore.idl.flatToNestedHash(xact),
438 console.log(js2JSON(payment_blobs[0]));
440 // page data not yet refreshed, capture data from current scope
444 previous_balance : Number($scope.summary.balance_owed()),
445 payment_total : Number($scope.payment_amount),
446 payment_applied : $scope.pending_payment(),
447 amount_voided : Number($scope.session_voided),
448 change_given : $scope.pending_change(),
449 payments : payment_blobs,
450 current_location : egCore.idl.toHash(
451 egCore.org.get(egCore.auth.user().ws_ou()))
454 // Not a good idea to use patron_stats.fines for this; it's out of date
455 print_data.patron = {
456 prefix : cusr.prefix(),
457 first_given_name : cusr.first_given_name(),
458 second_given_name : cusr.second_given_name(),
459 family_name : cusr.family_name(),
460 suffix : cusr.suffix(),
461 pref_prefix : cusr.pref_prefix(),
462 pref_first_given_name : cusr.pref_first_given_name(),
463 pref_second_given_name : cusr.pref_second_given_name(),
464 pref_family_name : cusr.pref_family_name(),
465 pref_suffix : cusr.pref_suffix(),
466 card : { barcode : cusr.card().barcode() },
467 expire_date : cusr.expire_date(),
468 alias : cusr.alias(),
469 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
470 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
473 print_data.new_balance = (
474 print_data.previous_balance * 100 -
475 print_data.payment_applied * 100) / 100;
477 for (var i = 0; i < $scope.receipt_count; i++) {
480 template : 'bill_payment',
486 $scope.showHistory = function() {
487 $location.path('/circ/patron/' +
488 patronSvc.current.id() + '/bill_history/transactions');
491 // For now, only adds billing to first selected item.
492 // Could do batches later if needed
493 $scope.addBilling = function(all) {
495 egBilling.showBillDialog({
496 xact : egCore.idl.flatToNestedHash(all[0]),
497 patron : $scope.patron()
498 }).then(refreshDisplay);
502 $scope.showBillDialog = function($event) {
503 egBilling.showBillDialog({
504 patron : $scope.patron()
505 }).then(refreshDisplay);
508 // Select refunds adds all refunds to the existing selection.
509 // It does not /only/ select refunds
510 $scope.selectRefunds = function() {
511 var ids = $scope.gridControls.selectedItems().map(
512 function(i) { return i.id });
513 angular.forEach($scope.gridControls.allItems(), function(item) {
514 if (Number(item['summary.balance_owed']) < 0)
517 $scope.gridControls.selectItems(ids);
521 // determine on initial page load when all of the grid rows should
523 var selectOnLoad = true;
524 billSvc.fetchBillSettings().then(function(s) {
525 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
526 $scope.focus_payment = false; // de-focus the payment box
527 $scope.gridControls.focusRowSelector = true;
528 selectOnLoad = false;
529 // if somehow the grid finishes rendering before our settings
530 // arrive, manually de-select everything.
531 $scope.gridControls.selectItems([]);
533 if (s['ui.circ.billing.amount_warn']) {
534 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
536 if (s['ui.circ.billing.amount_limit']) {
537 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
539 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
540 $scope.disable_auto_print = Boolean(
541 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
544 if (s['circ.disable_patron_credit']) {
545 $scope.disablePatronCredit = true;
547 if (!s['credit.processor.default']) {
548 // If we don't have a CC processor, we should disable the "internal" CC form
549 $scope.disableCreditCardForm = true;
551 // Stripe isn't supported in the staff client currently, so disable here too
552 $scope.disableCreditCardForm = (s['credit.processor.default'] == 'Stripe');
556 $scope.gridControls.allItemsRetrieved = function() {
558 selectOnLoad = false; // only for initial controller load.
559 // select all non-refund items
560 $scope.gridControls.selectItems(
561 $scope.gridControls.allItems()
562 .filter(function(i) {return i['summary.balance_owed'] > 0})
563 .map(function(i){return i.id})
570 $scope.printBills = function(selected) {
571 if (!selected.length) return;
572 // bills print receipt assumes nested hashes, but our grid
573 // stores flattener data. Fetch the selected xacts as
574 // fleshed pcrud objects and hashify.
575 // (Consider an alternate approach..)
576 var ids = selected.map(function(t){ return t.id });
578 egCore.pcrud.search('mbt',
580 {flesh : 5, flesh_fields : {
581 'mbt' : ['summary', 'circulation'],
582 'circ' : ['target_copy'],
583 'acp' : ['call_number'],
584 'acn' : ['record','owning_lib','prefix','suffix'],
585 'bre' : ['simple_record']
588 {authoritative : true}
591 var cusr = patronSvc.current;
594 template : 'bills_current',
596 transactions : xacts,
597 current_location : egCore.idl.toHash(
598 egCore.org.get(egCore.auth.user().ws_ou())),
600 prefix : cusr.prefix(),
601 first_given_name : cusr.first_given_name(),
602 second_given_name : cusr.second_given_name(),
603 family_name : cusr.family_name(),
604 suffix : cusr.suffix(),
605 pref_prefix : cusr.pref_prefix(),
606 pref_first_given_name : cusr.pref_first_given_name(),
607 pref_second_given_name : cusr.pref_second_given_name(),
608 pref_family_name : cusr.pref_family_name(),
609 pref_suffix : cusr.pref_suffix(),
610 card : { barcode : cusr.card().barcode() },
611 expire_date : cusr.expire_date(),
612 alias : cusr.alias(),
613 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
614 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
622 billing_total : xact.billing_total(),
623 billings : xact.billings(),
624 grocery : xact.grocery(),
626 payment_total : xact.payment_total(),
627 payments : xact.payments(),
628 summary : egCore.idl.toHash(xact.summary()),
629 unrecovered : xact.unrecovered(),
630 xact_finish : xact.xact_finish(),
631 xact_start : xact.xact_start(),
633 if (xact.circulation()) {
634 newXact.copy_barcode = xact.circulation().target_copy().barcode();
635 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
636 newXact.call_number = {
637 label : xact.circulation().target_copy().call_number().label(),
638 prefix : xact.circulation().target_copy().call_number().prefix().label(),
639 suffix : xact.circulation().target_copy().call_number().suffix().label(),
641 name : xact.circulation().target_copy().call_number().owning_lib().name(),
642 shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
651 $scope.applyPayment = function() {
653 if ($scope.payment_amount > $scope.max_amount ) {
655 egCore.strings.PAYMENT_OVER_MAX,
656 { max_amount : ''+$scope.max_amount,
658 $scope.payment_amount = 0;
665 verify_payment_amount().then(
666 function() { // amount confirmed
667 add_payment_note().then(function(pay_note) {
668 add_cc_args().then(function(cc_args) {
669 var note_text = pay_note ? pay_note.value || '' : null;
670 sendPayment(note_text, cc_args);
674 function() { // amount rejected
675 console.warn('payment amount rejected');
676 $scope.payment_amount = 0;
681 function verify_payment_amount() {
682 if ($scope.payment_amount < $scope.warn_amount)
685 return egConfirmDialog.open(
686 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
687 egCore.strings.PAYMENT_WARN_AMOUNT,
688 {payment_amount : ''+$scope.payment_amount}
692 function add_payment_note() {
693 if (!$scope.annotate_payment) return $q.when();
694 return egPromptDialog.open(
695 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
698 function add_cc_args() {
699 if ($scope.payment_type != 'credit_card_payment')
702 var disableCreditCardForm = $scope.disableCreditCardForm;
704 return $uibModal.open({
705 templateUrl : './circ/patron/t_cc_payment_dialog',
708 '$scope','$uibModalInstance',
709 function($scope , $uibModalInstance) {
713 where_process : disableCreditCardForm ? '0' : '1', // internal=1 ; external=0
714 disable_internal : disableCreditCardForm,
715 type : 'VISA', // external only
716 billing_first : patronSvc.current.first_given_name(),
717 billing_last : patronSvc.current.family_name()
721 var addr = patronSvc.current.billing_address() ||
722 patronSvc.current.mailing_address();
724 var cc = $scope.context.cc;
725 cc.billing_address = addr.street1() +
726 (addr.street2() ? ' ' + addr.street2() : '');
727 cc.billing_city = addr.city();
728 cc.billing_state = addr.state();
729 cc.billing_zip = addr.post_code();
732 $scope.ok = function() {
733 // CC payment form is not a <form>,
734 // so apply validation manually.
735 if ( $scope.context.cc.where_process == 0 &&
736 !$scope.context.cc.approval_code)
739 $uibModalInstance.close($scope.context.cc);
742 $scope.cancel = function() {
743 $uibModalInstance.dismiss();
750 $scope.voidAllBillings = function(items) {
754 angular.forEach(items, function(item) {
756 billSvc.fetchBills(item.id).then(function(bills) {
757 angular.forEach(bills, function(b) {
758 if (b.voided() != 't') {
759 cents += b.amount() * 100;
760 bill_ids.push(b.id())
764 if (bill_ids.length == 0) {
773 $q.all(promises).then(function(){
774 egCore.audio.play('warning.circ.void_billings_confirmation');
775 egConfirmDialog.open(
776 egCore.strings.CONFIRM_VOID_BILLINGS, '',
777 { billIds : ''+bill_ids,
778 amount : ''+(cents/100),
780 billSvc.voidBills(bill_ids).then(function() {
781 $scope.session_voided =
782 ($scope.session_voided * 100 + cents) / 100;
791 $scope.adjustToZero = function(items) {
792 if (items.length == 0) return;
794 var ids = items.map(function(item) {return item.id});
796 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
797 egConfirmDialog.open(
798 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
801 billSvc.adjustBillsToZero(ids).then(function() {
810 // note this is functionally equivalent to selecting a neg. transaction
811 // then clicking Apply Payment -- this just adds a speed bump (ditto
813 $scope.refundXact = function(all) {
814 var items = all.filter(function(item) {
815 return item['summary.balance_owed'] < 0
818 if (items.length == 0) return;
820 var ids = items.map(function(item) {return item.id});
822 egCore.audio.play('warning.circ.refund_confirmation');
823 egConfirmDialog.open(
824 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
827 // reset the received payment amount. this ensures
828 // we're not mingling payments with refunds.
829 $scope.payment_amount = 0;
835 // direct the user to the transaction details page
836 $scope.showFullDetails = function(all) {
837 var lastClicked = $scope.gridControls.contextMenuItem();
839 $location.path('/circ/patron/' +
840 patronSvc.current.id() + '/bill/' + lastClicked + '/statement');
842 $location.path('/circ/patron/' +
843 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
848 $scope.activateBill = function(xact) {
849 $scope.showFullDetails([xact]);
855 * Displays details of a single transaction
857 .controller('XactDetailsCtrl',
858 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
859 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
861 $scope.initTab('bills', $routeParams.id);
862 var xact_id = $routeParams.xact_id;
863 $scope.xact_tab = $routeParams.xact_tab;
865 var xactGrid = $scope.xactGridControls = {
866 setQuery : function() { return {xact : xact_id} },
867 setSort : function() { return ['billing_ts'] }
870 var paymentGrid = $scope.paymentGridControls = {
871 setQuery : function() { return {xact : xact_id} },
872 setSort : function() { return ['payment_ts'] }
876 $scope.voidBillings = function(bill_list) {
879 angular.forEach(bill_list, function(b) {
880 if (b.voided != 't') {
881 cents += b.amount * 100;
886 if (bill_ids.length == 0) {
891 egCore.audio.play('warning.circ.void_billings_confirmation');
892 egConfirmDialog.open(
893 egCore.strings.CONFIRM_VOID_BILLINGS, '',
894 { billIds : ''+bill_ids,
895 amount : ''+(cents/100),
897 billSvc.voidBills(bill_ids).then(function() {
898 // TODO? $scope.session_voided = ...
900 // refresh bills and summary data
901 // note: no need to update payments
902 patronSvc.fetchUserStats();
904 egBilling.fetchXact(xact_id).then(function(xact) {
915 // batch-edit billing and payment notes, depending on 'type'
916 function editNotes(selected, type) {
917 var notes = selected.map(function(b){ return b.note }).join(',');
918 var ids = selected.map(function(b){ return b.id });
920 // show the note edit prompt
922 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
924 ok : function(value) {
926 var func = 'updateBillNotes';
927 if (type == 'payment') func = 'updatePaymentNotes';
929 billSvc[func](value, ids).then(function() {
930 if (type == 'payment') {
931 paymentGrid.refresh();
941 $scope.editBillNotes = function(selected) {
942 editNotes(selected, 'bill');
945 $scope.editPaymentNotes = function(selected) {
946 editNotes(selected, 'payment');
949 // -- retrieve our data
950 if ($scope.xact_tab == 'statement') {
951 //fetch combined billing statement data
952 billSvc.fetchStatement(xact_id).then(function(statement) {
953 //console.log(statement);
954 $scope.statement_data = statement;
957 $scope.total_circs = 0; // start with 0 instead of undefined
958 egBilling.fetchXact(xact_id).then(function(xact) {
961 var copyId = xact.circulation().target_copy().id();
963 egCore.pcrud.search('circbyyr',
964 {copy : copyId}, null, {atomic : true})
965 .then(function(counts) {
966 angular.forEach(counts, function(count) {
967 circ_count += Number(count.count());
969 $scope.total_circs = circ_count;
971 // set the title. only needs to be done on initial page load
972 if (xact.circulation()) {
973 if (xact.circulation().target_copy().call_number().id() == -1) {
974 $scope.title = xact.circulation().target_copy().dummy_title();
976 // TODO: shared bib service?
977 $scope.title = xact.circulation().target_copy()
978 .call_number().record().simple_record().title();
979 $scope.title_id = xact.circulation().target_copy()
980 .call_number().record().id();
987 .controller('BillHistoryCtrl',
988 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
989 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
991 $scope.initTab('bills', $routeParams.id);
992 billSvc.userId = $routeParams.id;
993 $scope.bill_tab = $routeParams.history_tab;
996 // link page controller actions defined by sub-controllers here
999 var start = new Date(); // now - 1 year
1000 start.setFullYear(start.getFullYear() - 1),
1003 xact_finish : new Date()
1006 $scope.date_range = function() {
1007 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
1008 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
1009 var today = new Date().toISOString().replace(/T.*/,'');
1010 if (end == today) end = 'now';
1011 return [start, end];
1016 .controller('BillXactHistoryCtrl',
1017 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
1018 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
1020 // generate a grid query with the current date widget values.
1021 function current_grid_query() {
1024 {'summary.balance_owed' : {'<>' : 0}},
1025 {'summary.last_payment_ts' : {'<>' : null}}
1027 xact_start : {between : $scope.date_range()},
1028 usr : billSvc.userId
1032 $scope.gridControls = {
1033 selectedItems : function(){return []},
1034 activateItem : function(item) {
1035 $scope.showFullDetails([item]);
1037 // this sets the query on page load
1038 setQuery : current_grid_query
1041 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1042 if (new_date !== old_date && new_date) {
1043 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1044 $scope.dates.xact_finish = new_date;
1046 $scope.actions.apply_date_range();
1050 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1051 if (new_date !== old_date && new_date) {
1052 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1053 $scope.dates.xact_start = new_date;
1055 $scope.actions.apply_date_range();
1060 $scope.actions.apply_date_range = function() {
1061 // tells the grid to re-draw itself with the new query
1062 $scope.gridControls.setQuery(current_grid_query());
1065 // TODO; move me to service
1066 function selected_payment_info() {
1067 var info = {owed : 0, billed : 0, paid : 0};
1068 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1069 info.owed += Number(item['summary.balance_owed']) * 100;
1070 info.billed += Number(item['summary.total_owed']) * 100;
1071 info.paid += Number(item['summary.total_paid']) * 100;
1079 $scope.totals.selected_billed = function() {
1080 return selected_payment_info().billed;
1082 $scope.totals.selected_paid = function() {
1083 return selected_payment_info().paid;
1086 $scope.showFullDetails = function(all) {
1088 $location.path('/circ/patron/' +
1089 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1092 // For now, only adds billing to first selected item.
1093 // Could do batches later if needed
1094 $scope.addBilling = function(all) {
1096 egBilling.showBillDialog({
1097 xact : egCore.idl.flatToNestedHash(all[0]),
1098 patron : $scope.patron()
1099 }).then(function() {
1100 $scope.gridControls.refresh();
1101 patronSvc.fetchUserStats();
1106 $scope.printBills = function(selected) { // FIXME: refactor me
1107 if (!selected.length) return;
1108 // bills print receipt assumes nested hashes, but our grid
1109 // stores flattener data. Fetch the selected xacts as
1110 // fleshed pcrud objects and hashify.
1111 // (Consider an alternate approach..)
1112 var ids = selected.map(function(t){ return t.id });
1114 egCore.pcrud.search('mbt',
1116 {flesh : 5, flesh_fields : {
1117 'mbt' : ['summary', 'circulation'],
1118 'circ' : ['target_copy'],
1119 'acp' : ['call_number'],
1120 'acn' : ['record','owning_lib','prefix','suffix'],
1121 'bre' : ['simple_record']
1124 {authoritative : true}
1127 var cusr = patronSvc.current;
1128 egCore.print.print({
1129 context : 'receipt',
1130 template : 'bills_historical',
1132 transactions : xacts,
1133 current_location : egCore.idl.toHash(
1134 egCore.org.get(egCore.auth.user().ws_ou())),
1136 prefix : cusr.prefix(),
1137 pref_prefix : cusr.pref_prefix(),
1138 pref_first_given_name : cusr.pref_first_given_name(),
1139 pref_second_given_name : cusr.pref_second_given_name(),
1140 pref_family_name : cusr.pref_family_name(),
1141 pref_suffix : cusr.pref_suffix(),
1142 first_given_name : cusr.first_given_name(),
1143 second_given_name : cusr.second_given_name(),
1144 family_name : cusr.family_name(),
1145 suffix : cusr.suffix(),
1146 card : { barcode : cusr.card().barcode() },
1147 expire_date : cusr.expire_date(),
1148 alias : cusr.alias(),
1149 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1150 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1158 billing_total : xact.billing_total(),
1159 billings : xact.billings(),
1160 grocery : xact.grocery(),
1162 payment_total : xact.payment_total(),
1163 payments : xact.payments(),
1164 summary : egCore.idl.toHash(xact.summary()),
1165 unrecovered : xact.unrecovered(),
1166 xact_finish : xact.xact_finish(),
1167 xact_start : xact.xact_start(),
1169 if (xact.circulation()) {
1170 newXact.copy_barcode = xact.circulation().target_copy().barcode();
1171 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
1172 newXact.call_number = {
1173 label : xact.circulation().target_copy().call_number().label(),
1174 prefix : xact.circulation().target_copy().call_number().prefix().label(),
1175 suffix : xact.circulation().target_copy().call_number().suffix().label(),
1177 name : xact.circulation().target_copy().call_number().owning_lib().name(),
1178 shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
1182 xacts.push(newXact);
1188 .controller('BillPaymentHistoryCtrl',
1189 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1190 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1192 // generate a grid query with the current date widget values.
1193 function current_grid_query() {
1195 'payment_ts' : {between : $scope.date_range()},
1196 'xact.usr' : billSvc.userId
1200 $scope.gridControls = {
1201 selectedItems : function(){return []},
1202 activateItem : function(item) {
1203 $scope.showFullDetails([item]);
1205 setSort : function() {
1206 return [{'payment_ts' : 'DESC'}, 'id'];
1208 setQuery : current_grid_query
1211 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1212 if (new_date !== old_date && new_date) {
1213 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1214 $scope.dates.xact_finish = new_date;
1216 $scope.actions.apply_date_range();
1220 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1221 if (new_date !== old_date && new_date) {
1222 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1223 $scope.dates.xact_start = new_date;
1225 $scope.actions.apply_date_range();
1230 $scope.actions.apply_date_range = function() {
1231 // tells the grid to re-draw itself with the new query
1232 $scope.gridControls.setQuery(current_grid_query());
1235 $scope.showFullDetails = function(all) {
1237 $location.path('/circ/patron/' +
1238 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1241 $scope.totals.selected_paid = function() {
1243 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1244 paid += Number(payment.amount) * 100;