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', '$sce',
177 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
178 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
179 egBilling , $uibModal, $sce) {
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) {
255 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
256 if (item['circulation.stop_fines'] == "LOST") {
257 icon = 'glyphicon-question-sign';
258 text = egCore.strings.STOP_FINES_LOST;
259 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
260 icon = 'glyphicon-exclamation-sign';
261 text = egCore.strings.STOP_FINES_LONGOVERDUE;
263 icon = 'glyphicon-time';
264 text = egCore.strings.CIRC_OVERDUE;
267 return $sce.trustAsHtml("<i class='glyphicon " + icon + "' title='" + text + "' aria-hidden='true'></i><span class='sr-only'>" + text + "</span>");
271 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
273 // given a payment amount, determines how much of that is applied
274 // to selected transactions and how much is left over (change).
275 function pending_payment_info() {
276 var amt = $scope.payment_amount || 0;
277 if (amt >= $scope.owed_selected()) {
279 payment : $scope.owed_selected(),
280 change : amt - $scope.owed_selected()
283 return {payment : amt, change : 0};
286 // calculates amount owed, billed, and paid for selected items
287 // TODO: move me to service
288 function selected_payment_info() {
289 var info = {owed : 0, billed : 0, paid : 0};
290 angular.forEach($scope.gridControls.selectedItems(), function(item) {
291 info.owed += Number(item['summary.balance_owed']) * 100;
292 info.billed += Number(item['summary.total_owed']) * 100;
293 info.paid += Number(item['summary.total_paid']) * 100;
301 $scope.pending_payment = function() {
302 return pending_payment_info().payment;
304 $scope.pending_change = function() {
305 return pending_payment_info().change;
307 $scope.owed_selected = function() {
308 return selected_payment_info().owed;
310 $scope.billed_selected = function() {
311 return selected_payment_info().billed;
313 $scope.paid_selected = function() {
314 return selected_payment_info().paid;
316 $scope.refunds_available = function() {
318 angular.forEach($scope.gridControls.allItems(), function(item) {
319 if (item['summary.balance_owed'] < 0)
320 amount += item['summary.balance_owed'] * 100;
322 return -(amount / 100);
324 $scope.invalid_check_number = function() {
325 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
328 // update the item.payment_pending value each time the user
329 // selects different transactions to pay against.
331 function() {return $scope.gridControls.selectedItems()},
332 function() {updatePendingColumn()},
336 // update the item.payment_pending for each (selected)
337 // transaction any time the user-entered payment amount is modified
338 $scope.$watch('payment_amount', updatePendingColumn);
340 // updates the value of the payment_pending column in the grid.
341 // This has to be managed manually since the display value in the grid
342 // is derived from the value on the stored item and not the contents
343 // of our local scope variables.
344 function updatePendingColumn() {
345 // reset all to zero..
346 angular.forEach($scope.gridControls.allItems(),
347 function(item) {item.payment_pending = 0});
349 var payment_amount = $scope.pending_payment();
351 var selected = $scope.gridControls.selectedItems();
352 for (var i = 0; i < selected.length; i++) { // for/break
353 var item = selected[i];
354 var owed = Number(item['summary.balance_owed']);
356 if (payment_amount > owed) {
357 // pending payment exceeds balance of current item.
358 // pay the entire item.
359 item.payment_pending = owed;
360 payment_amount -= owed;
363 // balance owed on the current item matches or exceeds
364 // the pending payment. Apply the full remainder of
365 // the payment to this item.. and we're done.
366 // Limit to two decimal places to avoid floating point issues
367 item.payment_pending = payment_amount.toFixed(2);
373 // builds payment arrays ([xact_id, ammount]) for all transactions
374 // which have a pending payment amount.
375 function generatePayments() {
377 angular.forEach($scope.gridControls.selectedItems(), function(item) {
378 if (item.payment_pending == 0) return;
379 payments.push([item.id, item.payment_pending]);
384 function refreshDisplay() {
385 patronSvc.fetchUserStats();
386 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
387 $scope.payment_amount = null;
388 $scope.gridControls.refresh();
391 // generates payments, collects user note if needed, and sends payment
393 function sendPayment(note, cc_args) {
394 $scope.applyingPayment = true;
395 var make_payments = generatePayments();
396 var patron_credit = $scope.convert_to_credit.isChecked ?
397 $scope.pending_change() : 0;
398 billSvc.applyPayment($scope.payment_type,
399 make_payments, note, $scope.check_number, cc_args, patron_credit)
401 function(payment_ids) {
402 var approval_code = cc_args ? cc_args.approval_code : '';
403 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
405 $scope.payment_type, payment_ids, make_payments, note, approval_code);
411 console.error('Payment was rejected: ' + msg);
414 .finally(function() { $scope.applyingPayment = false; })
417 $scope.onReceiptOnPayChanged = function(){
418 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
421 $scope.onAnnotatePaymentChanged = function(){
422 egCore.hatch.setItem('eg.circ.bills.annotatepayment', $scope.annotate_payment);
425 function printReceipt(type, payment_ids, payments_made, note, approval_code) {
426 var payment_blobs = [];
427 var cusr = patronSvc.current;
429 angular.forEach(payments_made, function(payment) {
430 var xact_id = payment[0];
432 // find the original transaction in the grid..
433 var xact = $scope.gridControls.allItems().filter(
434 function(item) {return item.id == xact_id})[0];
437 xact : egCore.idl.flatToNestedHash(xact),
442 console.log(js2JSON(payment_blobs[0]));
444 // page data not yet refreshed, capture data from current scope
448 approval_code : approval_code,
449 previous_balance : Number($scope.summary.balance_owed()),
450 payment_total : Number($scope.payment_amount),
451 payment_applied : $scope.pending_payment(),
452 amount_voided : Number($scope.session_voided),
453 change_given : $scope.pending_change(),
454 payments : payment_blobs,
455 current_location : egCore.idl.toHash(
456 egCore.org.get(egCore.auth.user().ws_ou()))
459 // Not a good idea to use patron_stats.fines for this; it's out of date
460 print_data.patron = {
461 prefix : cusr.prefix(),
462 first_given_name : cusr.first_given_name(),
463 second_given_name : cusr.second_given_name(),
464 family_name : cusr.family_name(),
465 suffix : cusr.suffix(),
466 pref_prefix : cusr.pref_prefix(),
467 pref_first_given_name : cusr.pref_first_given_name(),
468 pref_second_given_name : cusr.pref_second_given_name(),
469 pref_family_name : cusr.pref_family_name(),
470 pref_suffix : cusr.pref_suffix(),
471 card : { barcode : cusr.card().barcode() },
472 expire_date : cusr.expire_date(),
473 alias : cusr.alias(),
474 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
475 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
478 print_data.new_balance = (
479 print_data.previous_balance * 100 -
480 print_data.payment_applied * 100) / 100;
482 for (var i = 0; i < $scope.receipt_count; i++) {
485 template : 'bill_payment',
491 $scope.showHistory = function() {
492 $location.path('/circ/patron/' +
493 patronSvc.current.id() + '/bill_history/transactions');
496 // For now, only adds billing to first selected item.
497 // Could do batches later if needed
498 $scope.addBilling = function(all) {
500 egBilling.showBillDialog({
501 xact : egCore.idl.flatToNestedHash(all[0]),
502 patron : $scope.patron()
503 }).then(refreshDisplay);
507 $scope.showBillDialog = function($event) {
508 egBilling.showBillDialog({
509 patron : $scope.patron()
510 }).then(refreshDisplay);
513 // Select refunds adds all refunds to the existing selection.
514 // It does not /only/ select refunds
515 $scope.selectRefunds = function() {
516 var ids = $scope.gridControls.selectedItems().map(
517 function(i) { return i.id });
518 angular.forEach($scope.gridControls.allItems(), function(item) {
519 if (Number(item['summary.balance_owed']) < 0)
522 $scope.gridControls.selectItems(ids);
526 // determine on initial page load when all of the grid rows should
528 var selectOnLoad = true;
529 billSvc.fetchBillSettings().then(function(s) {
530 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
531 $scope.focus_payment = false; // de-focus the payment box
532 $scope.gridControls.focusRowSelector = true;
533 selectOnLoad = false;
534 // if somehow the grid finishes rendering before our settings
535 // arrive, manually de-select everything.
536 $scope.gridControls.selectItems([]);
538 if (s['ui.circ.billing.amount_warn']) {
539 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
541 if (s['ui.circ.billing.amount_limit']) {
542 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
544 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
545 $scope.disable_auto_print = Boolean(
546 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
549 if (s['circ.disable_patron_credit']) {
550 $scope.disablePatronCredit = true;
552 if (!s['credit.processor.default']) {
553 // If we don't have a CC processor, we should disable the "internal" CC form
554 $scope.disableCreditCardForm = true;
556 // Stripe isn't supported in the staff client currently, so disable here too
557 $scope.disableCreditCardForm = (s['credit.processor.default'] == 'Stripe');
561 $scope.gridControls.allItemsRetrieved = function() {
563 selectOnLoad = false; // only for initial controller load.
564 // select all non-refund items
565 $scope.gridControls.selectItems(
566 $scope.gridControls.allItems()
567 .filter(function(i) {return i['summary.balance_owed'] > 0})
568 .map(function(i){return i.id})
575 $scope.printBills = function(selected) {
576 if (!selected.length) return;
577 // bills print receipt assumes nested hashes, but our grid
578 // stores flattener data. Fetch the selected xacts as
579 // fleshed pcrud objects and hashify.
580 // (Consider an alternate approach..)
581 var ids = selected.map(function(t){ return t.id });
583 egCore.pcrud.search('mbt',
585 {flesh : 5, flesh_fields : {
586 'mbt' : ['summary', 'circulation'],
587 'circ' : ['target_copy'],
588 'acp' : ['call_number'],
589 'acn' : ['record','owning_lib','prefix','suffix'],
590 'bre' : ['simple_record']
593 {authoritative : true}
596 var cusr = patronSvc.current;
599 template : 'bills_current',
601 transactions : xacts,
602 current_location : egCore.idl.toHash(
603 egCore.org.get(egCore.auth.user().ws_ou())),
605 prefix : cusr.prefix(),
606 first_given_name : cusr.first_given_name(),
607 second_given_name : cusr.second_given_name(),
608 family_name : cusr.family_name(),
609 suffix : cusr.suffix(),
610 pref_prefix : cusr.pref_prefix(),
611 pref_first_given_name : cusr.pref_first_given_name(),
612 pref_second_given_name : cusr.pref_second_given_name(),
613 pref_family_name : cusr.pref_family_name(),
614 pref_suffix : cusr.pref_suffix(),
615 card : { barcode : cusr.card().barcode() },
616 expire_date : cusr.expire_date(),
617 alias : cusr.alias(),
618 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
619 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
627 billing_total : xact.billing_total(),
628 billings : xact.billings(),
629 grocery : xact.grocery(),
631 payment_total : xact.payment_total(),
632 payments : xact.payments(),
633 summary : egCore.idl.toHash(xact.summary()),
634 unrecovered : xact.unrecovered(),
635 xact_finish : xact.xact_finish(),
636 xact_start : xact.xact_start(),
638 if (xact.circulation()) {
639 newXact.copy_barcode = xact.circulation().target_copy().barcode();
640 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
641 newXact.call_number = {
642 label : xact.circulation().target_copy().call_number().label(),
643 prefix : xact.circulation().target_copy().call_number().prefix().label(),
644 suffix : xact.circulation().target_copy().call_number().suffix().label(),
646 name : xact.circulation().target_copy().call_number().owning_lib().name(),
647 shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
656 $scope.applyPayment = function() {
658 if ($scope.payment_amount > $scope.max_amount ) {
660 egCore.strings.PAYMENT_OVER_MAX,
661 { max_amount : ''+$scope.max_amount,
663 $scope.payment_amount = 0;
670 verify_payment_amount().then(
671 function() { // amount confirmed
672 add_payment_note().then(function(pay_note) {
673 add_cc_args().then(function(cc_args) {
674 var note_text = pay_note ? pay_note.value || '' : null;
675 sendPayment(note_text, cc_args);
679 function() { // amount rejected
680 console.warn('payment amount rejected');
681 $scope.payment_amount = 0;
686 function verify_payment_amount() {
687 if ($scope.payment_amount < $scope.warn_amount)
690 return egConfirmDialog.open(
691 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
692 egCore.strings.PAYMENT_WARN_AMOUNT,
693 {payment_amount : ''+$scope.payment_amount}
697 function add_payment_note() {
698 if (!$scope.annotate_payment) return $q.when();
699 return egPromptDialog.open(
700 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
703 function add_cc_args() {
704 if ($scope.payment_type != 'credit_card_payment')
707 var disableCreditCardForm = $scope.disableCreditCardForm;
709 return $uibModal.open({
710 templateUrl : './circ/patron/t_cc_payment_dialog',
713 '$scope','$uibModalInstance',
714 function($scope , $uibModalInstance) {
718 where_process : disableCreditCardForm ? '0' : '1', // internal=1 ; external=0
719 disable_internal : disableCreditCardForm,
720 type : 'VISA', // external only
721 billing_first : patronSvc.current.first_given_name(),
722 billing_last : patronSvc.current.family_name()
726 var addr = patronSvc.current.billing_address() ||
727 patronSvc.current.mailing_address();
729 var cc = $scope.context.cc;
730 cc.billing_address = addr.street1() +
731 (addr.street2() ? ' ' + addr.street2() : '');
732 cc.billing_city = addr.city();
733 cc.billing_state = addr.state();
734 cc.billing_zip = addr.post_code();
737 $scope.ok = function() {
738 // CC payment form is not a <form>,
739 // so apply validation manually.
740 if ( $scope.context.cc.where_process == 0 &&
741 !$scope.context.cc.approval_code)
744 $uibModalInstance.close($scope.context.cc);
747 $scope.cancel = function() {
748 $uibModalInstance.dismiss();
755 $scope.voidAllBillings = function(items) {
759 angular.forEach(items, function(item) {
761 billSvc.fetchBills(item.id).then(function(bills) {
762 angular.forEach(bills, function(b) {
763 if (b.voided() != 't') {
764 cents += b.amount() * 100;
765 bill_ids.push(b.id())
769 if (bill_ids.length == 0) {
778 $q.all(promises).then(function(){
779 egCore.audio.play('warning.circ.void_billings_confirmation');
780 egConfirmDialog.open(
781 egCore.strings.CONFIRM_VOID_BILLINGS, '',
782 { billIds : ''+bill_ids,
783 amount : ''+(cents/100),
785 billSvc.voidBills(bill_ids).then(function() {
786 $scope.session_voided =
787 ($scope.session_voided * 100 + cents) / 100;
796 $scope.adjustToZero = function(items) {
797 if (items.length == 0) return;
799 var ids = items.map(function(item) {return item.id});
801 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
802 egConfirmDialog.open(
803 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
806 billSvc.adjustBillsToZero(ids).then(function() {
815 // note this is functionally equivalent to selecting a neg. transaction
816 // then clicking Apply Payment -- this just adds a speed bump (ditto
818 $scope.refundXact = function(all) {
819 var items = all.filter(function(item) {
820 return item['summary.balance_owed'] < 0
823 if (items.length == 0) return;
825 var ids = items.map(function(item) {return item.id});
827 egCore.audio.play('warning.circ.refund_confirmation');
828 egConfirmDialog.open(
829 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
832 // reset the received payment amount. this ensures
833 // we're not mingling payments with refunds.
834 $scope.payment_amount = 0;
840 // direct the user to the transaction details page
841 $scope.showFullDetails = function(all) {
842 var lastClicked = $scope.gridControls.contextMenuItem();
844 $location.path('/circ/patron/' +
845 patronSvc.current.id() + '/bill/' + lastClicked + '/statement');
847 $location.path('/circ/patron/' +
848 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
853 $scope.activateBill = function(xact) {
854 $scope.showFullDetails([xact]);
860 * Displays details of a single transaction
862 .controller('XactDetailsCtrl',
863 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
864 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
866 $scope.initTab('bills', $routeParams.id);
867 var xact_id = $routeParams.xact_id;
868 $scope.xact_tab = $routeParams.xact_tab;
870 var xactGrid = $scope.xactGridControls = {
871 setQuery : function() { return {xact : xact_id} },
872 setSort : function() { return ['billing_ts'] }
875 var paymentGrid = $scope.paymentGridControls = {
876 setQuery : function() { return {xact : xact_id} },
877 setSort : function() { return ['payment_ts'] }
881 $scope.voidBillings = function(bill_list) {
884 angular.forEach(bill_list, function(b) {
885 if (b.voided != 't') {
886 cents += b.amount * 100;
891 if (bill_ids.length == 0) {
896 egCore.audio.play('warning.circ.void_billings_confirmation');
897 egConfirmDialog.open(
898 egCore.strings.CONFIRM_VOID_BILLINGS, '',
899 { billIds : ''+bill_ids,
900 amount : ''+(cents/100),
902 billSvc.voidBills(bill_ids).then(function() {
903 // TODO? $scope.session_voided = ...
905 // refresh bills and summary data
906 // note: no need to update payments
907 patronSvc.fetchUserStats();
909 egBilling.fetchXact(xact_id).then(function(xact) {
920 // batch-edit billing and payment notes, depending on 'type'
921 function editNotes(selected, type) {
922 var notes = selected.map(function(b){ return b.note }).join(',');
923 var ids = selected.map(function(b){ return b.id });
925 // show the note edit prompt
927 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
929 ok : function(value) {
931 var func = 'updateBillNotes';
932 if (type == 'payment') func = 'updatePaymentNotes';
934 billSvc[func](value, ids).then(function() {
935 if (type == 'payment') {
936 paymentGrid.refresh();
946 $scope.editBillNotes = function(selected) {
947 editNotes(selected, 'bill');
950 $scope.editPaymentNotes = function(selected) {
951 editNotes(selected, 'payment');
954 // -- retrieve our data
955 if ($scope.xact_tab == 'statement') {
956 //fetch combined billing statement data
957 billSvc.fetchStatement(xact_id).then(function(statement) {
958 //console.log(statement);
959 $scope.statement_data = statement;
962 $scope.total_circs = 0; // start with 0 instead of undefined
963 egBilling.fetchXact(xact_id).then(function(xact) {
966 var copyId = xact.circulation().target_copy().id();
968 egCore.pcrud.search('circbyyr',
969 {copy : copyId}, null, {atomic : true})
970 .then(function(counts) {
971 angular.forEach(counts, function(count) {
972 circ_count += Number(count.count());
974 $scope.total_circs = circ_count;
976 // set the title. only needs to be done on initial page load
977 if (xact.circulation()) {
978 if (xact.circulation().target_copy().call_number().id() == -1) {
979 $scope.title = xact.circulation().target_copy().dummy_title();
981 // TODO: shared bib service?
982 $scope.title = xact.circulation().target_copy()
983 .call_number().record().simple_record().title();
984 $scope.title_id = xact.circulation().target_copy()
985 .call_number().record().id();
992 .controller('BillHistoryCtrl',
993 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
994 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
996 $scope.initTab('bills', $routeParams.id);
997 billSvc.userId = $routeParams.id;
998 $scope.bill_tab = $routeParams.history_tab;
1001 // link page controller actions defined by sub-controllers here
1002 $scope.actions = {};
1004 var start = new Date(); // now - 1 year
1005 start.setFullYear(start.getFullYear() - 1),
1008 xact_finish : new Date()
1011 $scope.date_range = function() {
1012 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
1013 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
1014 var today = new Date().toISOString().replace(/T.*/,'');
1015 if (end == today) end = 'now';
1016 return [start, end];
1021 .controller('BillXactHistoryCtrl',
1022 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
1023 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
1025 // generate a grid query with the current date widget values.
1026 function current_grid_query() {
1029 {'summary.balance_owed' : {'<>' : 0}},
1030 {'summary.last_payment_ts' : {'<>' : null}}
1032 xact_start : {between : $scope.date_range()},
1033 usr : billSvc.userId
1037 $scope.gridControls = {
1038 selectedItems : function(){return []},
1039 activateItem : function(item) {
1040 $scope.showFullDetails([item]);
1042 // this sets the query on page load
1043 setQuery : current_grid_query
1046 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1047 if (new_date !== old_date && new_date) {
1048 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1049 $scope.dates.xact_finish = new_date;
1051 $scope.actions.apply_date_range();
1055 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1056 if (new_date !== old_date && new_date) {
1057 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1058 $scope.dates.xact_start = new_date;
1060 $scope.actions.apply_date_range();
1065 $scope.actions.apply_date_range = function() {
1066 // tells the grid to re-draw itself with the new query
1067 $scope.gridControls.setQuery(current_grid_query());
1070 // TODO; move me to service
1071 function selected_payment_info() {
1072 var info = {owed : 0, billed : 0, paid : 0};
1073 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1074 info.owed += Number(item['summary.balance_owed']) * 100;
1075 info.billed += Number(item['summary.total_owed']) * 100;
1076 info.paid += Number(item['summary.total_paid']) * 100;
1084 $scope.totals.selected_billed = function() {
1085 return selected_payment_info().billed;
1087 $scope.totals.selected_paid = function() {
1088 return selected_payment_info().paid;
1091 $scope.showFullDetails = function(all) {
1093 $location.path('/circ/patron/' +
1094 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1097 // For now, only adds billing to first selected item.
1098 // Could do batches later if needed
1099 $scope.addBilling = function(all) {
1101 egBilling.showBillDialog({
1102 xact : egCore.idl.flatToNestedHash(all[0]),
1103 patron : $scope.patron()
1104 }).then(function() {
1105 $scope.gridControls.refresh();
1106 patronSvc.fetchUserStats();
1111 $scope.printBills = function(selected) { // FIXME: refactor me
1112 if (!selected.length) return;
1113 // bills print receipt assumes nested hashes, but our grid
1114 // stores flattener data. Fetch the selected xacts as
1115 // fleshed pcrud objects and hashify.
1116 // (Consider an alternate approach..)
1117 var ids = selected.map(function(t){ return t.id });
1119 egCore.pcrud.search('mbt',
1121 {flesh : 5, flesh_fields : {
1122 'mbt' : ['summary', 'circulation'],
1123 'circ' : ['target_copy'],
1124 'acp' : ['call_number'],
1125 'acn' : ['record','owning_lib','prefix','suffix'],
1126 'bre' : ['simple_record']
1129 {authoritative : true}
1132 var cusr = patronSvc.current;
1133 egCore.print.print({
1134 context : 'receipt',
1135 template : 'bills_historical',
1137 transactions : xacts,
1138 current_location : egCore.idl.toHash(
1139 egCore.org.get(egCore.auth.user().ws_ou())),
1141 prefix : cusr.prefix(),
1142 pref_prefix : cusr.pref_prefix(),
1143 pref_first_given_name : cusr.pref_first_given_name(),
1144 pref_second_given_name : cusr.pref_second_given_name(),
1145 pref_family_name : cusr.pref_family_name(),
1146 pref_suffix : cusr.pref_suffix(),
1147 first_given_name : cusr.first_given_name(),
1148 second_given_name : cusr.second_given_name(),
1149 family_name : cusr.family_name(),
1150 suffix : cusr.suffix(),
1151 card : { barcode : cusr.card().barcode() },
1152 expire_date : cusr.expire_date(),
1153 alias : cusr.alias(),
1154 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1155 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1163 billing_total : xact.billing_total(),
1164 billings : xact.billings(),
1165 grocery : xact.grocery(),
1167 payment_total : xact.payment_total(),
1168 payments : xact.payments(),
1169 summary : egCore.idl.toHash(xact.summary()),
1170 unrecovered : xact.unrecovered(),
1171 xact_finish : xact.xact_finish(),
1172 xact_start : xact.xact_start(),
1174 if (xact.circulation()) {
1175 newXact.copy_barcode = xact.circulation().target_copy().barcode();
1176 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title();
1177 newXact.call_number = {
1178 label : xact.circulation().target_copy().call_number().label(),
1179 prefix : xact.circulation().target_copy().call_number().prefix().label(),
1180 suffix : xact.circulation().target_copy().call_number().suffix().label(),
1182 name : xact.circulation().target_copy().call_number().owning_lib().name(),
1183 shortname : xact.circulation().target_copy().call_number().owning_lib().shortname()
1187 xacts.push(newXact);
1193 .controller('BillPaymentHistoryCtrl',
1194 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1195 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1197 // generate a grid query with the current date widget values.
1198 function current_grid_query() {
1200 'payment_ts' : {between : $scope.date_range()},
1201 'xact.usr' : billSvc.userId
1205 $scope.gridControls = {
1206 selectedItems : function(){return []},
1207 activateItem : function(item) {
1208 $scope.showFullDetails([item]);
1210 setSort : function() {
1211 return [{'payment_ts' : 'DESC'}, 'id'];
1213 setQuery : current_grid_query
1216 $scope.$watch('dates.xact_start', function(new_date, old_date) {
1217 if (new_date !== old_date && new_date) {
1218 if (new_date.getTime() > $scope.dates.xact_finish.getTime()) {
1219 $scope.dates.xact_finish = new_date;
1221 $scope.actions.apply_date_range();
1225 $scope.$watch('dates.xact_finish', function(new_date, old_date) {
1226 if (new_date !== old_date && new_date) {
1227 if (new_date.getTime() < $scope.dates.xact_start.getTime()) {
1228 $scope.dates.xact_start = new_date;
1230 $scope.actions.apply_date_range();
1235 $scope.actions.apply_date_range = function() {
1236 // tells the grid to re-draw itself with the new query
1237 $scope.gridControls.setQuery(current_grid_query());
1240 $scope.showFullDetails = function(all) {
1242 $location.path('/circ/patron/' +
1243 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1246 $scope.totals.selected_paid = function() {
1248 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1249 paid += Number(payment.amount) * 100;