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 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
219 // given a payment amount, determines how much of that is applied
220 // to selected transactions and how much is left over (change).
221 function pending_payment_info() {
222 var amt = $scope.payment_amount || 0;
223 if (amt >= $scope.owed_selected()) {
225 payment : $scope.owed_selected(),
226 change : amt - $scope.owed_selected()
229 return {payment : amt, change : 0};
232 // calculates amount owed, billed, and paid for selected items
233 // TODO: move me to service
234 function selected_payment_info() {
235 var info = {owed : 0, billed : 0, paid : 0};
236 angular.forEach($scope.gridControls.selectedItems(), function(item) {
237 info.owed += Number(item['summary.balance_owed']) * 100;
238 info.billed += Number(item['summary.total_owed']) * 100;
239 info.paid += Number(item['summary.total_paid']) * 100;
247 $scope.pending_payment = function() {
248 return pending_payment_info().payment;
250 $scope.pending_change = function() {
251 return pending_payment_info().change;
253 $scope.owed_selected = function() {
254 return selected_payment_info().owed;
256 $scope.billed_selected = function() {
257 return selected_payment_info().billed;
259 $scope.paid_selected = function() {
260 return selected_payment_info().paid;
262 $scope.refunds_available = function() {
264 angular.forEach($scope.gridControls.allItems(), function(item) {
265 if (item['summary.balance_owed'] < 0)
266 amount += item['summary.balance_owed'] * 100;
268 return -(amount / 100);
270 $scope.invalid_check_number = function() {
271 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
274 // update the item.payment_pending value each time the user
275 // selects different transactions to pay against.
277 function() {return $scope.gridControls.selectedItems()},
278 function() {updatePendingColumn()},
282 // update the item.payment_pending for each (selected)
283 // transaction any time the user-entered payment amount is modified
284 $scope.$watch('payment_amount', updatePendingColumn);
286 // updates the value of the payment_pending column in the grid.
287 // This has to be managed manually since the display value in the grid
288 // is derived from the value on the stored item and not the contents
289 // of our local scope variables.
290 function updatePendingColumn() {
291 // reset all to zero..
292 angular.forEach($scope.gridControls.allItems(),
293 function(item) {item.payment_pending = 0});
295 var payment_amount = $scope.pending_payment();
297 var selected = $scope.gridControls.selectedItems();
298 for (var i = 0; i < selected.length; i++) { // for/break
299 var item = selected[i];
300 var owed = Number(item['summary.balance_owed']);
302 if (payment_amount > owed) {
303 // pending payment exceeds balance of current item.
304 // pay the entire item.
305 item.payment_pending = owed;
306 payment_amount -= owed;
309 // balance owed on the current item matches or exceeds
310 // the pending payment. Apply the full remainder of
311 // the payment to this item.. and we're done.
312 item.payment_pending = payment_amount;
318 // builds payment arrays ([xact_id, ammount]) for all transactions
319 // which have a pending payment amount.
320 function generatePayments() {
322 angular.forEach($scope.gridControls.selectedItems(), function(item) {
323 if (item.payment_pending == 0) return;
324 payments.push([item.id, item.payment_pending]);
329 function refreshDisplay() {
330 patronSvc.fetchUserStats();
331 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
332 $scope.payment_amount = null;
333 $scope.gridControls.refresh();
336 // generates payments, collects user note if needed, and sends payment
338 function sendPayment(note, cc_args) {
339 $scope.applyingPayment = true;
340 var make_payments = generatePayments();
341 billSvc.applyPayment($scope.payment_type,
342 make_payments, note, $scope.check_number, cc_args)
344 function(payment_ids) {
346 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
348 $scope.payment_type, payment_ids, make_payments, note);
354 console.error('Payment was rejected: ' + msg);
357 .finally(function() { $scope.applyingPayment = false; })
360 $scope.onReceiptOnPayChanged = function(){
361 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
364 function printReceipt(type, payment_ids, payments_made, note) {
365 var payment_blobs = [];
366 var cusr = patronSvc.current;
368 angular.forEach(payments_made, function(payment) {
369 var xact_id = payment[0];
371 // find the original transaction in the grid..
372 var xact = $scope.gridControls.allItems().filter(
373 function(item) {return item.id == xact_id})[0];
376 xact : egCore.idl.flatToNestedHash(xact),
381 console.log(js2JSON(payment_blobs[0]));
383 // page data not yet refreshed, capture data from current scope
387 previous_balance : Number($scope.summary.balance_owed()),
388 payment_total : Number($scope.payment_amount),
389 payment_applied : $scope.pending_payment(),
390 amount_voided : Number($scope.session_voided),
391 change_given : $scope.pending_change(),
392 payments : payment_blobs,
393 current_location : egCore.idl.toHash(
394 egCore.org.get(egCore.auth.user().ws_ou()))
397 // Not a good idea to use patron_stats.fines for this; it's out of date
398 print_data.patron = {
399 prefix : cusr.prefix(),
400 first_given_name : cusr.first_given_name(),
401 second_given_name : cusr.second_given_name(),
402 family_name : cusr.family_name(),
403 suffix : cusr.suffix(),
404 card : { barcode : cusr.card().barcode() },
405 expire_date : cusr.expire_date(),
406 alias : cusr.alias(),
407 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/).length),
408 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
411 print_data.new_balance = (
412 print_data.previous_balance * 100 -
413 print_data.payment_applied * 100) / 100;
415 for (var i = 0; i < $scope.receipt_count; i++) {
418 template : 'bill_payment',
424 $scope.showHistory = function() {
425 $location.path('/circ/patron/' +
426 patronSvc.current.id() + '/bill_history/transactions');
429 // For now, only adds billing to first selected item.
430 // Could do batches later if needed
431 $scope.addBilling = function(all) {
433 egBilling.showBillDialog({
434 xact : egCore.idl.flatToNestedHash(all[0]),
435 patron : $scope.patron()
436 }).then(refreshDisplay);
440 $scope.showBillDialog = function($event) {
441 egBilling.showBillDialog({
442 patron : $scope.patron()
443 }).then(refreshDisplay);
446 // Select refunds adds all refunds to the existing selection.
447 // It does not /only/ select refunds
448 $scope.selectRefunds = function() {
449 var ids = $scope.gridControls.selectedItems().map(
450 function(i) { return i.id });
451 angular.forEach($scope.gridControls.allItems(), function(item) {
452 if (Number(item['summary.balance_owed']) < 0)
455 $scope.gridControls.selectItems(ids);
459 // determine on initial page load when all of the grid rows should
461 var selectOnLoad = true;
462 billSvc.fetchBillSettings().then(function(s) {
463 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
464 $scope.focus_payment = false; // de-focus the payment box
465 $scope.gridControls.focusRowSelector = true;
466 selectOnLoad = false;
467 // if somehow the grid finishes rendering before our settings
468 // arrive, manually de-select everything.
469 $scope.gridControls.selectItems([]);
471 if (s['ui.circ.billing.amount_warn']) {
472 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
474 if (s['ui.circ.billing.amount_limit']) {
475 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
477 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
478 $scope.disable_auto_print = Boolean(
479 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
484 $scope.gridControls.allItemsRetrieved = function() {
486 selectOnLoad = false; // only for initial controller load.
487 // select all non-refund items
488 $scope.gridControls.selectItems(
489 $scope.gridControls.allItems()
490 .filter(function(i) {return i['summary.balance_owed'] > 0})
491 .map(function(i){return i.id})
498 $scope.printBills = function(selected) {
499 if (!selected.length) return;
500 // bills print receipt assumes nested hashes, but our grid
501 // stores flattener data. Fetch the selected xacts as
502 // fleshed pcrud objects and hashify.
503 // (Consider an alternate approach..)
504 var ids = selected.map(function(t){ return t.id });
506 egCore.pcrud.search('mbt',
508 {flesh : 5, flesh_fields : {
509 'mbt' : ['summary', 'circulation'],
510 'circ' : ['target_copy'],
511 'acp' : ['call_number'],
513 'bre' : ['simple_record']
516 {authoritative : true}
521 template : 'bills_current',
523 transactions : xacts,
524 current_location : egCore.idl.toHash(
525 egCore.org.get(egCore.auth.user().ws_ou()))
532 billing_total : xact.billing_total(),
533 billings : xact.billings(),
534 grocery : xact.grocery(),
536 payment_total : xact.payment_total(),
537 payments : xact.payments(),
538 summary : egCore.idl.toHash(xact.summary()),
539 unrecovered : xact.unrecovered(),
540 xact_finish : xact.xact_finish(),
541 xact_start : xact.xact_start(),
543 if (xact.circulation()) {
544 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
545 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
552 $scope.applyPayment = function() {
554 if ($scope.payment_amount > $scope.max_amount ) {
556 egCore.strings.PAYMENT_OVER_MAX,
557 { max_amount : ''+$scope.max_amount,
559 $scope.payment_amount = 0;
566 verify_payment_amount().then(
567 function() { // amount confirmed
568 add_payment_note().then(function(pay_note) {
569 add_cc_args().then(function(cc_args) {
570 var note_text = pay_note ? pay_note.value || '' : null;
571 sendPayment(note_text, cc_args);
575 function() { // amount rejected
576 console.warn('payment amount rejected');
577 $scope.payment_amount = 0;
582 function verify_payment_amount() {
583 if ($scope.payment_amount < $scope.warn_amount)
586 return egConfirmDialog.open(
587 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
588 egCore.strings.PAYMENT_WARN_AMOUNT,
589 {payment_amount : ''+$scope.payment_amount}
593 function add_payment_note() {
594 if (!$scope.annotate_payment) return $q.when();
595 return egPromptDialog.open(
596 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
599 function add_cc_args() {
600 if ($scope.payment_type != 'credit_card_payment')
603 return $uibModal.open({
604 templateUrl : './circ/patron/t_cc_payment_dialog',
607 '$scope','$uibModalInstance',
608 function($scope , $uibModalInstance) {
612 where_process : '1', // internal=1 ; external=0
613 type : 'VISA', // external only
614 billing_first : patronSvc.current.first_given_name(),
615 billing_last : patronSvc.current.family_name()
619 var addr = patronSvc.current.billing_address() ||
620 patronSvc.current.mailing_address();
622 var cc = $scope.context.cc;
623 cc.billing_address = addr.street1() +
624 (addr.street2() ? ' ' + addr.street2() : '');
625 cc.billing_city = addr.city();
626 cc.billing_state = addr.state();
627 cc.billing_zip = addr.post_code();
630 $scope.ok = function() {
631 // CC payment form is not a <form>,
632 // so apply validation manually.
633 if ( $scope.context.cc.where_process == 0 &&
634 !$scope.context.cc.approval_code)
637 $uibModalInstance.close($scope.context.cc);
640 $scope.cancel = function() {
641 $uibModalInstance.dismiss();
648 $scope.voidAllBillings = function(items) {
652 angular.forEach(items, function(item) {
654 billSvc.fetchBills(item.id).then(function(bills) {
655 angular.forEach(bills, function(b) {
656 if (b.voided() != 't') {
657 cents += b.amount() * 100;
658 bill_ids.push(b.id())
662 if (bill_ids.length == 0) {
671 $q.all(promises).then(function(){
672 egCore.audio.play('warning.circ.void_billings_confirmation');
673 egConfirmDialog.open(
674 egCore.strings.CONFIRM_VOID_BILLINGS, '',
675 { billIds : ''+bill_ids,
676 amount : ''+(cents/100),
678 billSvc.voidBills(bill_ids).then(function() {
679 $scope.session_voided =
680 ($scope.session_voided * 100 + cents) / 100;
689 $scope.adjustToZero = function(items) {
690 if (items.length == 0) return;
692 var ids = items.map(function(item) {return item.id});
694 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
695 egConfirmDialog.open(
696 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
699 billSvc.adjustBillsToZero(ids).then(function() {
708 // note this is functionally equivalent to selecting a neg. transaction
709 // then clicking Apply Payment -- this just adds a speed bump (ditto
711 $scope.refundXact = function(all) {
712 var items = all.filter(function(item) {
713 return item['summary.balance_owed'] < 0
716 if (items.length == 0) return;
718 var ids = items.map(function(item) {return item.id});
720 egCore.audio.play('warning.circ.refund_confirmation');
721 egConfirmDialog.open(
722 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
725 // reset the received payment amount. this ensures
726 // we're not mingling payments with refunds.
727 $scope.payment_amount = 0;
733 // direct the user to the transaction details page
734 $scope.showFullDetails = function(all) {
736 $location.path('/circ/patron/' +
737 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
740 $scope.activateBill = function(xact) {
741 $scope.showFullDetails([xact]);
747 * Displays details of a single transaction
749 .controller('XactDetailsCtrl',
750 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
751 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
753 $scope.initTab('bills', $routeParams.id);
754 var xact_id = $routeParams.xact_id;
755 $scope.xact_tab = $routeParams.xact_tab;
757 var xactGrid = $scope.xactGridControls = {
758 setQuery : function() { return {xact : xact_id} },
759 setSort : function() { return ['billing_ts'] }
762 var paymentGrid = $scope.paymentGridControls = {
763 setQuery : function() { return {xact : xact_id} },
764 setSort : function() { return ['payment_ts'] }
768 $scope.voidBillings = function(bill_list) {
771 angular.forEach(bill_list, function(b) {
772 if (b.voided != 't') {
773 cents += b.amount * 100;
778 if (bill_ids.length == 0) {
783 egCore.audio.play('warning.circ.void_billings_confirmation');
784 egConfirmDialog.open(
785 egCore.strings.CONFIRM_VOID_BILLINGS, '',
786 { billIds : ''+bill_ids,
787 amount : ''+(cents/100),
789 billSvc.voidBills(bill_ids).then(function() {
790 // TODO? $scope.session_voided = ...
792 // refresh bills and summary data
793 // note: no need to update payments
794 patronSvc.fetchUserStats();
796 egBilling.fetchXact(xact_id).then(function(xact) {
807 // batch-edit billing and payment notes, depending on 'type'
808 function editNotes(selected, type) {
809 var notes = selected.map(function(b){ return b.note }).join(',');
810 var ids = selected.map(function(b){ return b.id });
812 // show the note edit prompt
814 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
816 ok : function(value) {
818 var func = 'updateBillNotes';
819 if (type == 'payment') func = 'updatePaymentNotes';
821 billSvc[func](value, ids).then(function() {
822 if (type == 'payment') {
823 paymentGrid.refresh();
833 $scope.editBillNotes = function(selected) {
834 editNotes(selected, 'bill');
837 $scope.editPaymentNotes = function(selected) {
838 editNotes(selected, 'payment');
841 // -- retrieve our data
842 if ($scope.xact_tab == 'statement') {
843 //fetch combined billing statement data
844 billSvc.fetchStatement(xact_id).then(function(statement) {
845 //console.log(statement);
846 $scope.statement_data = statement;
849 $scope.total_circs = 0; // start with 0 instead of undefined
850 egBilling.fetchXact(xact_id).then(function(xact) {
853 var copyId = xact.circulation().target_copy().id();
855 egCore.pcrud.search('circbyyr',
856 {copy : copyId}, null, {atomic : true})
857 .then(function(counts) {
858 angular.forEach(counts, function(count) {
859 circ_count += Number(count.count());
861 $scope.total_circs = circ_count;
863 // set the title. only needs to be done on initial page load
864 if (xact.circulation()) {
865 if (xact.circulation().target_copy().call_number().id() == -1) {
866 $scope.title = xact.circulation().target_copy().dummy_title();
868 // TODO: shared bib service?
869 $scope.title = xact.circulation().target_copy()
870 .call_number().record().simple_record().title();
871 $scope.title_id = xact.circulation().target_copy()
872 .call_number().record().id();
879 .controller('BillHistoryCtrl',
880 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
881 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
883 $scope.initTab('bills', $routeParams.id);
884 billSvc.userId = $routeParams.id;
885 $scope.bill_tab = $routeParams.history_tab;
888 // link page controller actions defined by sub-controllers here
891 var start = new Date(); // now - 1 year
892 start.setFullYear(start.getFullYear() - 1),
895 xact_finish : new Date()
898 $scope.date_range = function() {
899 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
900 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
901 var today = new Date().toISOString().replace(/T.*/,'');
902 if (end == today) end = 'now';
908 .controller('BillXactHistoryCtrl',
909 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
910 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
912 // generate a grid query with the current date widget values.
913 function current_grid_query() {
916 {'summary.balance_owed' : {'<>' : 0}},
917 {'summary.last_payment_ts' : {'<>' : null}}
919 xact_start : {between : $scope.date_range()},
924 $scope.gridControls = {
925 selectedItems : function(){return []},
926 activateItem : function(item) {
927 $scope.showFullDetails([item]);
929 // this sets the query on page load
930 setQuery : current_grid_query
933 $scope.actions.apply_date_range = function() {
934 // tells the grid to re-draw itself with the new query
935 $scope.gridControls.setQuery(current_grid_query());
938 // TODO; move me to service
939 function selected_payment_info() {
940 var info = {owed : 0, billed : 0, paid : 0};
941 angular.forEach($scope.gridControls.selectedItems(), function(item) {
942 info.owed += Number(item['summary.balance_owed']) * 100;
943 info.billed += Number(item['summary.total_owed']) * 100;
944 info.paid += Number(item['summary.total_paid']) * 100;
952 $scope.totals.selected_billed = function() {
953 return selected_payment_info().billed;
955 $scope.totals.selected_paid = function() {
956 return selected_payment_info().paid;
959 $scope.showFullDetails = function(all) {
961 $location.path('/circ/patron/' +
962 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
965 // For now, only adds billing to first selected item.
966 // Could do batches later if needed
967 $scope.addBilling = function(all) {
969 egBilling.showBillDialog({
970 xact : egCore.idl.flatToNestedHash(all[0]),
971 patron : $scope.patron()
973 $scope.gridControls.refresh();
974 patronSvc.fetchUserStats();
979 $scope.printBills = function(selected) { // FIXME: refactor me
980 if (!selected.length) return;
981 // bills print receipt assumes nested hashes, but our grid
982 // stores flattener data. Fetch the selected xacts as
983 // fleshed pcrud objects and hashify.
984 // (Consider an alternate approach..)
985 var ids = selected.map(function(t){ return t.id });
987 egCore.pcrud.search('mbt',
989 {flesh : 5, flesh_fields : {
990 'mbt' : ['summary', 'circulation'],
991 'circ' : ['target_copy'],
992 'acp' : ['call_number'],
994 'bre' : ['simple_record']
997 {authoritative : true}
1000 egCore.print.print({
1001 context : 'receipt',
1002 template : 'bills_historical',
1004 transactions : xacts,
1005 current_location : egCore.idl.toHash(
1006 egCore.org.get(egCore.auth.user().ws_ou()))
1013 billing_total : xact.billing_total(),
1014 billings : xact.billings(),
1015 grocery : xact.grocery(),
1017 payment_total : xact.payment_total(),
1018 payments : xact.payments(),
1019 summary : egCore.idl.toHash(xact.summary()),
1020 unrecovered : xact.unrecovered(),
1021 xact_finish : xact.xact_finish(),
1022 xact_start : xact.xact_start(),
1024 if (xact.circulation()) {
1025 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1026 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1028 xacts.push(newXact);
1034 .controller('BillPaymentHistoryCtrl',
1035 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1036 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1038 // generate a grid query with the current date widget values.
1039 function current_grid_query() {
1041 'payment_ts' : {between : $scope.date_range()},
1042 'xact.usr' : billSvc.userId
1046 $scope.gridControls = {
1047 selectedItems : function(){return []},
1048 activateItem : function(item) {
1049 $scope.showFullDetails([item]);
1051 setSort : function() {
1052 return [{'payment_ts' : 'DESC'}, 'id'];
1054 setQuery : current_grid_query
1057 $scope.actions.apply_date_range = function() {
1058 // tells the grid to re-draw itself with the new query
1059 $scope.gridControls.setQuery(current_grid_query());
1062 $scope.showFullDetails = function(all) {
1064 $location.path('/circ/patron/' +
1065 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1068 $scope.totals.selected_paid = function() {
1070 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1071 paid += Number(payment.amount) * 100;