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) {
398 var approval_code = cc_args ? cc_args.approval_code : '';
399 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
401 $scope.payment_type, payment_ids, make_payments, note, approval_code);
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, approval_code) {
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 approval_code : approval_code,
445 previous_balance : Number($scope.summary.balance_owed()),
446 payment_total : Number($scope.payment_amount),
447 payment_applied : $scope.pending_payment(),
448 amount_voided : Number($scope.session_voided),
449 change_given : $scope.pending_change(),
450 payments : payment_blobs,
451 current_location : egCore.idl.toHash(
452 egCore.org.get(egCore.auth.user().ws_ou()))
455 // Not a good idea to use patron_stats.fines for this; it's out of date
456 print_data.patron = {
457 prefix : cusr.prefix(),
458 first_given_name : cusr.first_given_name(),
459 second_given_name : cusr.second_given_name(),
460 family_name : cusr.family_name(),
461 suffix : cusr.suffix(),
462 pref_prefix : cusr.pref_prefix(),
463 pref_first_given_name : cusr.pref_first_given_name(),
464 pref_second_given_name : cusr.pref_second_given_name(),
465 pref_family_name : cusr.pref_family_name(),
466 pref_suffix : cusr.pref_suffix(),
467 card : { barcode : cusr.card().barcode() },
468 expire_date : cusr.expire_date(),
469 alias : cusr.alias(),
470 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
471 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
474 print_data.new_balance = (
475 print_data.previous_balance * 100 -
476 print_data.payment_applied * 100) / 100;
478 for (var i = 0; i < $scope.receipt_count; i++) {
481 template : 'bill_payment',
487 $scope.showHistory = function() {
488 $location.path('/circ/patron/' +
489 patronSvc.current.id() + '/bill_history/transactions');
492 // For now, only adds billing to first selected item.
493 // Could do batches later if needed
494 $scope.addBilling = function(all) {
496 egBilling.showBillDialog({
497 xact : egCore.idl.flatToNestedHash(all[0]),
498 patron : $scope.patron()
499 }).then(refreshDisplay);
503 $scope.showBillDialog = function($event) {
504 egBilling.showBillDialog({
505 patron : $scope.patron()
506 }).then(refreshDisplay);
509 // Select refunds adds all refunds to the existing selection.
510 // It does not /only/ select refunds
511 $scope.selectRefunds = function() {
512 var ids = $scope.gridControls.selectedItems().map(
513 function(i) { return i.id });
514 angular.forEach($scope.gridControls.allItems(), function(item) {
515 if (Number(item['summary.balance_owed']) < 0)
518 $scope.gridControls.selectItems(ids);
522 // determine on initial page load when all of the grid rows should
524 var selectOnLoad = true;
525 billSvc.fetchBillSettings().then(function(s) {
526 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
527 $scope.focus_payment = false; // de-focus the payment box
528 $scope.gridControls.focusRowSelector = true;
529 selectOnLoad = false;
530 // if somehow the grid finishes rendering before our settings
531 // arrive, manually de-select everything.
532 $scope.gridControls.selectItems([]);
534 if (s['ui.circ.billing.amount_warn']) {
535 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
537 if (s['ui.circ.billing.amount_limit']) {
538 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
540 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
541 $scope.disable_auto_print = Boolean(
542 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
545 if (s['circ.disable_patron_credit']) {
546 $scope.disablePatronCredit = true;
548 if (!s['credit.processor.default']) {
549 // If we don't have a CC processor, we should disable the "internal" CC form
550 $scope.disableCreditCardForm = true;
552 // Stripe isn't supported in the staff client currently, so disable here too
553 $scope.disableCreditCardForm = (s['credit.processor.default'] == 'Stripe');
557 $scope.gridControls.allItemsRetrieved = function() {
559 selectOnLoad = false; // only for initial controller load.
560 // select all non-refund items
561 $scope.gridControls.selectItems(
562 $scope.gridControls.allItems()
563 .filter(function(i) {return i['summary.balance_owed'] > 0})
564 .map(function(i){return i.id})
571 $scope.printBills = function(selected) {
572 if (!selected.length) return;
573 // bills print receipt assumes nested hashes, but our grid
574 // stores flattener data. Fetch the selected xacts as
575 // fleshed pcrud objects and hashify.
576 // (Consider an alternate approach..)
577 var ids = selected.map(function(t){ return t.id });
579 egCore.pcrud.search('mbt',
581 {flesh : 5, flesh_fields : {
582 'mbt' : ['summary', 'circulation'],
583 'circ' : ['target_copy'],
584 'acp' : ['call_number'],
585 'acn' : ['record','owning_lib','prefix','suffix'],
586 'bre' : ['simple_record']
589 {authoritative : true}
592 var cusr = patronSvc.current;
595 template : 'bills_current',
597 transactions : xacts,
598 current_location : egCore.idl.toHash(
599 egCore.org.get(egCore.auth.user().ws_ou())),
601 prefix : cusr.prefix(),
602 first_given_name : cusr.first_given_name(),
603 second_given_name : cusr.second_given_name(),
604 family_name : cusr.family_name(),
605 suffix : cusr.suffix(),
606 pref_prefix : cusr.pref_prefix(),
607 pref_first_given_name : cusr.pref_first_given_name(),
608 pref_second_given_name : cusr.pref_second_given_name(),
609 pref_family_name : cusr.pref_family_name(),
610 pref_suffix : cusr.pref_suffix(),
611 card : { barcode : cusr.card().barcode() },
612 expire_date : cusr.expire_date(),
613 alias : cusr.alias(),
614 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
615 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
623 billing_total : xact.billing_total(),
624 billings : xact.billings(),
625 grocery : xact.grocery(),
627 payment_total : xact.payment_total(),
628 payments : xact.payments(),
629 summary : egCore.idl.toHash(xact.summary()),
630 unrecovered : xact.unrecovered(),
631 xact_finish : xact.xact_finish(),
632 xact_start : xact.xact_start(),
634 if (xact.circulation()) {
635 newXact.copy_barcode = xact.circulation().target_copy().barcode();
636 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
637 newXact.call_number = {
638 label : xact.circulation().target_copy().call_number().label(),
639 prefix : xact.circulation().target_copy().call_number().prefix().label(),
640 suffix : xact.circulation().target_copy().call_number().suffix().label(),
642 name : xact.circulation().target_copy().call_number().owning_lib().name(),
643 shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
652 $scope.applyPayment = function() {
654 if ($scope.payment_amount > $scope.max_amount ) {
656 egCore.strings.PAYMENT_OVER_MAX,
657 { max_amount : ''+$scope.max_amount,
659 $scope.payment_amount = 0;
666 verify_payment_amount().then(
667 function() { // amount confirmed
668 add_payment_note().then(function(pay_note) {
669 add_cc_args().then(function(cc_args) {
670 var note_text = pay_note ? pay_note.value || '' : null;
671 sendPayment(note_text, cc_args);
675 function() { // amount rejected
676 console.warn('payment amount rejected');
677 $scope.payment_amount = 0;
682 function verify_payment_amount() {
683 if ($scope.payment_amount < $scope.warn_amount)
686 return egConfirmDialog.open(
687 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
688 egCore.strings.PAYMENT_WARN_AMOUNT,
689 {payment_amount : ''+$scope.payment_amount}
693 function add_payment_note() {
694 if (!$scope.annotate_payment) return $q.when();
695 return egPromptDialog.open(
696 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
699 function add_cc_args() {
700 if ($scope.payment_type != 'credit_card_payment')
703 var disableCreditCardForm = $scope.disableCreditCardForm;
705 return $uibModal.open({
706 templateUrl : './circ/patron/t_cc_payment_dialog',
709 '$scope','$uibModalInstance',
710 function($scope , $uibModalInstance) {
714 where_process : disableCreditCardForm ? '0' : '1', // internal=1 ; external=0
715 disable_internal : disableCreditCardForm,
716 type : 'VISA', // external only
717 billing_first : patronSvc.current.first_given_name(),
718 billing_last : patronSvc.current.family_name()
722 var addr = patronSvc.current.billing_address() ||
723 patronSvc.current.mailing_address();
725 var cc = $scope.context.cc;
726 cc.billing_address = addr.street1() +
727 (addr.street2() ? ' ' + addr.street2() : '');
728 cc.billing_city = addr.city();
729 cc.billing_state = addr.state();
730 cc.billing_zip = addr.post_code();
733 $scope.ok = function() {
734 // CC payment form is not a <form>,
735 // so apply validation manually.
736 if ( $scope.context.cc.where_process == 0 &&
737 !$scope.context.cc.approval_code)
740 $uibModalInstance.close($scope.context.cc);
743 $scope.cancel = function() {
744 $uibModalInstance.dismiss();
751 $scope.voidAllBillings = function(items) {
755 angular.forEach(items, function(item) {
757 billSvc.fetchBills(item.id).then(function(bills) {
758 angular.forEach(bills, function(b) {
759 if (b.voided() != 't') {
760 cents += b.amount() * 100;
761 bill_ids.push(b.id())
765 if (bill_ids.length == 0) {
774 $q.all(promises).then(function(){
775 egCore.audio.play('warning.circ.void_billings_confirmation');
776 egConfirmDialog.open(
777 egCore.strings.CONFIRM_VOID_BILLINGS, '',
778 { billIds : ''+bill_ids,
779 amount : ''+(cents/100),
781 billSvc.voidBills(bill_ids).then(function() {
782 $scope.session_voided =
783 ($scope.session_voided * 100 + cents) / 100;
792 $scope.adjustToZero = function(items) {
793 if (items.length == 0) return;
795 var ids = items.map(function(item) {return item.id});
797 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
798 egConfirmDialog.open(
799 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
802 billSvc.adjustBillsToZero(ids).then(function() {
811 // note this is functionally equivalent to selecting a neg. transaction
812 // then clicking Apply Payment -- this just adds a speed bump (ditto
814 $scope.refundXact = function(all) {
815 var items = all.filter(function(item) {
816 return item['summary.balance_owed'] < 0
819 if (items.length == 0) return;
821 var ids = items.map(function(item) {return item.id});
823 egCore.audio.play('warning.circ.refund_confirmation');
824 egConfirmDialog.open(
825 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
828 // reset the received payment amount. this ensures
829 // we're not mingling payments with refunds.
830 $scope.payment_amount = 0;
836 // direct the user to the transaction details page
837 $scope.showFullDetails = function(all) {
838 var lastClicked = $scope.gridControls.contextMenuItem();
840 $location.path('/circ/patron/' +
841 patronSvc.current.id() + '/bill/' + lastClicked + '/statement');
843 $location.path('/circ/patron/' +
844 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
849 $scope.activateBill = function(xact) {
850 $scope.showFullDetails([xact]);
856 * Displays details of a single transaction
858 .controller('XactDetailsCtrl',
859 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
860 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
862 $scope.initTab('bills', $routeParams.id);
863 var xact_id = $routeParams.xact_id;
864 $scope.xact_tab = $routeParams.xact_tab;
866 var xactGrid = $scope.xactGridControls = {
867 setQuery : function() { return {xact : xact_id} },
868 setSort : function() { return ['billing_ts'] }
871 var paymentGrid = $scope.paymentGridControls = {
872 setQuery : function() { return {xact : xact_id} },
873 setSort : function() { return ['payment_ts'] }
877 $scope.voidBillings = function(bill_list) {
880 angular.forEach(bill_list, function(b) {
881 if (b.voided != 't') {
882 cents += b.amount * 100;
887 if (bill_ids.length == 0) {
892 egCore.audio.play('warning.circ.void_billings_confirmation');
893 egConfirmDialog.open(
894 egCore.strings.CONFIRM_VOID_BILLINGS, '',
895 { billIds : ''+bill_ids,
896 amount : ''+(cents/100),
898 billSvc.voidBills(bill_ids).then(function() {
899 // TODO? $scope.session_voided = ...
901 // refresh bills and summary data
902 // note: no need to update payments
903 patronSvc.fetchUserStats();
905 egBilling.fetchXact(xact_id).then(function(xact) {
916 // batch-edit billing and payment notes, depending on 'type'
917 function editNotes(selected, type) {
918 var notes = selected.map(function(b){ return b.note }).join(',');
919 var ids = selected.map(function(b){ return b.id });
921 // show the note edit prompt
923 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
925 ok : function(value) {
927 var func = 'updateBillNotes';
928 if (type == 'payment') func = 'updatePaymentNotes';
930 billSvc[func](value, ids).then(function() {
931 if (type == 'payment') {
932 paymentGrid.refresh();
942 $scope.editBillNotes = function(selected) {
943 editNotes(selected, 'bill');
946 $scope.editPaymentNotes = function(selected) {
947 editNotes(selected, 'payment');
950 // -- retrieve our data
951 if ($scope.xact_tab == 'statement') {
952 //fetch combined billing statement data
953 billSvc.fetchStatement(xact_id).then(function(statement) {
954 //console.log(statement);
955 $scope.statement_data = statement;
958 $scope.total_circs = 0; // start with 0 instead of undefined
959 egBilling.fetchXact(xact_id).then(function(xact) {
962 var copyId = xact.circulation().target_copy().id();
964 egCore.pcrud.search('circbyyr',
965 {copy : copyId}, null, {atomic : true})
966 .then(function(counts) {
967 angular.forEach(counts, function(count) {
968 circ_count += Number(count.count());
970 $scope.total_circs = circ_count;
972 // set the title. only needs to be done on initial page load
973 if (xact.circulation()) {
974 if (xact.circulation().target_copy().call_number().id() == -1) {
975 $scope.title = xact.circulation().target_copy().dummy_title();
977 // TODO: shared bib service?
978 $scope.title = xact.circulation().target_copy()
979 .call_number().record().simple_record().title();
980 $scope.title_id = xact.circulation().target_copy()
981 .call_number().record().id();
988 .controller('BillHistoryCtrl',
989 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
990 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
992 $scope.initTab('bills', $routeParams.id);
993 billSvc.userId = $routeParams.id;
994 $scope.bill_tab = $routeParams.history_tab;
997 // link page controller actions defined by sub-controllers here
1000 var start = new Date(); // now - 1 year
1001 start.setFullYear(start.getFullYear() - 1),
1004 xact_finish : new Date()
1007 $scope.date_range = function() {
1008 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
1009 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
1010 var today = new Date().toISOString().replace(/T.*/,'');
1011 if (end == today) end = 'now';
1012 return [start, end];
1017 .controller('BillXactHistoryCtrl',
1018 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
1019 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
1021 // generate a grid query with the current date widget values.
1022 function current_grid_query() {
1025 {'summary.balance_owed' : {'<>' : 0}},
1026 {'summary.last_payment_ts' : {'<>' : null}}
1028 xact_start : {between : $scope.date_range()},
1029 usr : billSvc.userId
1033 $scope.gridControls = {
1034 selectedItems : function(){return []},
1035 activateItem : function(item) {
1036 $scope.showFullDetails([item]);
1038 // this sets the query on page load
1039 setQuery : current_grid_query
1042 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1043 if (new_date !== old_date && new_date) {
1044 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1045 $scope.dates.xact_finish = new_date;
1047 $scope.actions.apply_date_range();
1051 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1052 if (new_date !== old_date && new_date) {
1053 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1054 $scope.dates.xact_start = new_date;
1056 $scope.actions.apply_date_range();
1061 $scope.actions.apply_date_range = function() {
1062 // tells the grid to re-draw itself with the new query
1063 $scope.gridControls.setQuery(current_grid_query());
1066 // TODO; move me to service
1067 function selected_payment_info() {
1068 var info = {owed : 0, billed : 0, paid : 0};
1069 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1070 info.owed += Number(item['summary.balance_owed']) * 100;
1071 info.billed += Number(item['summary.total_owed']) * 100;
1072 info.paid += Number(item['summary.total_paid']) * 100;
1080 $scope.totals.selected_billed = function() {
1081 return selected_payment_info().billed;
1083 $scope.totals.selected_paid = function() {
1084 return selected_payment_info().paid;
1087 $scope.showFullDetails = function(all) {
1089 $location.path('/circ/patron/' +
1090 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1093 // For now, only adds billing to first selected item.
1094 // Could do batches later if needed
1095 $scope.addBilling = function(all) {
1097 egBilling.showBillDialog({
1098 xact : egCore.idl.flatToNestedHash(all[0]),
1099 patron : $scope.patron()
1100 }).then(function() {
1101 $scope.gridControls.refresh();
1102 patronSvc.fetchUserStats();
1107 $scope.printBills = function(selected) { // FIXME: refactor me
1108 if (!selected.length) return;
1109 // bills print receipt assumes nested hashes, but our grid
1110 // stores flattener data. Fetch the selected xacts as
1111 // fleshed pcrud objects and hashify.
1112 // (Consider an alternate approach..)
1113 var ids = selected.map(function(t){ return t.id });
1115 egCore.pcrud.search('mbt',
1117 {flesh : 5, flesh_fields : {
1118 'mbt' : ['summary', 'circulation'],
1119 'circ' : ['target_copy'],
1120 'acp' : ['call_number'],
1121 'acn' : ['record','owning_lib','prefix','suffix'],
1122 'bre' : ['simple_record']
1125 {authoritative : true}
1128 var cusr = patronSvc.current;
1129 egCore.print.print({
1130 context : 'receipt',
1131 template : 'bills_historical',
1133 transactions : xacts,
1134 current_location : egCore.idl.toHash(
1135 egCore.org.get(egCore.auth.user().ws_ou())),
1137 prefix : cusr.prefix(),
1138 pref_prefix : cusr.pref_prefix(),
1139 pref_first_given_name : cusr.pref_first_given_name(),
1140 pref_second_given_name : cusr.pref_second_given_name(),
1141 pref_family_name : cusr.pref_family_name(),
1142 pref_suffix : cusr.pref_suffix(),
1143 first_given_name : cusr.first_given_name(),
1144 second_given_name : cusr.second_given_name(),
1145 family_name : cusr.family_name(),
1146 suffix : cusr.suffix(),
1147 card : { barcode : cusr.card().barcode() },
1148 expire_date : cusr.expire_date(),
1149 alias : cusr.alias(),
1150 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1151 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1159 billing_total : xact.billing_total(),
1160 billings : xact.billings(),
1161 grocery : xact.grocery(),
1163 payment_total : xact.payment_total(),
1164 payments : xact.payments(),
1165 summary : egCore.idl.toHash(xact.summary()),
1166 unrecovered : xact.unrecovered(),
1167 xact_finish : xact.xact_finish(),
1168 xact_start : xact.xact_start(),
1170 if (xact.circulation()) {
1171 newXact.copy_barcode = xact.circulation().target_copy().barcode();
1172 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
1173 newXact.call_number = {
1174 label : xact.circulation().target_copy().call_number().label(),
1175 prefix : xact.circulation().target_copy().call_number().prefix().label(),
1176 suffix : xact.circulation().target_copy().call_number().suffix().label(),
1178 name : xact.circulation().target_copy().call_number().owning_lib().name(),
1179 shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
1183 xacts.push(newXact);
1189 .controller('BillPaymentHistoryCtrl',
1190 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1191 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1193 // generate a grid query with the current date widget values.
1194 function current_grid_query() {
1196 'payment_ts' : {between : $scope.date_range()},
1197 'xact.usr' : billSvc.userId
1201 $scope.gridControls = {
1202 selectedItems : function(){return []},
1203 activateItem : function(item) {
1204 $scope.showFullDetails([item]);
1206 setSort : function() {
1207 return [{'payment_ts' : 'DESC'}, 'id'];
1209 setQuery : current_grid_query
1212 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1213 if (new_date !== old_date && new_date) {
1214 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1215 $scope.dates.xact_finish = new_date;
1217 $scope.actions.apply_date_range();
1221 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1222 if (new_date !== old_date && new_date) {
1223 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1224 $scope.dates.xact_start = new_date;
1226 $scope.actions.apply_date_range();
1231 $scope.actions.apply_date_range = function() {
1232 // tells the grid to re-draw itself with the new query
1233 $scope.gridControls.setQuery(current_grid_query());
1236 $scope.showFullDetails = function(all) {
1238 $location.path('/circ/patron/' +
1239 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1242 $scope.totals.selected_paid = function() {
1244 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1245 paid += Number(payment.amount) * 100;