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);
80 // reload patron data if credit balance has changed:
81 if(type === 'credit_payment' || patron_credit){ patronSvc.refreshPrimary(); }
87 service.fetchBills = function(xact_id) {
89 return egCore.pcrud.search('mb',
90 {xact : xact_id}, null,
91 {authoritative : true}
93 function() {return bills},
95 function(bill) {bills.push(bill); return bill}
99 service.fetchStatement = function(xact_id) {
100 return egCore.net.request(
102 'open-ils.circ.money.statement.retrieve',
103 egCore.auth.token(), xact_id
104 ).then(function(resp) {
105 if (evt = egCore.evt.parse(resp)) return alert(evt);
110 // TODO: no longer needed?
111 service.fetchPayments = function(xact_id) {
112 return egCore.net.request(
114 'open-ils.circ.money.payment.retrieve.all.authoritative',
115 egCore.auth.token(), xact_id
119 service.voidBills = function(bill_ids) {
120 return egCore.net.requestWithParamList(
122 'open-ils.circ.money.billing.void',
123 [egCore.auth.token()].concat(bill_ids)
124 ).then(function(resp) {
125 if (evt = egCore.evt.parse(resp)) return alert(evt);
130 service.adjustBillsToZero = function(bill_ids) {
131 return egCore.net.request(
133 'open-ils.circ.money.billable_xact.adjust_to_zero',
136 ).then(function(resp) {
137 if (evt = egCore.evt.parse(resp)) return alert(evt);
142 service.updateBillNotes = function(note, ids) {
143 return egCore.net.requestWithParamList(
145 'open-ils.circ.money.billing.note.edit',
146 [egCore.auth.token(), note].concat(ids)
147 ).then(function(resp) {
148 if (evt = egCore.evt.parse(resp)) return alert(evt);
153 service.updatePaymentNotes = function(note, ids) {
154 return egCore.net.requestWithParamList(
156 'open-ils.circ.money.payment.note.edit',
157 [egCore.auth.token(), note].concat(ids)
158 ).then(function(resp) {
159 if (evt = egCore.evt.parse(resp)) return alert(evt);
171 .controller('PatronBillsCtrl',
172 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
173 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
174 'egBilling','$uibModal',
175 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
176 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
177 egBilling , $uibModal) {
179 $scope.initTab('bills', $routeParams.id);
180 billSvc.userId = $routeParams.id;
182 // set up some defaults
183 $scope.check_number = null;
184 $scope.payment_amount = null;
185 $scope.session_voided = 0;
186 $scope.payment_type = 'cash_payment';
187 $scope.focus_payment = true;
188 $scope.annotate_payment = false;
189 $scope.receipt_count = 1;
190 $scope.receipt_on_pay = { isChecked: false };
191 $scope.convert_to_credit = {isChecked: false};
192 $scope.warn_amount = 1000;
193 $scope.max_amount = 100000;
194 $scope.amount_verified = false;
195 $scope.disable_auto_print = false;
197 // check receipt_on_pay setting default persisted
198 egCore.hatch.getItem('circ.bills.receiptonpay')
199 .then(function(rcptOnPay){
200 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
203 // pre-define list-returning funcs in case we access them
204 // before the grid instantiates
205 $scope.gridControls = {
206 focusRowSelector : false,
207 selectedItems : function(){return []},
208 allItems : function(){return []},
209 itemRetrieved : function(item) {
210 item.payment_pending = 0;
212 activateItem : function(item) {
213 $scope.showFullDetails([item]);
215 setQuery : function() {
217 usr : billSvc.userId,
219 'summary.balance_owed' : {'<>' : 0}
222 setSort : function() {
223 return ['xact_start'];
227 // Apply coloring to rows based on fines stop reason
228 $scope.colorizeBillsList = {
229 apply: function(item) {
230 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
231 if (item['circulation.stop_fines'] == 'LOST') {
233 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
234 return 'longoverdue-row';
236 return 'overdue-row';
242 // Status Icon Column definition
243 $scope.statusIconColumn = {
245 template: function(item) {
247 if (item['circulation.due_date'] && !item['circulation.checkin_time']) {
248 if (item['circulation.stop_fines'] == "LOST") {
249 icon = 'glyphicon-question-sign';
250 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
251 icon = 'glyphicon-exclamation-sign';
253 icon = 'glyphicon-time';
256 return "<i class='glyphicon " + icon + "'></i>"
260 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
262 // given a payment amount, determines how much of that is applied
263 // to selected transactions and how much is left over (change).
264 function pending_payment_info() {
265 var amt = $scope.payment_amount || 0;
266 if (amt >= $scope.owed_selected()) {
268 payment : $scope.owed_selected(),
269 change : amt - $scope.owed_selected()
272 return {payment : amt, change : 0};
275 // calculates amount owed, billed, and paid for selected items
276 // TODO: move me to service
277 function selected_payment_info() {
278 var info = {owed : 0, billed : 0, paid : 0};
279 angular.forEach($scope.gridControls.selectedItems(), function(item) {
280 info.owed += Number(item['summary.balance_owed']) * 100;
281 info.billed += Number(item['summary.total_owed']) * 100;
282 info.paid += Number(item['summary.total_paid']) * 100;
290 $scope.pending_payment = function() {
291 return pending_payment_info().payment;
293 $scope.pending_change = function() {
294 return pending_payment_info().change;
296 $scope.owed_selected = function() {
297 return selected_payment_info().owed;
299 $scope.billed_selected = function() {
300 return selected_payment_info().billed;
302 $scope.paid_selected = function() {
303 return selected_payment_info().paid;
305 $scope.refunds_available = function() {
307 angular.forEach($scope.gridControls.allItems(), function(item) {
308 if (item['summary.balance_owed'] < 0)
309 amount += item['summary.balance_owed'] * 100;
311 return -(amount / 100);
313 $scope.invalid_check_number = function() {
314 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
317 // update the item.payment_pending value each time the user
318 // selects different transactions to pay against.
320 function() {return $scope.gridControls.selectedItems()},
321 function() {updatePendingColumn()},
325 // update the item.payment_pending for each (selected)
326 // transaction any time the user-entered payment amount is modified
327 $scope.$watch('payment_amount', updatePendingColumn);
329 // updates the value of the payment_pending column in the grid.
330 // This has to be managed manually since the display value in the grid
331 // is derived from the value on the stored item and not the contents
332 // of our local scope variables.
333 function updatePendingColumn() {
334 // reset all to zero..
335 angular.forEach($scope.gridControls.allItems(),
336 function(item) {item.payment_pending = 0});
338 var payment_amount = $scope.pending_payment();
340 var selected = $scope.gridControls.selectedItems();
341 for (var i = 0; i < selected.length; i++) { // for/break
342 var item = selected[i];
343 var owed = Number(item['summary.balance_owed']);
345 if (payment_amount > owed) {
346 // pending payment exceeds balance of current item.
347 // pay the entire item.
348 item.payment_pending = owed;
349 payment_amount -= owed;
352 // balance owed on the current item matches or exceeds
353 // the pending payment. Apply the full remainder of
354 // the payment to this item.. and we're done.
355 item.payment_pending = payment_amount;
361 // builds payment arrays ([xact_id, ammount]) for all transactions
362 // which have a pending payment amount.
363 function generatePayments() {
365 angular.forEach($scope.gridControls.selectedItems(), function(item) {
366 if (item.payment_pending == 0) return;
367 payments.push([item.id, item.payment_pending]);
372 function refreshDisplay() {
373 patronSvc.fetchUserStats();
374 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
375 $scope.payment_amount = null;
376 $scope.gridControls.refresh();
379 // generates payments, collects user note if needed, and sends payment
381 function sendPayment(note, cc_args) {
382 $scope.applyingPayment = true;
383 var make_payments = generatePayments();
384 var patron_credit = $scope.convert_to_credit.isChecked ?
385 $scope.pending_change() : 0;
386 billSvc.applyPayment($scope.payment_type,
387 make_payments, note, $scope.check_number, cc_args, patron_credit)
389 function(payment_ids) {
391 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
393 $scope.payment_type, payment_ids, make_payments, note);
399 console.error('Payment was rejected: ' + msg);
402 .finally(function() { $scope.applyingPayment = false; })
405 $scope.onReceiptOnPayChanged = function(){
406 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
409 function printReceipt(type, payment_ids, payments_made, note) {
410 var payment_blobs = [];
411 var cusr = patronSvc.current;
413 angular.forEach(payments_made, function(payment) {
414 var xact_id = payment[0];
416 // find the original transaction in the grid..
417 var xact = $scope.gridControls.allItems().filter(
418 function(item) {return item.id == xact_id})[0];
421 xact : egCore.idl.flatToNestedHash(xact),
426 console.log(js2JSON(payment_blobs[0]));
428 // page data not yet refreshed, capture data from current scope
432 previous_balance : Number($scope.summary.balance_owed()),
433 payment_total : Number($scope.payment_amount),
434 payment_applied : $scope.pending_payment(),
435 amount_voided : Number($scope.session_voided),
436 change_given : $scope.pending_change(),
437 payments : payment_blobs,
438 current_location : egCore.idl.toHash(
439 egCore.org.get(egCore.auth.user().ws_ou()))
442 // Not a good idea to use patron_stats.fines for this; it's out of date
443 print_data.patron = {
444 prefix : cusr.prefix(),
445 first_given_name : cusr.first_given_name(),
446 second_given_name : cusr.second_given_name(),
447 family_name : cusr.family_name(),
448 suffix : cusr.suffix(),
449 card : { barcode : cusr.card().barcode() },
450 expire_date : cusr.expire_date(),
451 alias : cusr.alias(),
452 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/)),
453 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
456 print_data.new_balance = (
457 print_data.previous_balance * 100 -
458 print_data.payment_applied * 100) / 100;
460 for (var i = 0; i < $scope.receipt_count; i++) {
463 template : 'bill_payment',
469 $scope.showHistory = function() {
470 $location.path('/circ/patron/' +
471 patronSvc.current.id() + '/bill_history/transactions');
474 // For now, only adds billing to first selected item.
475 // Could do batches later if needed
476 $scope.addBilling = function(all) {
478 egBilling.showBillDialog({
479 xact : egCore.idl.flatToNestedHash(all[0]),
480 patron : $scope.patron()
481 }).then(refreshDisplay);
485 $scope.showBillDialog = function($event) {
486 egBilling.showBillDialog({
487 patron : $scope.patron()
488 }).then(refreshDisplay);
491 // Select refunds adds all refunds to the existing selection.
492 // It does not /only/ select refunds
493 $scope.selectRefunds = function() {
494 var ids = $scope.gridControls.selectedItems().map(
495 function(i) { return i.id });
496 angular.forEach($scope.gridControls.allItems(), function(item) {
497 if (Number(item['summary.balance_owed']) < 0)
500 $scope.gridControls.selectItems(ids);
504 // determine on initial page load when all of the grid rows should
506 var selectOnLoad = true;
507 billSvc.fetchBillSettings().then(function(s) {
508 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
509 $scope.focus_payment = false; // de-focus the payment box
510 $scope.gridControls.focusRowSelector = true;
511 selectOnLoad = false;
512 // if somehow the grid finishes rendering before our settings
513 // arrive, manually de-select everything.
514 $scope.gridControls.selectItems([]);
516 if (s['ui.circ.billing.amount_warn']) {
517 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
519 if (s['ui.circ.billing.amount_limit']) {
520 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
522 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
523 $scope.disable_auto_print = Boolean(
524 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
527 if (s['circ.disable_patron_credit']) {
528 $scope.disablePatronCredit = true;
532 $scope.gridControls.allItemsRetrieved = function() {
534 selectOnLoad = false; // only for initial controller load.
535 // select all non-refund items
536 $scope.gridControls.selectItems(
537 $scope.gridControls.allItems()
538 .filter(function(i) {return i['summary.balance_owed'] > 0})
539 .map(function(i){return i.id})
546 $scope.printBills = function(selected) {
547 if (!selected.length) return;
548 // bills print receipt assumes nested hashes, but our grid
549 // stores flattener data. Fetch the selected xacts as
550 // fleshed pcrud objects and hashify.
551 // (Consider an alternate approach..)
552 var ids = selected.map(function(t){ return t.id });
554 egCore.pcrud.search('mbt',
556 {flesh : 5, flesh_fields : {
557 'mbt' : ['summary', 'circulation'],
558 'circ' : ['target_copy'],
559 'acp' : ['call_number'],
561 'bre' : ['simple_record']
564 {authoritative : true}
567 var cusr = patronSvc.current;
570 template : 'bills_current',
572 transactions : xacts,
573 current_location : egCore.idl.toHash(
574 egCore.org.get(egCore.auth.user().ws_ou())),
576 prefix : cusr.prefix(),
577 first_given_name : cusr.first_given_name(),
578 second_given_name : cusr.second_given_name(),
579 family_name : cusr.family_name(),
580 suffix : cusr.suffix(),
581 card : { barcode : cusr.card().barcode() },
582 expire_date : cusr.expire_date(),
583 alias : cusr.alias(),
584 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
585 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
593 billing_total : xact.billing_total(),
594 billings : xact.billings(),
595 grocery : xact.grocery(),
597 payment_total : xact.payment_total(),
598 payments : xact.payments(),
599 summary : egCore.idl.toHash(xact.summary()),
600 unrecovered : xact.unrecovered(),
601 xact_finish : xact.xact_finish(),
602 xact_start : xact.xact_start(),
604 if (xact.circulation()) {
605 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
606 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
613 $scope.applyPayment = function() {
615 if ($scope.payment_amount > $scope.max_amount ) {
617 egCore.strings.PAYMENT_OVER_MAX,
618 { max_amount : ''+$scope.max_amount,
620 $scope.payment_amount = 0;
627 verify_payment_amount().then(
628 function() { // amount confirmed
629 add_payment_note().then(function(pay_note) {
630 add_cc_args().then(function(cc_args) {
631 var note_text = pay_note ? pay_note.value || '' : null;
632 sendPayment(note_text, cc_args);
636 function() { // amount rejected
637 console.warn('payment amount rejected');
638 $scope.payment_amount = 0;
643 function verify_payment_amount() {
644 if ($scope.payment_amount < $scope.warn_amount)
647 return egConfirmDialog.open(
648 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
649 egCore.strings.PAYMENT_WARN_AMOUNT,
650 {payment_amount : ''+$scope.payment_amount}
654 function add_payment_note() {
655 if (!$scope.annotate_payment) return $q.when();
656 return egPromptDialog.open(
657 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
660 function add_cc_args() {
661 if ($scope.payment_type != 'credit_card_payment')
664 return $uibModal.open({
665 templateUrl : './circ/patron/t_cc_payment_dialog',
668 '$scope','$uibModalInstance',
669 function($scope , $uibModalInstance) {
673 where_process : '1', // internal=1 ; external=0
674 type : 'VISA', // external only
675 billing_first : patronSvc.current.first_given_name(),
676 billing_last : patronSvc.current.family_name()
680 var addr = patronSvc.current.billing_address() ||
681 patronSvc.current.mailing_address();
683 var cc = $scope.context.cc;
684 cc.billing_address = addr.street1() +
685 (addr.street2() ? ' ' + addr.street2() : '');
686 cc.billing_city = addr.city();
687 cc.billing_state = addr.state();
688 cc.billing_zip = addr.post_code();
691 $scope.ok = function() {
692 // CC payment form is not a <form>,
693 // so apply validation manually.
694 if ( $scope.context.cc.where_process == 0 &&
695 !$scope.context.cc.approval_code)
698 $uibModalInstance.close($scope.context.cc);
701 $scope.cancel = function() {
702 $uibModalInstance.dismiss();
709 $scope.voidAllBillings = function(items) {
713 angular.forEach(items, function(item) {
715 billSvc.fetchBills(item.id).then(function(bills) {
716 angular.forEach(bills, function(b) {
717 if (b.voided() != 't') {
718 cents += b.amount() * 100;
719 bill_ids.push(b.id())
723 if (bill_ids.length == 0) {
732 $q.all(promises).then(function(){
733 egCore.audio.play('warning.circ.void_billings_confirmation');
734 egConfirmDialog.open(
735 egCore.strings.CONFIRM_VOID_BILLINGS, '',
736 { billIds : ''+bill_ids,
737 amount : ''+(cents/100),
739 billSvc.voidBills(bill_ids).then(function() {
740 $scope.session_voided =
741 ($scope.session_voided * 100 + cents) / 100;
750 $scope.adjustToZero = function(items) {
751 if (items.length == 0) return;
753 var ids = items.map(function(item) {return item.id});
755 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
756 egConfirmDialog.open(
757 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
760 billSvc.adjustBillsToZero(ids).then(function() {
769 // note this is functionally equivalent to selecting a neg. transaction
770 // then clicking Apply Payment -- this just adds a speed bump (ditto
772 $scope.refundXact = function(all) {
773 var items = all.filter(function(item) {
774 return item['summary.balance_owed'] < 0
777 if (items.length == 0) return;
779 var ids = items.map(function(item) {return item.id});
781 egCore.audio.play('warning.circ.refund_confirmation');
782 egConfirmDialog.open(
783 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
786 // reset the received payment amount. this ensures
787 // we're not mingling payments with refunds.
788 $scope.payment_amount = 0;
794 // direct the user to the transaction details page
795 $scope.showFullDetails = function(all) {
797 $location.path('/circ/patron/' +
798 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
801 $scope.activateBill = function(xact) {
802 $scope.showFullDetails([xact]);
808 * Displays details of a single transaction
810 .controller('XactDetailsCtrl',
811 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
812 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
814 $scope.initTab('bills', $routeParams.id);
815 var xact_id = $routeParams.xact_id;
816 $scope.xact_tab = $routeParams.xact_tab;
818 var xactGrid = $scope.xactGridControls = {
819 setQuery : function() { return {xact : xact_id} },
820 setSort : function() { return ['billing_ts'] }
823 var paymentGrid = $scope.paymentGridControls = {
824 setQuery : function() { return {xact : xact_id} },
825 setSort : function() { return ['payment_ts'] }
829 $scope.voidBillings = function(bill_list) {
832 angular.forEach(bill_list, function(b) {
833 if (b.voided != 't') {
834 cents += b.amount * 100;
839 if (bill_ids.length == 0) {
844 egCore.audio.play('warning.circ.void_billings_confirmation');
845 egConfirmDialog.open(
846 egCore.strings.CONFIRM_VOID_BILLINGS, '',
847 { billIds : ''+bill_ids,
848 amount : ''+(cents/100),
850 billSvc.voidBills(bill_ids).then(function() {
851 // TODO? $scope.session_voided = ...
853 // refresh bills and summary data
854 // note: no need to update payments
855 patronSvc.fetchUserStats();
857 egBilling.fetchXact(xact_id).then(function(xact) {
868 // batch-edit billing and payment notes, depending on 'type'
869 function editNotes(selected, type) {
870 var notes = selected.map(function(b){ return b.note }).join(',');
871 var ids = selected.map(function(b){ return b.id });
873 // show the note edit prompt
875 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
877 ok : function(value) {
879 var func = 'updateBillNotes';
880 if (type == 'payment') func = 'updatePaymentNotes';
882 billSvc[func](value, ids).then(function() {
883 if (type == 'payment') {
884 paymentGrid.refresh();
894 $scope.editBillNotes = function(selected) {
895 editNotes(selected, 'bill');
898 $scope.editPaymentNotes = function(selected) {
899 editNotes(selected, 'payment');
902 // -- retrieve our data
903 if ($scope.xact_tab == 'statement') {
904 //fetch combined billing statement data
905 billSvc.fetchStatement(xact_id).then(function(statement) {
906 //console.log(statement);
907 $scope.statement_data = statement;
910 $scope.total_circs = 0; // start with 0 instead of undefined
911 egBilling.fetchXact(xact_id).then(function(xact) {
914 var copyId = xact.circulation().target_copy().id();
916 egCore.pcrud.search('circbyyr',
917 {copy : copyId}, null, {atomic : true})
918 .then(function(counts) {
919 angular.forEach(counts, function(count) {
920 circ_count += Number(count.count());
922 $scope.total_circs = circ_count;
924 // set the title. only needs to be done on initial page load
925 if (xact.circulation()) {
926 if (xact.circulation().target_copy().call_number().id() == -1) {
927 $scope.title = xact.circulation().target_copy().dummy_title();
929 // TODO: shared bib service?
930 $scope.title = xact.circulation().target_copy()
931 .call_number().record().simple_record().title();
932 $scope.title_id = xact.circulation().target_copy()
933 .call_number().record().id();
940 .controller('BillHistoryCtrl',
941 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
942 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
944 $scope.initTab('bills', $routeParams.id);
945 billSvc.userId = $routeParams.id;
946 $scope.bill_tab = $routeParams.history_tab;
949 // link page controller actions defined by sub-controllers here
952 var start = new Date(); // now - 1 year
953 start.setFullYear(start.getFullYear() - 1),
956 xact_finish : new Date()
959 $scope.date_range = function() {
960 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
961 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
962 var today = new Date().toISOString().replace(/T.*/,'');
963 if (end == today) end = 'now';
969 .controller('BillXactHistoryCtrl',
970 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
971 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
973 // generate a grid query with the current date widget values.
974 function current_grid_query() {
977 {'summary.balance_owed' : {'<>' : 0}},
978 {'summary.last_payment_ts' : {'<>' : null}}
980 xact_start : {between : $scope.date_range()},
985 $scope.gridControls = {
986 selectedItems : function(){return []},
987 activateItem : function(item) {
988 $scope.showFullDetails([item]);
990 // this sets the query on page load
991 setQuery : current_grid_query
994 $scope.actions.apply_date_range = function() {
995 // tells the grid to re-draw itself with the new query
996 $scope.gridControls.setQuery(current_grid_query());
999 // TODO; move me to service
1000 function selected_payment_info() {
1001 var info = {owed : 0, billed : 0, paid : 0};
1002 angular.forEach($scope.gridControls.selectedItems(), function(item) {
1003 info.owed += Number(item['summary.balance_owed']) * 100;
1004 info.billed += Number(item['summary.total_owed']) * 100;
1005 info.paid += Number(item['summary.total_paid']) * 100;
1013 $scope.totals.selected_billed = function() {
1014 return selected_payment_info().billed;
1016 $scope.totals.selected_paid = function() {
1017 return selected_payment_info().paid;
1020 $scope.showFullDetails = function(all) {
1022 $location.path('/circ/patron/' +
1023 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
1026 // For now, only adds billing to first selected item.
1027 // Could do batches later if needed
1028 $scope.addBilling = function(all) {
1030 egBilling.showBillDialog({
1031 xact : egCore.idl.flatToNestedHash(all[0]),
1032 patron : $scope.patron()
1033 }).then(function() {
1034 $scope.gridControls.refresh();
1035 patronSvc.fetchUserStats();
1040 $scope.printBills = function(selected) { // FIXME: refactor me
1041 if (!selected.length) return;
1042 // bills print receipt assumes nested hashes, but our grid
1043 // stores flattener data. Fetch the selected xacts as
1044 // fleshed pcrud objects and hashify.
1045 // (Consider an alternate approach..)
1046 var ids = selected.map(function(t){ return t.id });
1048 egCore.pcrud.search('mbt',
1050 {flesh : 5, flesh_fields : {
1051 'mbt' : ['summary', 'circulation'],
1052 'circ' : ['target_copy'],
1053 'acp' : ['call_number'],
1055 'bre' : ['simple_record']
1058 {authoritative : true}
1061 var cusr = patronSvc.current;
1062 egCore.print.print({
1063 context : 'receipt',
1064 template : 'bills_historical',
1066 transactions : xacts,
1067 current_location : egCore.idl.toHash(
1068 egCore.org.get(egCore.auth.user().ws_ou())),
1070 prefix : cusr.prefix(),
1071 first_given_name : cusr.first_given_name(),
1072 second_given_name : cusr.second_given_name(),
1073 family_name : cusr.family_name(),
1074 suffix : cusr.suffix(),
1075 card : { barcode : cusr.card().barcode() },
1076 expire_date : cusr.expire_date(),
1077 alias : cusr.alias(),
1078 has_email : Boolean(cusr.email() && cusr.email().match(/.*@.*/)),
1079 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
1087 billing_total : xact.billing_total(),
1088 billings : xact.billings(),
1089 grocery : xact.grocery(),
1091 payment_total : xact.payment_total(),
1092 payments : xact.payments(),
1093 summary : egCore.idl.toHash(xact.summary()),
1094 unrecovered : xact.unrecovered(),
1095 xact_finish : xact.xact_finish(),
1096 xact_start : xact.xact_start(),
1098 if (xact.circulation()) {
1099 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1100 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1102 xacts.push(newXact);
1108 .controller('BillPaymentHistoryCtrl',
1109 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1110 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1112 // generate a grid query with the current date widget values.
1113 function current_grid_query() {
1115 'payment_ts' : {between : $scope.date_range()},
1116 'xact.usr' : billSvc.userId
1120 $scope.gridControls = {
1121 selectedItems : function(){return []},
1122 activateItem : function(item) {
1123 $scope.showFullDetails([item]);
1125 setSort : function() {
1126 return [{'payment_ts' : 'DESC'}, 'id'];
1128 setQuery : current_grid_query
1131 $scope.actions.apply_date_range = function() {
1132 // tells the grid to re-draw itself with the new query
1133 $scope.gridControls.setQuery(current_grid_query());
1136 $scope.showFullDetails = function(all) {
1138 $location.path('/circ/patron/' +
1139 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1142 $scope.totals.selected_paid = function() {
1144 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1145 paid += Number(payment.amount) * 100;