4 angular.module('egPatronApp')
7 ['$q','egCore','egWorkLog','patronSvc',
8 function($q , egCore , egWorkLog , patronSvc) {
12 // fetch org unit settings specific to the bills display
13 service.fetchBillSettings = function() {
14 if (service.settings) return $q.when(service.settings);
15 return egCore.org.settings([
16 'ui.circ.billing.uncheck_bills_and_unfocus_payment_box',
17 'ui.circ.billing.amount_warn', 'ui.circ.billing.amount_limit',
18 'circ.staff_client.do_not_auto_attempt_print',
19 'circ.disable_patron_credit'
20 ]).then(function(s) {return service.settings = s});
23 // user billing summary
24 service.fetchSummary = function() {
25 return egCore.pcrud.retrieve(
26 'mous', service.userId, {}, {authoritative : true})
27 .then(function(summary) {return service.summary = summary})
30 service.applyPayment = function(
31 type, payments, note, check, cc_args, patron_credit) {
33 return egCore.net.request(
35 'open-ils.circ.money.payment',
36 egCore.auth.token(), {
37 userid : service.userId,
42 patron_credit : patron_credit,
45 patronSvc.current.last_xact_id()
46 ).then(function(resp) {
47 console.debug('payments: ' + js2JSON(resp));
49 if (evt = egCore.evt.parse(resp)) {
50 // Ideally, all scenarios that lead to this alert appearing
51 // will be avoided by the application logic. Leave the alert
52 // in place now to root out any that remain to be addressed.
54 return $q.reject(''+evt);
57 var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
60 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
61 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
62 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
63 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
64 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
65 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
66 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
70 'action' : 'paid_bill',
71 'patron_id' : service.userId,
72 'total_amount' : total
76 // payment API returns the update xact id so we can track it
77 // for future payments without having to refresh the user.
78 patronSvc.current.last_xact_id(resp.last_xact_id);
83 service.fetchBills = function(xact_id) {
85 return egCore.pcrud.search('mb',
86 {xact : xact_id}, null,
87 {authoritative : true}
89 function() {return bills},
91 function(bill) {bills.push(bill); return bill}
95 service.fetchStatement = function(xact_id) {
96 return egCore.net.request(
98 'open-ils.circ.money.statement.retrieve',
99 egCore.auth.token(), xact_id
100 ).then(function(resp) {
101 if (evt = egCore.evt.parse(resp)) return alert(evt);
106 // TODO: no longer needed?
107 service.fetchPayments = function(xact_id) {
108 return egCore.net.request(
110 'open-ils.circ.money.payment.retrieve.all.authoritative',
111 egCore.auth.token(), xact_id
115 service.voidBills = function(bill_ids) {
116 return egCore.net.requestWithParamList(
118 'open-ils.circ.money.billing.void',
119 [egCore.auth.token()].concat(bill_ids)
120 ).then(function(resp) {
121 if (evt = egCore.evt.parse(resp)) return alert(evt);
126 service.adjustBillsToZero = function(bill_ids) {
127 return egCore.net.request(
129 'open-ils.circ.money.billable_xact.adjust_to_zero',
132 ).then(function(resp) {
133 if (evt = egCore.evt.parse(resp)) return alert(evt);
138 service.updateBillNotes = function(note, ids) {
139 return egCore.net.requestWithParamList(
141 'open-ils.circ.money.billing.note.edit',
142 [egCore.auth.token(), note].concat(ids)
143 ).then(function(resp) {
144 if (evt = egCore.evt.parse(resp)) return alert(evt);
149 service.updatePaymentNotes = function(note, ids) {
150 return egCore.net.requestWithParamList(
152 'open-ils.circ.money.payment.note.edit',
153 [egCore.auth.token(), note].concat(ids)
154 ).then(function(resp) {
155 if (evt = egCore.evt.parse(resp)) return alert(evt);
167 .controller('PatronBillsCtrl',
168 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
169 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
170 'egBilling','$uibModal',
171 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
172 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
173 egBilling , $uibModal) {
175 $scope.initTab('bills', $routeParams.id);
176 billSvc.userId = $routeParams.id;
178 // set up some defaults
179 $scope.check_number = null;
180 $scope.payment_amount = null;
181 $scope.session_voided = 0;
182 $scope.payment_type = 'cash_payment';
183 $scope.focus_payment = true;
184 $scope.annotate_payment = false;
185 $scope.receipt_count = 1;
186 $scope.receipt_on_pay = { isChecked: false };
187 $scope.convert_to_credit = {isChecked: false};
188 $scope.warn_amount = 1000;
189 $scope.max_amount = 100000;
190 $scope.amount_verified = false;
191 $scope.disable_auto_print = false;
193 // check receipt_on_pay setting default persisted
194 egCore.hatch.getItem('circ.bills.receiptonpay')
195 .then(function(rcptOnPay){
196 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
199 // pre-define list-returning funcs in case we access them
200 // before the grid instantiates
201 $scope.gridControls = {
202 focusRowSelector : false,
203 selectedItems : function(){return []},
204 allItems : function(){return []},
205 itemRetrieved : function(item) {
206 item.payment_pending = 0;
208 activateItem : function(item) {
209 $scope.showFullDetails([item]);
211 setQuery : function() {
213 usr : billSvc.userId,
215 'summary.balance_owed' : {'<>' : 0}
218 setSort : function() {
219 return ['xact_start'];
223 // Apply coloring to rows based on fines stop reason
224 $scope.colorizeBillsList = {
225 apply: function(item) {
226 if (!item['circulation.checkin_time']) {
227 if (item['circulation.stop_fines'] == 'LOST') {
229 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
230 return 'longoverdue-row';
232 return 'overdue-row';
238 // Status Icon Column definition
239 $scope.statusIconColumn = {
241 template: function(item) {
243 if (!item['circulation.checkin_time']) {
244 if (item['circulation.stop_fines'] == "LOST") {
245 icon = 'glyphicon-question-sign';
246 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
247 icon = 'glyphicon-exclamation-sign';
249 icon = 'glyphicon-time';
252 return "<i class='glyphicon " + icon + "'></i>"
256 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
258 // given a payment amount, determines how much of that is applied
259 // to selected transactions and how much is left over (change).
260 function pending_payment_info() {
261 var amt = $scope.payment_amount || 0;
262 if (amt >= $scope.owed_selected()) {
264 payment : $scope.owed_selected(),
265 change : amt - $scope.owed_selected()
268 return {payment : amt, change : 0};
271 // calculates amount owed, billed, and paid for selected items
272 // TODO: move me to service
273 function selected_payment_info() {
274 var info = {owed : 0, billed : 0, paid : 0};
275 angular.forEach($scope.gridControls.selectedItems(), function(item) {
276 info.owed += Number(item['summary.balance_owed']) * 100;
277 info.billed += Number(item['summary.total_owed']) * 100;
278 info.paid += Number(item['summary.total_paid']) * 100;
286 $scope.pending_payment = function() {
287 return pending_payment_info().payment;
289 $scope.pending_change = function() {
290 return pending_payment_info().change;
292 $scope.owed_selected = function() {
293 return selected_payment_info().owed;
295 $scope.billed_selected = function() {
296 return selected_payment_info().billed;
298 $scope.paid_selected = function() {
299 return selected_payment_info().paid;
301 $scope.refunds_available = function() {
303 angular.forEach($scope.gridControls.allItems(), function(item) {
304 if (item['summary.balance_owed'] < 0)
305 amount += item['summary.balance_owed'] * 100;
307 return -(amount / 100);
309 $scope.invalid_check_number = function() {
310 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
313 // update the item.payment_pending value each time the user
314 // selects different transactions to pay against.
316 function() {return $scope.gridControls.selectedItems()},
317 function() {updatePendingColumn()},
321 // update the item.payment_pending for each (selected)
322 // transaction any time the user-entered payment amount is modified
323 $scope.$watch('payment_amount', updatePendingColumn);
325 // updates the value of the payment_pending column in the grid.
326 // This has to be managed manually since the display value in the grid
327 // is derived from the value on the stored item and not the contents
328 // of our local scope variables.
329 function updatePendingColumn() {
330 // reset all to zero..
331 angular.forEach($scope.gridControls.allItems(),
332 function(item) {item.payment_pending = 0});
334 var payment_amount = $scope.pending_payment();
336 var selected = $scope.gridControls.selectedItems();
337 for (var i = 0; i < selected.length; i++) { // for/break
338 var item = selected[i];
339 var owed = Number(item['summary.balance_owed']);
341 if (payment_amount > owed) {
342 // pending payment exceeds balance of current item.
343 // pay the entire item.
344 item.payment_pending = owed;
345 payment_amount -= owed;
348 // balance owed on the current item matches or exceeds
349 // the pending payment. Apply the full remainder of
350 // the payment to this item.. and we're done.
351 item.payment_pending = payment_amount;
357 // builds payment arrays ([xact_id, ammount]) for all transactions
358 // which have a pending payment amount.
359 function generatePayments() {
361 angular.forEach($scope.gridControls.selectedItems(), function(item) {
362 if (item.payment_pending == 0) return;
363 payments.push([item.id, item.payment_pending]);
368 function refreshDisplay() {
369 patronSvc.fetchUserStats();
370 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
371 $scope.payment_amount = null;
372 $scope.gridControls.refresh();
375 // generates payments, collects user note if needed, and sends payment
377 function sendPayment(note, cc_args) {
378 $scope.applyingPayment = true;
379 var make_payments = generatePayments();
380 var patron_credit = $scope.convert_to_credit.isChecked ?
381 $scope.pending_change() : 0;
382 billSvc.applyPayment($scope.payment_type,
383 make_payments, note, $scope.check_number, cc_args, patron_credit)
385 function(payment_ids) {
387 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
389 $scope.payment_type, payment_ids, make_payments, note);
395 console.error('Payment was rejected: ' + msg);
398 .finally(function() { $scope.applyingPayment = false; })
401 $scope.onReceiptOnPayChanged = function(){
402 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
405 function printReceipt(type, payment_ids, payments_made, note) {
406 var payment_blobs = [];
407 var cusr = patronSvc.current;
409 angular.forEach(payments_made, function(payment) {
410 var xact_id = payment[0];
412 // find the original transaction in the grid..
413 var xact = $scope.gridControls.allItems().filter(
414 function(item) {return item.id == xact_id})[0];
417 xact : egCore.idl.flatToNestedHash(xact),
422 console.log(js2JSON(payment_blobs[0]));
424 // page data not yet refreshed, capture data from current scope
428 previous_balance : Number($scope.summary.balance_owed()),
429 payment_total : Number($scope.payment_amount),
430 payment_applied : $scope.pending_payment(),
431 amount_voided : Number($scope.session_voided),
432 change_given : $scope.pending_change(),
433 payments : payment_blobs,
434 current_location : egCore.idl.toHash(
435 egCore.org.get(egCore.auth.user().ws_ou()))
438 // Not a good idea to use patron_stats.fines for this; it's out of date
439 print_data.patron = {
440 prefix : cusr.prefix(),
441 first_given_name : cusr.first_given_name(),
442 second_given_name : cusr.second_given_name(),
443 family_name : cusr.family_name(),
444 suffix : cusr.suffix(),
445 card : { barcode : cusr.card().barcode() },
446 expire_date : cusr.expire_date(),
447 alias : cusr.alias(),
448 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/).length),
449 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
452 print_data.new_balance = (
453 print_data.previous_balance * 100 -
454 print_data.payment_applied * 100) / 100;
456 for (var i = 0; i < $scope.receipt_count; i++) {
459 template : 'bill_payment',
465 $scope.showHistory = function() {
466 $location.path('/circ/patron/' +
467 patronSvc.current.id() + '/bill_history/transactions');
470 // For now, only adds billing to first selected item.
471 // Could do batches later if needed
472 $scope.addBilling = function(all) {
474 egBilling.showBillDialog({
475 xact : egCore.idl.flatToNestedHash(all[0]),
476 patron : $scope.patron()
477 }).then(refreshDisplay);
481 $scope.showBillDialog = function($event) {
482 egBilling.showBillDialog({
483 patron : $scope.patron()
484 }).then(refreshDisplay);
487 // Select refunds adds all refunds to the existing selection.
488 // It does not /only/ select refunds
489 $scope.selectRefunds = function() {
490 var ids = $scope.gridControls.selectedItems().map(
491 function(i) { return i.id });
492 angular.forEach($scope.gridControls.allItems(), function(item) {
493 if (Number(item['summary.balance_owed']) < 0)
496 $scope.gridControls.selectItems(ids);
500 // determine on initial page load when all of the grid rows should
502 var selectOnLoad = true;
503 billSvc.fetchBillSettings().then(function(s) {
504 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
505 $scope.focus_payment = false; // de-focus the payment box
506 $scope.gridControls.focusRowSelector = true;
507 selectOnLoad = false;
508 // if somehow the grid finishes rendering before our settings
509 // arrive, manually de-select everything.
510 $scope.gridControls.selectItems([]);
512 if (s['ui.circ.billing.amount_warn']) {
513 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
515 if (s['ui.circ.billing.amount_limit']) {
516 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
518 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
519 $scope.disable_auto_print = Boolean(
520 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
523 if (s['circ.disable_patron_credit']) {
524 $scope.disablePatronCredit = true;
528 $scope.gridControls.allItemsRetrieved = function() {
530 selectOnLoad = false; // only for initial controller load.
531 // select all non-refund items
532 $scope.gridControls.selectItems(
533 $scope.gridControls.allItems()
534 .filter(function(i) {return i['summary.balance_owed'] > 0})
535 .map(function(i){return i.id})
542 $scope.printBills = function(selected) {
543 if (!selected.length) return;
544 // bills print receipt assumes nested hashes, but our grid
545 // stores flattener data. Fetch the selected xacts as
546 // fleshed pcrud objects and hashify.
547 // (Consider an alternate approach..)
548 var ids = selected.map(function(t){ return t.id });
550 egCore.pcrud.search('mbt',
552 {flesh : 5, flesh_fields : {
553 'mbt' : ['summary', 'circulation'],
554 'circ' : ['target_copy'],
555 'acp' : ['call_number'],
557 'bre' : ['simple_record']
560 {authoritative : true}
563 var cusr = patronSvc.current;
566 template : 'bills_current',
568 transactions : xacts,
569 current_location : egCore.idl.toHash(
570 egCore.org.get(egCore.auth.user().ws_ou())),
572 prefix : cusr.prefix(),
573 first_given_name : cusr.first_given_name(),
574 second_given_name : cusr.second_given_name(),
575 family_name : cusr.family_name(),
576 suffix : cusr.suffix(),
577 card : { barcode : cusr.card().barcode() },
578 expire_date : cusr.expire_date(),
579 alias : cusr.alias(),
580 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/).length),
581 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
589 billing_total : xact.billing_total(),
590 billings : xact.billings(),
591 grocery : xact.grocery(),
593 payment_total : xact.payment_total(),
594 payments : xact.payments(),
595 summary : egCore.idl.toHash(xact.summary()),
596 unrecovered : xact.unrecovered(),
597 xact_finish : xact.xact_finish(),
598 xact_start : xact.xact_start(),
600 if (xact.circulation()) {
601 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
602 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
609 $scope.applyPayment = function() {
611 if ($scope.payment_amount > $scope.max_amount ) {
613 egCore.strings.PAYMENT_OVER_MAX,
614 { max_amount : ''+$scope.max_amount,
616 $scope.payment_amount = 0;
623 verify_payment_amount().then(
624 function() { // amount confirmed
625 add_payment_note().then(function(pay_note) {
626 add_cc_args().then(function(cc_args) {
627 var note_text = pay_note ? pay_note.value || '' : null;
628 sendPayment(note_text, cc_args);
632 function() { // amount rejected
633 console.warn('payment amount rejected');
634 $scope.payment_amount = 0;
639 function verify_payment_amount() {
640 if ($scope.payment_amount < $scope.warn_amount)
643 return egConfirmDialog.open(
644 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
645 egCore.strings.PAYMENT_WARN_AMOUNT,
646 {payment_amount : ''+$scope.payment_amount}
650 function add_payment_note() {
651 if (!$scope.annotate_payment) return $q.when();
652 return egPromptDialog.open(
653 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
656 function add_cc_args() {
657 if ($scope.payment_type != 'credit_card_payment')
660 return $uibModal.open({
661 templateUrl : './circ/patron/t_cc_payment_dialog',
664 '$scope','$uibModalInstance',
665 function($scope , $uibModalInstance) {
669 where_process : '1', // internal=1 ; external=0
670 type : 'VISA', // external only
671 billing_first : patronSvc.current.first_given_name(),
672 billing_last : patronSvc.current.family_name()
676 var addr = patronSvc.current.billing_address() ||
677 patronSvc.current.mailing_address();
679 var cc = $scope.context.cc;
680 cc.billing_address = addr.street1() +
681 (addr.street2() ? ' ' + addr.street2() : '');
682 cc.billing_city = addr.city();
683 cc.billing_state = addr.state();
684 cc.billing_zip = addr.post_code();
687 $scope.ok = function() {
688 // CC payment form is not a <form>,
689 // so apply validation manually.
690 if ( $scope.context.cc.where_process == 0 &&
691 !$scope.context.cc.approval_code)
694 $uibModalInstance.close($scope.context.cc);
697 $scope.cancel = function() {
698 $uibModalInstance.dismiss();
705 $scope.voidAllBillings = function(items) {
709 angular.forEach(items, function(item) {
711 billSvc.fetchBills(item.id).then(function(bills) {
712 angular.forEach(bills, function(b) {
713 if (b.voided() != 't') {
714 cents += b.amount() * 100;
715 bill_ids.push(b.id())
719 if (bill_ids.length == 0) {
728 $q.all(promises).then(function(){
729 egCore.audio.play('warning.circ.void_billings_confirmation');
730 egConfirmDialog.open(
731 egCore.strings.CONFIRM_VOID_BILLINGS, '',
732 { billIds : ''+bill_ids,
733 amount : ''+(cents/100),
735 billSvc.voidBills(bill_ids).then(function() {
736 $scope.session_voided =
737 ($scope.session_voided * 100 + cents) / 100;
746 $scope.adjustToZero = function(items) {
747 if (items.length == 0) return;
749 var ids = items.map(function(item) {return item.id});
751 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
752 egConfirmDialog.open(
753 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
756 billSvc.adjustBillsToZero(ids).then(function() {
765 // note this is functionally equivalent to selecting a neg. transaction
766 // then clicking Apply Payment -- this just adds a speed bump (ditto
768 $scope.refundXact = function(all) {
769 var items = all.filter(function(item) {
770 return item['summary.balance_owed'] < 0
773 if (items.length == 0) return;
775 var ids = items.map(function(item) {return item.id});
777 egCore.audio.play('warning.circ.refund_confirmation');
778 egConfirmDialog.open(
779 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
782 // reset the received payment amount. this ensures
783 // we're not mingling payments with refunds.
784 $scope.payment_amount = 0;
790 // direct the user to the transaction details page
791 $scope.showFullDetails = function(all) {
793 $location.path('/circ/patron/' +
794 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
797 $scope.activateBill = function(xact) {
798 $scope.showFullDetails([xact]);
804 * Displays details of a single transaction
806 .controller('XactDetailsCtrl',
807 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
808 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
810 $scope.initTab('bills', $routeParams.id);
811 var xact_id = $routeParams.xact_id;
812 $scope.xact_tab = $routeParams.xact_tab;
814 var xactGrid = $scope.xactGridControls = {
815 setQuery : function() { return {xact : xact_id} },
816 setSort : function() { return ['billing_ts'] }
819 var paymentGrid = $scope.paymentGridControls = {
820 setQuery : function() { return {xact : xact_id} },
821 setSort : function() { return ['payment_ts'] }
825 $scope.voidBillings = function(bill_list) {
828 angular.forEach(bill_list, function(b) {
829 if (b.voided != 't') {
830 cents += b.amount * 100;
835 if (bill_ids.length == 0) {
840 egCore.audio.play('warning.circ.void_billings_confirmation');
841 egConfirmDialog.open(
842 egCore.strings.CONFIRM_VOID_BILLINGS, '',
843 { billIds : ''+bill_ids,
844 amount : ''+(cents/100),
846 billSvc.voidBills(bill_ids).then(function() {
847 // TODO? $scope.session_voided = ...
849 // refresh bills and summary data
850 // note: no need to update payments
851 patronSvc.fetchUserStats();
853 egBilling.fetchXact(xact_id).then(function(xact) {
864 // batch-edit billing and payment notes, depending on 'type'
865 function editNotes(selected, type) {
866 var notes = selected.map(function(b){ return b.note }).join(',');
867 var ids = selected.map(function(b){ return b.id });
869 // show the note edit prompt
871 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
873 ok : function(value) {
875 var func = 'updateBillNotes';
876 if (type == 'payment') func = 'updatePaymentNotes';
878 billSvc[func](value, ids).then(function() {
879 if (type == 'payment') {
880 paymentGrid.refresh();
890 $scope.editBillNotes = function(selected) {
891 editNotes(selected, 'bill');
894 $scope.editPaymentNotes = function(selected) {
895 editNotes(selected, 'payment');
898 // -- retrieve our data
899 if ($scope.xact_tab == 'statement') {
900 //fetch combined billing statement data
901 billSvc.fetchStatement(xact_id).then(function(statement) {
902 //console.log(statement);
903 $scope.statement_data = statement;
906 $scope.total_circs = 0; // start with 0 instead of undefined
907 egBilling.fetchXact(xact_id).then(function(xact) {
910 var copyId = xact.circulation().target_copy().id();
912 egCore.pcrud.search('circbyyr',
913 {copy : copyId}, null, {atomic : true})
914 .then(function(counts) {
915 angular.forEach(counts, function(count) {
916 circ_count += Number(count.count());
918 $scope.total_circs = circ_count;
920 // set the title. only needs to be done on initial page load
921 if (xact.circulation()) {
922 if (xact.circulation().target_copy().call_number().id() == -1) {
923 $scope.title = xact.circulation().target_copy().dummy_title();
925 // TODO: shared bib service?
926 $scope.title = xact.circulation().target_copy()
927 .call_number().record().simple_record().title();
928 $scope.title_id = xact.circulation().target_copy()
929 .call_number().record().id();
936 .controller('BillHistoryCtrl',
937 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
938 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
940 $scope.initTab('bills', $routeParams.id);
941 billSvc.userId = $routeParams.id;
942 $scope.bill_tab = $routeParams.history_tab;
945 // link page controller actions defined by sub-controllers here
948 var start = new Date(); // now - 1 year
949 start.setFullYear(start.getFullYear() - 1),
952 xact_finish : new Date()
955 $scope.date_range = function() {
956 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
957 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
958 var today = new Date().toISOString().replace(/T.*/,'');
959 if (end == today) end = 'now';
965 .controller('BillXactHistoryCtrl',
966 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
967 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
969 // generate a grid query with the current date widget values.
970 function current_grid_query() {
973 {'summary.balance_owed' : {'<>' : 0}},
974 {'summary.last_payment_ts' : {'<>' : null}}
976 xact_start : {between : $scope.date_range()},
981 $scope.gridControls = {
982 selectedItems : function(){return []},
983 activateItem : function(item) {
984 $scope.showFullDetails([item]);
986 // this sets the query on page load
987 setQuery : current_grid_query
990 $scope.actions.apply_date_range = function() {
991 // tells the grid to re-draw itself with the new query
992 $scope.gridControls.setQuery(current_grid_query());
995 // TODO; move me to service
996 function selected_payment_info() {
997 var info = {owed : 0, billed : 0, paid : 0};
998 angular.forEach($scope.gridControls.selectedItems(), function(item) {
999 info.owed += Number(item['summary.balance_owed']) * 100;
1000 info.billed += Number(item['summary.total_owed']) * 100;
1001 info.paid += Number(item['summary.total_paid']) * 100;
1009 $scope.totals.selected_billed = function() {
1010 return selected_payment_info().billed;
1012 $scope.totals.selected_paid = function() {
1013 return selected_payment_info().paid;
1016 $scope.showFullDetails = function(all) {
1018 $location.path('/circ/patron/' +
1019 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1022 // For now, only adds billing to first selected item.
1023 // Could do batches later if needed
1024 $scope.addBilling = function(all) {
1026 egBilling.showBillDialog({
1027 xact : egCore.idl.flatToNestedHash(all[0]),
1028 patron : $scope.patron()
1029 }).then(function() {
1030 $scope.gridControls.refresh();
1031 patronSvc.fetchUserStats();
1036 $scope.printBills = function(selected) { // FIXME: refactor me
1037 if (!selected.length) return;
1038 // bills print receipt assumes nested hashes, but our grid
1039 // stores flattener data. Fetch the selected xacts as
1040 // fleshed pcrud objects and hashify.
1041 // (Consider an alternate approach..)
1042 var ids = selected.map(function(t){ return t.id });
1044 egCore.pcrud.search('mbt',
1046 {flesh : 5, flesh_fields : {
1047 'mbt' : ['summary', 'circulation'],
1048 'circ' : ['target_copy'],
1049 'acp' : ['call_number'],
1051 'bre' : ['simple_record']
1054 {authoritative : true}
1057 var cusr = patronSvc.current;
1058 egCore.print.print({
1059 context : 'receipt',
1060 template : 'bills_historical',
1062 transactions : xacts,
1063 current_location : egCore.idl.toHash(
1064 egCore.org.get(egCore.auth.user().ws_ou())),
1066 prefix : cusr.prefix(),
1067 first_given_name : cusr.first_given_name(),
1068 second_given_name : cusr.second_given_name(),
1069 family_name : cusr.family_name(),
1070 suffix : cusr.suffix(),
1071 card : { barcode : cusr.card().barcode() },
1072 expire_date : cusr.expire_date(),
1073 alias : cusr.alias(),
1074 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/).length),
1075 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1083 billing_total : xact.billing_total(),
1084 billings : xact.billings(),
1085 grocery : xact.grocery(),
1087 payment_total : xact.payment_total(),
1088 payments : xact.payments(),
1089 summary : egCore.idl.toHash(xact.summary()),
1090 unrecovered : xact.unrecovered(),
1091 xact_finish : xact.xact_finish(),
1092 xact_start : xact.xact_start(),
1094 if (xact.circulation()) {
1095 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1096 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1098 xacts.push(newXact);
1104 .controller('BillPaymentHistoryCtrl',
1105 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1106 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1108 // generate a grid query with the current date widget values.
1109 function current_grid_query() {
1111 'payment_ts' : {between : $scope.date_range()},
1112 'xact.usr' : billSvc.userId
1116 $scope.gridControls = {
1117 selectedItems : function(){return []},
1118 activateItem : function(item) {
1119 $scope.showFullDetails([item]);
1121 setSort : function() {
1122 return [{'payment_ts' : 'DESC'}, 'id'];
1124 setQuery : current_grid_query
1127 $scope.actions.apply_date_range = function() {
1128 // tells the grid to re-draw itself with the new query
1129 $scope.gridControls.setQuery(current_grid_query());
1132 $scope.showFullDetails = function(all) {
1134 $location.path('/circ/patron/' +
1135 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1138 $scope.totals.selected_paid = function() {
1140 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1141 paid += Number(payment.amount) * 100;