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','ui.circ.billing.amount_warn','ui.circ.billing.amount_limit','circ.staff_client.do_not_auto_attempt_print']
17 ).then(function(s) {return service.settings = s});
20 // user billing summary
21 service.fetchSummary = function() {
22 return egCore.pcrud.retrieve(
23 'mous', service.userId, {}, {authoritative : true})
24 .then(function(summary) {return service.summary = summary})
27 service.applyPayment = function(type, payments, note, check, cc_args) {
28 return egCore.net.request(
30 'open-ils.circ.money.payment',
31 egCore.auth.token(), {
32 userid : service.userId,
40 patronSvc.current.last_xact_id()
41 ).then(function(resp) {
42 console.debug('payments: ' + js2JSON(resp));
44 if (evt = egCore.evt.parse(resp)) {
45 // Ideally, all scenarios that lead to this alert appearing
46 // will be avoided by the application logic. Leave the alert
47 // in place now to root out any that remain to be addressed.
49 return $q.reject(''+evt);
52 var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
55 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
56 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
57 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
58 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
59 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
60 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
61 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
65 'action' : 'paid_bill',
66 'patron_id' : service.userId,
67 'total_amount' : total
71 // payment API returns the update xact id so we can track it
72 // for future payments without having to refresh the user.
73 patronSvc.current.last_xact_id(resp.last_xact_id);
78 service.fetchBills = function(xact_id) {
80 return egCore.pcrud.search('mb',
81 {xact : xact_id}, null,
82 {authoritative : true}
84 function() {return bills},
86 function(bill) {bills.push(bill); return bill}
90 service.fetchStatement = function(xact_id) {
91 return egCore.net.request(
93 'open-ils.circ.money.statement.retrieve',
94 egCore.auth.token(), xact_id
95 ).then(function(resp) {
96 if (evt = egCore.evt.parse(resp)) return alert(evt);
101 // TODO: no longer needed?
102 service.fetchPayments = function(xact_id) {
103 return egCore.net.request(
105 'open-ils.circ.money.payment.retrieve.all.authoritative',
106 egCore.auth.token(), xact_id
110 service.voidBills = function(bill_ids) {
111 return egCore.net.requestWithParamList(
113 'open-ils.circ.money.billing.void',
114 [egCore.auth.token()].concat(bill_ids)
115 ).then(function(resp) {
116 if (evt = egCore.evt.parse(resp)) return alert(evt);
121 service.adjustBillsToZero = function(bill_ids) {
122 return egCore.net.request(
124 'open-ils.circ.money.billable_xact.adjust_to_zero',
127 ).then(function(resp) {
128 if (evt = egCore.evt.parse(resp)) return alert(evt);
133 service.updateBillNotes = function(note, ids) {
134 return egCore.net.requestWithParamList(
136 'open-ils.circ.money.billing.note.edit',
137 [egCore.auth.token(), note].concat(ids)
138 ).then(function(resp) {
139 if (evt = egCore.evt.parse(resp)) return alert(evt);
144 service.updatePaymentNotes = function(note, ids) {
145 return egCore.net.requestWithParamList(
147 'open-ils.circ.money.payment.note.edit',
148 [egCore.auth.token(), note].concat(ids)
149 ).then(function(resp) {
150 if (evt = egCore.evt.parse(resp)) return alert(evt);
162 .controller('PatronBillsCtrl',
163 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
164 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
165 'egBilling','$uibModal',
166 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
167 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
168 egBilling , $uibModal) {
170 $scope.initTab('bills', $routeParams.id);
171 billSvc.userId = $routeParams.id;
173 // set up some defaults
174 $scope.check_number = null;
175 $scope.payment_amount = null;
176 $scope.session_voided = 0;
177 $scope.payment_type = 'cash_payment';
178 $scope.focus_payment = true;
179 $scope.annotate_payment = false;
180 $scope.receipt_count = 1;
181 $scope.receipt_on_pay = { isChecked: false };
182 $scope.warn_amount = 1000;
183 $scope.max_amount = 100000;
184 $scope.amount_verified = false;
185 $scope.disable_auto_print = false;
187 // check receipt_on_pay setting default persisted
188 egCore.hatch.getItem('circ.bills.receiptonpay')
189 .then(function(rcptOnPay){
190 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
193 // pre-define list-returning funcs in case we access them
194 // before the grid instantiates
195 $scope.gridControls = {
196 focusRowSelector : false,
197 selectedItems : function(){return []},
198 allItems : function(){return []},
199 itemRetrieved : function(item) {
200 item.payment_pending = 0;
202 activateItem : function(item) {
203 $scope.showFullDetails([item]);
205 setQuery : function() {
207 usr : billSvc.userId,
209 'summary.balance_owed' : {'<>' : 0}
212 setSort : function() {
213 return ['xact_start'];
217 // Apply coloring to rows based on fines stop reason
218 $scope.colorizeBillsList = {
219 apply: function(item) {
220 if (!item['circulation.checkin_time']) {
221 if (item['circulation.stop_fines'] == 'LOST') {
222 return 'dark-red-row-highlight';
223 } else if (item['circulation.stop_fines'] == 'LONGOVERDUE') {
224 return 'red-row-highlight';
226 return 'orange-row-highlight';
232 // Status Icon Column definition
233 $scope.statusIconColumn = {
235 template: function(item) {
237 if (!item['circulation.checkin_time']) {
238 if (item['circulation.stop_fines'] == "LOST") {
239 icon = 'glyphicon-question-sign';
240 } else if (item['circulation.stop_fines'] == "LONGOVERDUE") {
241 icon = 'glyphicon-exclamation-sign';
243 icon = 'glyphicon-time';
246 return "<i class='glyphicon " + icon + "'></i>"
250 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
252 // given a payment amount, determines how much of that is applied
253 // to selected transactions and how much is left over (change).
254 function pending_payment_info() {
255 var amt = $scope.payment_amount || 0;
256 if (amt >= $scope.owed_selected()) {
258 payment : $scope.owed_selected(),
259 change : amt - $scope.owed_selected()
262 return {payment : amt, change : 0};
265 // calculates amount owed, billed, and paid for selected items
266 // TODO: move me to service
267 function selected_payment_info() {
268 var info = {owed : 0, billed : 0, paid : 0};
269 angular.forEach($scope.gridControls.selectedItems(), function(item) {
270 info.owed += Number(item['summary.balance_owed']) * 100;
271 info.billed += Number(item['summary.total_owed']) * 100;
272 info.paid += Number(item['summary.total_paid']) * 100;
280 $scope.pending_payment = function() {
281 return pending_payment_info().payment;
283 $scope.pending_change = function() {
284 return pending_payment_info().change;
286 $scope.owed_selected = function() {
287 return selected_payment_info().owed;
289 $scope.billed_selected = function() {
290 return selected_payment_info().billed;
292 $scope.paid_selected = function() {
293 return selected_payment_info().paid;
295 $scope.refunds_available = function() {
297 angular.forEach($scope.gridControls.allItems(), function(item) {
298 if (item['summary.balance_owed'] < 0)
299 amount += item['summary.balance_owed'] * 100;
301 return -(amount / 100);
303 $scope.invalid_check_number = function() {
304 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
307 // update the item.payment_pending value each time the user
308 // selects different transactions to pay against.
310 function() {return $scope.gridControls.selectedItems()},
311 function() {updatePendingColumn()},
315 // update the item.payment_pending for each (selected)
316 // transaction any time the user-entered payment amount is modified
317 $scope.$watch('payment_amount', updatePendingColumn);
319 // updates the value of the payment_pending column in the grid.
320 // This has to be managed manually since the display value in the grid
321 // is derived from the value on the stored item and not the contents
322 // of our local scope variables.
323 function updatePendingColumn() {
324 // reset all to zero..
325 angular.forEach($scope.gridControls.allItems(),
326 function(item) {item.payment_pending = 0});
328 var payment_amount = $scope.pending_payment();
330 var selected = $scope.gridControls.selectedItems();
331 for (var i = 0; i < selected.length; i++) { // for/break
332 var item = selected[i];
333 var owed = Number(item['summary.balance_owed']);
335 if (payment_amount > owed) {
336 // pending payment exceeds balance of current item.
337 // pay the entire item.
338 item.payment_pending = owed;
339 payment_amount -= owed;
342 // balance owed on the current item matches or exceeds
343 // the pending payment. Apply the full remainder of
344 // the payment to this item.. and we're done.
345 item.payment_pending = payment_amount;
351 // builds payment arrays ([xact_id, ammount]) for all transactions
352 // which have a pending payment amount.
353 function generatePayments() {
355 angular.forEach($scope.gridControls.selectedItems(), function(item) {
356 if (item.payment_pending == 0) return;
357 payments.push([item.id, item.payment_pending]);
362 function refreshDisplay() {
363 patronSvc.fetchUserStats();
364 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
365 $scope.payment_amount = null;
366 $scope.gridControls.refresh();
369 // generates payments, collects user note if needed, and sends payment
371 function sendPayment(note, cc_args) {
372 $scope.applyingPayment = true;
373 var make_payments = generatePayments();
374 billSvc.applyPayment($scope.payment_type,
375 make_payments, note, $scope.check_number, cc_args)
377 function(payment_ids) {
379 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
381 $scope.payment_type, payment_ids, make_payments, note);
387 console.error('Payment was rejected: ' + msg);
390 .finally(function() { $scope.applyingPayment = false; })
393 $scope.onReceiptOnPayChanged = function(){
394 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
397 function printReceipt(type, payment_ids, payments_made, note) {
398 var payment_blobs = [];
399 var cusr = patronSvc.current;
401 angular.forEach(payments_made, function(payment) {
402 var xact_id = payment[0];
404 // find the original transaction in the grid..
405 var xact = $scope.gridControls.allItems().filter(
406 function(item) {return item.id == xact_id})[0];
409 xact : egCore.idl.flatToNestedHash(xact),
414 console.log(js2JSON(payment_blobs[0]));
416 // page data not yet refreshed, capture data from current scope
420 previous_balance : Number($scope.summary.balance_owed()),
421 payment_total : Number($scope.payment_amount),
422 payment_applied : $scope.pending_payment(),
423 amount_voided : Number($scope.session_voided),
424 change_given : $scope.pending_change(),
425 payments : payment_blobs,
426 current_location : egCore.idl.toHash(
427 egCore.org.get(egCore.auth.user().ws_ou()))
430 // Not a good idea to use patron_stats.fines for this; it's out of date
431 print_data.patron = {
432 prefix : cusr.prefix(),
433 first_given_name : cusr.first_given_name(),
434 second_given_name : cusr.second_given_name(),
435 family_name : cusr.family_name(),
436 suffix : cusr.suffix(),
437 card : { barcode : cusr.card().barcode() },
438 expire_date : cusr.expire_date(),
439 alias : cusr.alias(),
440 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/).length),
441 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
444 print_data.new_balance = (
445 print_data.previous_balance * 100 -
446 print_data.payment_applied * 100) / 100;
448 for (var i = 0; i < $scope.receipt_count; i++) {
451 template : 'bill_payment',
457 $scope.showHistory = function() {
458 $location.path('/circ/patron/' +
459 patronSvc.current.id() + '/bill_history/transactions');
462 // For now, only adds billing to first selected item.
463 // Could do batches later if needed
464 $scope.addBilling = function(all) {
466 egBilling.showBillDialog({
467 xact : egCore.idl.flatToNestedHash(all[0]),
468 patron : $scope.patron()
469 }).then(refreshDisplay);
473 $scope.showBillDialog = function($event) {
474 egBilling.showBillDialog({
475 patron : $scope.patron()
476 }).then(refreshDisplay);
479 // Select refunds adds all refunds to the existing selection.
480 // It does not /only/ select refunds
481 $scope.selectRefunds = function() {
482 var ids = $scope.gridControls.selectedItems().map(
483 function(i) { return i.id });
484 angular.forEach($scope.gridControls.allItems(), function(item) {
485 if (Number(item['summary.balance_owed']) < 0)
488 $scope.gridControls.selectItems(ids);
492 // determine on initial page load when all of the grid rows should
494 var selectOnLoad = true;
495 billSvc.fetchBillSettings().then(function(s) {
496 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
497 $scope.focus_payment = false; // de-focus the payment box
498 $scope.gridControls.focusRowSelector = true;
499 selectOnLoad = false;
500 // if somehow the grid finishes rendering before our settings
501 // arrive, manually de-select everything.
502 $scope.gridControls.selectItems([]);
504 if (s['ui.circ.billing.amount_warn']) {
505 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
507 if (s['ui.circ.billing.amount_limit']) {
508 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
510 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
511 $scope.disable_auto_print = Boolean(
512 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
517 $scope.gridControls.allItemsRetrieved = function() {
519 selectOnLoad = false; // only for initial controller load.
520 // select all non-refund items
521 $scope.gridControls.selectItems(
522 $scope.gridControls.allItems()
523 .filter(function(i) {return i['summary.balance_owed'] > 0})
524 .map(function(i){return i.id})
531 $scope.printBills = function(selected) {
532 if (!selected.length) return;
533 // bills print receipt assumes nested hashes, but our grid
534 // stores flattener data. Fetch the selected xacts as
535 // fleshed pcrud objects and hashify.
536 // (Consider an alternate approach..)
537 var ids = selected.map(function(t){ return t.id });
539 egCore.pcrud.search('mbt',
541 {flesh : 5, flesh_fields : {
542 'mbt' : ['summary', 'circulation'],
543 'circ' : ['target_copy'],
544 'acp' : ['call_number'],
546 'bre' : ['simple_record']
549 {authoritative : true}
554 template : 'bills_current',
556 transactions : xacts,
557 current_location : egCore.idl.toHash(
558 egCore.org.get(egCore.auth.user().ws_ou()))
565 billing_total : xact.billing_total(),
566 billings : xact.billings(),
567 grocery : xact.grocery(),
569 payment_total : xact.payment_total(),
570 payments : xact.payments(),
571 summary : egCore.idl.toHash(xact.summary()),
572 unrecovered : xact.unrecovered(),
573 xact_finish : xact.xact_finish(),
574 xact_start : xact.xact_start(),
576 if (xact.circulation()) {
577 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
578 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
585 $scope.applyPayment = function() {
587 if ($scope.payment_amount > $scope.max_amount ) {
589 egCore.strings.PAYMENT_OVER_MAX,
590 { max_amount : ''+$scope.max_amount,
592 $scope.payment_amount = 0;
599 verify_payment_amount().then(
600 function() { // amount confirmed
601 add_payment_note().then(function(pay_note) {
602 add_cc_args().then(function(cc_args) {
603 var note_text = pay_note ? pay_note.value || '' : null;
604 sendPayment(note_text, cc_args);
608 function() { // amount rejected
609 console.warn('payment amount rejected');
610 $scope.payment_amount = 0;
615 function verify_payment_amount() {
616 if ($scope.payment_amount < $scope.warn_amount)
619 return egConfirmDialog.open(
620 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
621 egCore.strings.PAYMENT_WARN_AMOUNT,
622 {payment_amount : ''+$scope.payment_amount}
626 function add_payment_note() {
627 if (!$scope.annotate_payment) return $q.when();
628 return egPromptDialog.open(
629 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
632 function add_cc_args() {
633 if ($scope.payment_type != 'credit_card_payment')
636 return $uibModal.open({
637 templateUrl : './circ/patron/t_cc_payment_dialog',
640 '$scope','$uibModalInstance',
641 function($scope , $uibModalInstance) {
645 where_process : '1', // internal=1 ; external=0
646 type : 'VISA', // external only
647 billing_first : patronSvc.current.first_given_name(),
648 billing_last : patronSvc.current.family_name()
652 var addr = patronSvc.current.billing_address() ||
653 patronSvc.current.mailing_address();
655 var cc = $scope.context.cc;
656 cc.billing_address = addr.street1() +
657 (addr.street2() ? ' ' + addr.street2() : '');
658 cc.billing_city = addr.city();
659 cc.billing_state = addr.state();
660 cc.billing_zip = addr.post_code();
663 $scope.ok = function() {
664 // CC payment form is not a <form>,
665 // so apply validation manually.
666 if ( $scope.context.cc.where_process == 0 &&
667 !$scope.context.cc.approval_code)
670 $uibModalInstance.close($scope.context.cc);
673 $scope.cancel = function() {
674 $uibModalInstance.dismiss();
681 $scope.voidAllBillings = function(items) {
685 angular.forEach(items, function(item) {
687 billSvc.fetchBills(item.id).then(function(bills) {
688 angular.forEach(bills, function(b) {
689 if (b.voided() != 't') {
690 cents += b.amount() * 100;
691 bill_ids.push(b.id())
695 if (bill_ids.length == 0) {
704 $q.all(promises).then(function(){
705 egCore.audio.play('warning.circ.void_billings_confirmation');
706 egConfirmDialog.open(
707 egCore.strings.CONFIRM_VOID_BILLINGS, '',
708 { billIds : ''+bill_ids,
709 amount : ''+(cents/100),
711 billSvc.voidBills(bill_ids).then(function() {
712 $scope.session_voided =
713 ($scope.session_voided * 100 + cents) / 100;
722 $scope.adjustToZero = function(items) {
723 if (items.length == 0) return;
725 var ids = items.map(function(item) {return item.id});
727 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
728 egConfirmDialog.open(
729 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
732 billSvc.adjustBillsToZero(ids).then(function() {
741 // note this is functionally equivalent to selecting a neg. transaction
742 // then clicking Apply Payment -- this just adds a speed bump (ditto
744 $scope.refundXact = function(all) {
745 var items = all.filter(function(item) {
746 return item['summary.balance_owed'] < 0
749 if (items.length == 0) return;
751 var ids = items.map(function(item) {return item.id});
753 egCore.audio.play('warning.circ.refund_confirmation');
754 egConfirmDialog.open(
755 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
758 // reset the received payment amount. this ensures
759 // we're not mingling payments with refunds.
760 $scope.payment_amount = 0;
766 // direct the user to the transaction details page
767 $scope.showFullDetails = function(all) {
769 $location.path('/circ/patron/' +
770 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
773 $scope.activateBill = function(xact) {
774 $scope.showFullDetails([xact]);
780 * Displays details of a single transaction
782 .controller('XactDetailsCtrl',
783 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
784 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
786 $scope.initTab('bills', $routeParams.id);
787 var xact_id = $routeParams.xact_id;
788 $scope.xact_tab = $routeParams.xact_tab;
790 var xactGrid = $scope.xactGridControls = {
791 setQuery : function() { return {xact : xact_id} },
792 setSort : function() { return ['billing_ts'] }
795 var paymentGrid = $scope.paymentGridControls = {
796 setQuery : function() { return {xact : xact_id} },
797 setSort : function() { return ['payment_ts'] }
801 $scope.voidBillings = function(bill_list) {
804 angular.forEach(bill_list, function(b) {
805 if (b.voided != 't') {
806 cents += b.amount * 100;
811 if (bill_ids.length == 0) {
816 egCore.audio.play('warning.circ.void_billings_confirmation');
817 egConfirmDialog.open(
818 egCore.strings.CONFIRM_VOID_BILLINGS, '',
819 { billIds : ''+bill_ids,
820 amount : ''+(cents/100),
822 billSvc.voidBills(bill_ids).then(function() {
823 // TODO? $scope.session_voided = ...
825 // refresh bills and summary data
826 // note: no need to update payments
827 patronSvc.fetchUserStats();
829 egBilling.fetchXact(xact_id).then(function(xact) {
840 // batch-edit billing and payment notes, depending on 'type'
841 function editNotes(selected, type) {
842 var notes = selected.map(function(b){ return b.note }).join(',');
843 var ids = selected.map(function(b){ return b.id });
845 // show the note edit prompt
847 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
849 ok : function(value) {
851 var func = 'updateBillNotes';
852 if (type == 'payment') func = 'updatePaymentNotes';
854 billSvc[func](value, ids).then(function() {
855 if (type == 'payment') {
856 paymentGrid.refresh();
866 $scope.editBillNotes = function(selected) {
867 editNotes(selected, 'bill');
870 $scope.editPaymentNotes = function(selected) {
871 editNotes(selected, 'payment');
874 // -- retrieve our data
875 if ($scope.xact_tab == 'statement') {
876 //fetch combined billing statement data
877 billSvc.fetchStatement(xact_id).then(function(statement) {
878 //console.log(statement);
879 $scope.statement_data = statement;
882 $scope.total_circs = 0; // start with 0 instead of undefined
883 egBilling.fetchXact(xact_id).then(function(xact) {
886 var copyId = xact.circulation().target_copy().id();
888 egCore.pcrud.search('circbyyr',
889 {copy : copyId}, null, {atomic : true})
890 .then(function(counts) {
891 angular.forEach(counts, function(count) {
892 circ_count += Number(count.count());
894 $scope.total_circs = circ_count;
896 // set the title. only needs to be done on initial page load
897 if (xact.circulation()) {
898 if (xact.circulation().target_copy().call_number().id() == -1) {
899 $scope.title = xact.circulation().target_copy().dummy_title();
901 // TODO: shared bib service?
902 $scope.title = xact.circulation().target_copy()
903 .call_number().record().simple_record().title();
904 $scope.title_id = xact.circulation().target_copy()
905 .call_number().record().id();
912 .controller('BillHistoryCtrl',
913 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
914 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
916 $scope.initTab('bills', $routeParams.id);
917 billSvc.userId = $routeParams.id;
918 $scope.bill_tab = $routeParams.history_tab;
921 // link page controller actions defined by sub-controllers here
924 var start = new Date(); // now - 1 year
925 start.setFullYear(start.getFullYear() - 1),
928 xact_finish : new Date()
931 $scope.date_range = function() {
932 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
933 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
934 var today = new Date().toISOString().replace(/T.*/,'');
935 if (end == today) end = 'now';
941 .controller('BillXactHistoryCtrl',
942 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
943 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
945 // generate a grid query with the current date widget values.
946 function current_grid_query() {
949 {'summary.balance_owed' : {'<>' : 0}},
950 {'summary.last_payment_ts' : {'<>' : null}}
952 xact_start : {between : $scope.date_range()},
957 $scope.gridControls = {
958 selectedItems : function(){return []},
959 activateItem : function(item) {
960 $scope.showFullDetails([item]);
962 // this sets the query on page load
963 setQuery : current_grid_query
966 $scope.actions.apply_date_range = function() {
967 // tells the grid to re-draw itself with the new query
968 $scope.gridControls.setQuery(current_grid_query());
971 // TODO; move me to service
972 function selected_payment_info() {
973 var info = {owed : 0, billed : 0, paid : 0};
974 angular.forEach($scope.gridControls.selectedItems(), function(item) {
975 info.owed += Number(item['summary.balance_owed']) * 100;
976 info.billed += Number(item['summary.total_owed']) * 100;
977 info.paid += Number(item['summary.total_paid']) * 100;
985 $scope.totals.selected_billed = function() {
986 return selected_payment_info().billed;
988 $scope.totals.selected_paid = function() {
989 return selected_payment_info().paid;
992 $scope.showFullDetails = function(all) {
994 $location.path('/circ/patron/' +
995 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
998 // For now, only adds billing to first selected item.
999 // Could do batches later if needed
1000 $scope.addBilling = function(all) {
1002 egBilling.showBillDialog({
1003 xact : egCore.idl.flatToNestedHash(all[0]),
1004 patron : $scope.patron()
1005 }).then(function() {
1006 $scope.gridControls.refresh();
1007 patronSvc.fetchUserStats();
1012 $scope.printBills = function(selected) { // FIXME: refactor me
1013 if (!selected.length) return;
1014 // bills print receipt assumes nested hashes, but our grid
1015 // stores flattener data. Fetch the selected xacts as
1016 // fleshed pcrud objects and hashify.
1017 // (Consider an alternate approach..)
1018 var ids = selected.map(function(t){ return t.id });
1020 egCore.pcrud.search('mbt',
1022 {flesh : 5, flesh_fields : {
1023 'mbt' : ['summary', 'circulation'],
1024 'circ' : ['target_copy'],
1025 'acp' : ['call_number'],
1027 'bre' : ['simple_record']
1030 {authoritative : true}
1033 egCore.print.print({
1034 context : 'receipt',
1035 template : 'bills_historical',
1037 transactions : xacts,
1038 current_location : egCore.idl.toHash(
1039 egCore.org.get(egCore.auth.user().ws_ou()))
1046 billing_total : xact.billing_total(),
1047 billings : xact.billings(),
1048 grocery : xact.grocery(),
1050 payment_total : xact.payment_total(),
1051 payments : xact.payments(),
1052 summary : egCore.idl.toHash(xact.summary()),
1053 unrecovered : xact.unrecovered(),
1054 xact_finish : xact.xact_finish(),
1055 xact_start : xact.xact_start(),
1057 if (xact.circulation()) {
1058 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1059 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1061 xacts.push(newXact);
1067 .controller('BillPaymentHistoryCtrl',
1068 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1069 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1071 // generate a grid query with the current date widget values.
1072 function current_grid_query() {
1074 'payment_ts' : {between : $scope.date_range()},
1075 'xact.usr' : billSvc.userId
1079 $scope.gridControls = {
1080 selectedItems : function(){return []},
1081 activateItem : function(item) {
1082 $scope.showFullDetails([item]);
1084 setSort : function() {
1085 return [{'payment_ts' : 'DESC'}, 'id'];
1087 setQuery : current_grid_query
1090 $scope.actions.apply_date_range = function() {
1091 // tells the grid to re-draw itself with the new query
1092 $scope.gridControls.setQuery(current_grid_query());
1095 $scope.showFullDetails = function(all) {
1097 $location.path('/circ/patron/' +
1098 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1101 $scope.totals.selected_paid = function() {
1103 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1104 paid += Number(payment.amount) * 100;