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 // TODO: no longer needed?
91 service.fetchPayments = function(xact_id) {
92 return egCore.net.request(
94 'open-ils.circ.money.payment.retrieve.all.authoritative',
95 egCore.auth.token(), xact_id
99 service.voidBills = function(bill_ids) {
100 return egCore.net.requestWithParamList(
102 'open-ils.circ.money.billing.void',
103 [egCore.auth.token()].concat(bill_ids)
104 ).then(function(resp) {
105 if (evt = egCore.evt.parse(resp)) return alert(evt);
110 service.adjustBillsToZero = function(bill_ids) {
111 return egCore.net.request(
113 'open-ils.circ.money.billable_xact.adjust_to_zero',
116 ).then(function(resp) {
117 if (evt = egCore.evt.parse(resp)) return alert(evt);
122 service.updateBillNotes = function(note, ids) {
123 return egCore.net.requestWithParamList(
125 'open-ils.circ.money.billing.note.edit',
126 [egCore.auth.token(), note].concat(ids)
127 ).then(function(resp) {
128 if (evt = egCore.evt.parse(resp)) return alert(evt);
133 service.updatePaymentNotes = function(note, ids) {
134 return egCore.net.requestWithParamList(
136 'open-ils.circ.money.payment.note.edit',
137 [egCore.auth.token(), note].concat(ids)
138 ).then(function(resp) {
139 if (evt = egCore.evt.parse(resp)) return alert(evt);
151 .controller('PatronBillsCtrl',
152 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
153 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
154 'egBilling','$uibModal',
155 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
156 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
157 egBilling , $uibModal) {
159 $scope.initTab('bills', $routeParams.id);
160 billSvc.userId = $routeParams.id;
162 // set up some defaults
163 $scope.check_number = null;
164 $scope.payment_amount = null;
165 $scope.session_voided = 0;
166 $scope.payment_type = 'cash_payment';
167 $scope.focus_payment = true;
168 $scope.annotate_payment = false;
169 $scope.receipt_count = 1;
170 $scope.receipt_on_pay = { isChecked: false };
171 $scope.warn_amount = 1000;
172 $scope.max_amount = 100000;
173 $scope.amount_verified = false;
174 $scope.disable_auto_print = false;
176 // check receipt_on_pay setting default persisted
177 egCore.hatch.getItem('circ.bills.receiptonpay')
178 .then(function(rcptOnPay){
179 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
182 // pre-define list-returning funcs in case we access them
183 // before the grid instantiates
184 $scope.gridControls = {
185 focusRowSelector : false,
186 selectedItems : function(){return []},
187 allItems : function(){return []},
188 itemRetrieved : function(item) {
189 item.payment_pending = 0;
191 activateItem : function(item) {
192 $scope.showFullDetails([item]);
194 setQuery : function() {
196 usr : billSvc.userId,
198 'summary.balance_owed' : {'<>' : 0}
201 setSort : function() {
202 return ['xact_start'];
206 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
208 // given a payment amount, determines how much of that is applied
209 // to selected transactions and how much is left over (change).
210 function pending_payment_info() {
211 var amt = $scope.payment_amount || 0;
212 if (amt >= $scope.owed_selected()) {
214 payment : $scope.owed_selected(),
215 change : amt - $scope.owed_selected()
218 return {payment : amt, change : 0};
221 // calculates amount owed, billed, and paid for selected items
222 // TODO: move me to service
223 function selected_payment_info() {
224 var info = {owed : 0, billed : 0, paid : 0};
225 angular.forEach($scope.gridControls.selectedItems(), function(item) {
226 info.owed += Number(item['summary.balance_owed']) * 100;
227 info.billed += Number(item['summary.total_owed']) * 100;
228 info.paid += Number(item['summary.total_paid']) * 100;
236 $scope.pending_payment = function() {
237 return pending_payment_info().payment;
239 $scope.pending_change = function() {
240 return pending_payment_info().change;
242 $scope.owed_selected = function() {
243 return selected_payment_info().owed;
245 $scope.billed_selected = function() {
246 return selected_payment_info().billed;
248 $scope.paid_selected = function() {
249 return selected_payment_info().paid;
251 $scope.refunds_available = function() {
253 angular.forEach($scope.gridControls.allItems(), function(item) {
254 if (item['summary.balance_owed'] < 0)
255 amount += item['summary.balance_owed'] * 100;
257 return -(amount / 100);
259 $scope.invalid_check_number = function() {
260 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
263 // update the item.payment_pending value each time the user
264 // selects different transactions to pay against.
266 function() {return $scope.gridControls.selectedItems()},
267 function() {updatePendingColumn()},
271 // update the item.payment_pending for each (selected)
272 // transaction any time the user-entered payment amount is modified
273 $scope.$watch('payment_amount', updatePendingColumn);
275 // updates the value of the payment_pending column in the grid.
276 // This has to be managed manually since the display value in the grid
277 // is derived from the value on the stored item and not the contents
278 // of our local scope variables.
279 function updatePendingColumn() {
280 // reset all to zero..
281 angular.forEach($scope.gridControls.allItems(),
282 function(item) {item.payment_pending = 0});
284 var payment_amount = $scope.pending_payment();
286 var selected = $scope.gridControls.selectedItems();
287 for (var i = 0; i < selected.length; i++) { // for/break
288 var item = selected[i];
289 var owed = Number(item['summary.balance_owed']);
291 if (payment_amount > owed) {
292 // pending payment exceeds balance of current item.
293 // pay the entire item.
294 item.payment_pending = owed;
295 payment_amount -= owed;
298 // balance owed on the current item matches or exceeds
299 // the pending payment. Apply the full remainder of
300 // the payment to this item.. and we're done.
301 item.payment_pending = payment_amount;
307 // builds payment arrays ([xact_id, ammount]) for all transactions
308 // which have a pending payment amount.
309 function generatePayments() {
311 angular.forEach($scope.gridControls.selectedItems(), function(item) {
312 if (item.payment_pending == 0) return;
313 payments.push([item.id, item.payment_pending]);
318 function refreshDisplay() {
319 patronSvc.fetchUserStats();
320 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
321 $scope.payment_amount = null;
322 $scope.gridControls.refresh();
325 // generates payments, collects user note if needed, and sends payment
327 function sendPayment(note, cc_args) {
328 $scope.applyingPayment = true;
329 var make_payments = generatePayments();
330 billSvc.applyPayment($scope.payment_type,
331 make_payments, note, $scope.check_number, cc_args)
333 function(payment_ids) {
335 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
337 $scope.payment_type, payment_ids, make_payments, note);
343 console.error('Payment was rejected: ' + msg);
346 .finally(function() { $scope.applyingPayment = false; })
349 $scope.onReceiptOnPayChanged = function(){
350 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
353 function printReceipt(type, payment_ids, payments_made, note) {
354 var payment_blobs = [];
355 var cusr = patronSvc.current;
357 angular.forEach(payments_made, function(payment) {
358 var xact_id = payment[0];
360 // find the original transaction in the grid..
361 var xact = $scope.gridControls.allItems().filter(
362 function(item) {return item.id == xact_id})[0];
365 xact : egCore.idl.flatToNestedHash(xact),
370 console.log(js2JSON(payment_blobs[0]));
372 // page data not yet refreshed, capture data from current scope
376 previous_balance : Number($scope.summary.balance_owed()),
377 payment_total : Number($scope.payment_amount),
378 payment_applied : $scope.pending_payment(),
379 amount_voided : Number($scope.session_voided),
380 change_given : $scope.pending_change(),
381 payments : payment_blobs,
382 current_location : egCore.idl.toHash(
383 egCore.org.get(egCore.auth.user().ws_ou()))
386 // Not a good idea to use patron_stats.fines for this; it's out of date
387 print_data.patron = {
388 prefix : cusr.prefix(),
389 first_given_name : cusr.first_given_name(),
390 second_given_name : cusr.second_given_name(),
391 family_name : cusr.family_name(),
392 suffix : cusr.suffix(),
393 card : { barcode : cusr.card().barcode() },
394 expire_date : cusr.expire_date(),
395 alias : cusr.alias(),
396 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/).length),
397 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
400 print_data.new_balance = (
401 print_data.previous_balance * 100 -
402 print_data.payment_applied * 100) / 100;
404 for (var i = 0; i < $scope.receipt_count; i++) {
407 template : 'bill_payment',
413 $scope.showHistory = function() {
414 $location.path('/circ/patron/' +
415 patronSvc.current.id() + '/bill_history/transactions');
418 // For now, only adds billing to first selected item.
419 // Could do batches later if needed
420 $scope.addBilling = function(all) {
422 egBilling.showBillDialog({
423 xact : egCore.idl.flatToNestedHash(all[0]),
424 patron : $scope.patron()
425 }).then(refreshDisplay);
429 $scope.showBillDialog = function($event) {
430 egBilling.showBillDialog({
431 patron : $scope.patron()
432 }).then(refreshDisplay);
435 // Select refunds adds all refunds to the existing selection.
436 // It does not /only/ select refunds
437 $scope.selectRefunds = function() {
438 var ids = $scope.gridControls.selectedItems().map(
439 function(i) { return i.id });
440 angular.forEach($scope.gridControls.allItems(), function(item) {
441 if (Number(item['summary.balance_owed']) < 0)
444 $scope.gridControls.selectItems(ids);
448 // determine on initial page load when all of the grid rows should
450 var selectOnLoad = true;
451 billSvc.fetchBillSettings().then(function(s) {
452 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
453 $scope.focus_payment = false; // de-focus the payment box
454 $scope.gridControls.focusRowSelector = true;
455 selectOnLoad = false;
456 // if somehow the grid finishes rendering before our settings
457 // arrive, manually de-select everything.
458 $scope.gridControls.selectItems([]);
460 if (s['ui.circ.billing.amount_warn']) {
461 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
463 if (s['ui.circ.billing.amount_limit']) {
464 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
466 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
467 $scope.disable_auto_print = Boolean(
468 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
473 $scope.gridControls.allItemsRetrieved = function() {
475 selectOnLoad = false; // only for initial controller load.
476 // select all non-refund items
477 $scope.gridControls.selectItems(
478 $scope.gridControls.allItems()
479 .filter(function(i) {return i['summary.balance_owed'] > 0})
480 .map(function(i){return i.id})
487 $scope.printBills = function(selected) {
488 if (!selected.length) return;
489 // bills print receipt assumes nested hashes, but our grid
490 // stores flattener data. Fetch the selected xacts as
491 // fleshed pcrud objects and hashify.
492 // (Consider an alternate approach..)
493 var ids = selected.map(function(t){ return t.id });
495 egCore.pcrud.search('mbt',
497 {flesh : 5, flesh_fields : {
498 'mbt' : ['summary', 'circulation'],
499 'circ' : ['target_copy'],
500 'acp' : ['call_number'],
502 'bre' : ['simple_record']
505 {authoritative : true}
510 template : 'bills_current',
512 transactions : xacts,
513 current_location : egCore.idl.toHash(
514 egCore.org.get(egCore.auth.user().ws_ou()))
521 billing_total : xact.billing_total(),
522 billings : xact.billings(),
523 grocery : xact.grocery(),
525 payment_total : xact.payment_total(),
526 payments : xact.payments(),
527 summary : egCore.idl.toHash(xact.summary()),
528 unrecovered : xact.unrecovered(),
529 xact_finish : xact.xact_finish(),
530 xact_start : xact.xact_start(),
532 if (xact.circulation()) {
533 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
534 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
541 $scope.applyPayment = function() {
543 if ($scope.payment_amount > $scope.max_amount ) {
545 egCore.strings.PAYMENT_OVER_MAX,
546 { max_amount : ''+$scope.max_amount,
548 $scope.payment_amount = 0;
555 verify_payment_amount().then(
556 function() { // amount confirmed
557 add_payment_note().then(function(pay_note) {
558 add_cc_args().then(function(cc_args) {
559 var note_text = pay_note ? pay_note.value || '' : null;
560 sendPayment(note_text, cc_args);
564 function() { // amount rejected
565 console.warn('payment amount rejected');
566 $scope.payment_amount = 0;
571 function verify_payment_amount() {
572 if ($scope.payment_amount < $scope.warn_amount)
575 return egConfirmDialog.open(
576 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
577 egCore.strings.PAYMENT_WARN_AMOUNT,
578 {payment_amount : ''+$scope.payment_amount}
582 function add_payment_note() {
583 if (!$scope.annotate_payment) return $q.when();
584 return egPromptDialog.open(
585 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
588 function add_cc_args() {
589 if ($scope.payment_type != 'credit_card_payment')
592 return $uibModal.open({
593 templateUrl : './circ/patron/t_cc_payment_dialog',
596 '$scope','$uibModalInstance',
597 function($scope , $uibModalInstance) {
601 where_process : '1', // internal=1 ; external=0
602 type : 'VISA', // external only
603 billing_first : patronSvc.current.first_given_name(),
604 billing_last : patronSvc.current.family_name()
608 var addr = patronSvc.current.billing_address() ||
609 patronSvc.current.mailing_address();
611 var cc = $scope.context.cc;
612 cc.billing_address = addr.street1() +
613 (addr.street2() ? ' ' + addr.street2() : '');
614 cc.billing_city = addr.city();
615 cc.billing_state = addr.state();
616 cc.billing_zip = addr.post_code();
619 $scope.ok = function() {
620 // CC payment form is not a <form>,
621 // so apply validation manually.
622 if ( $scope.context.cc.where_process == 0 &&
623 !$scope.context.cc.approval_code)
626 $uibModalInstance.close($scope.context.cc);
629 $scope.cancel = function() {
630 $uibModalInstance.dismiss();
637 $scope.voidAllBillings = function(items) {
641 angular.forEach(items, function(item) {
643 billSvc.fetchBills(item.id).then(function(bills) {
644 angular.forEach(bills, function(b) {
645 if (b.voided() != 't') {
646 cents += b.amount() * 100;
647 bill_ids.push(b.id())
651 if (bill_ids.length == 0) {
660 $q.all(promises).then(function(){
661 egCore.audio.play('warning.circ.void_billings_confirmation');
662 egConfirmDialog.open(
663 egCore.strings.CONFIRM_VOID_BILLINGS, '',
664 { billIds : ''+bill_ids,
665 amount : ''+(cents/100),
667 billSvc.voidBills(bill_ids).then(function() {
668 $scope.session_voided =
669 ($scope.session_voided * 100 + cents) / 100;
678 $scope.adjustToZero = function(items) {
679 if (items.length == 0) return;
681 var ids = items.map(function(item) {return item.id});
683 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
684 egConfirmDialog.open(
685 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
688 billSvc.adjustBillsToZero(ids).then(function() {
697 // note this is functionally equivalent to selecting a neg. transaction
698 // then clicking Apply Payment -- this just adds a speed bump (ditto
700 $scope.refundXact = function(all) {
701 var items = all.filter(function(item) {
702 return item['summary.balance_owed'] < 0
705 if (items.length == 0) return;
707 var ids = items.map(function(item) {return item.id});
709 egCore.audio.play('warning.circ.refund_confirmation');
710 egConfirmDialog.open(
711 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
714 // reset the received payment amount. this ensures
715 // we're not mingling payments with refunds.
716 $scope.payment_amount = 0;
722 // direct the user to the transaction details page
723 $scope.showFullDetails = function(all) {
725 $location.path('/circ/patron/' +
726 patronSvc.current.id() + '/bill/' + all[0].id);
729 $scope.activateBill = function(xact) {
730 $scope.showFullDetails([xact]);
736 * Displays details of a single transaction
738 .controller('XactDetailsCtrl',
739 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
740 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
742 $scope.initTab('bills', $routeParams.id);
743 var xact_id = $routeParams.xact_id;
745 var xactGrid = $scope.xactGridControls = {
746 setQuery : function() { return {xact : xact_id} },
747 setSort : function() { return ['billing_ts'] }
750 var paymentGrid = $scope.paymentGridControls = {
751 setQuery : function() { return {xact : xact_id} },
752 setSort : function() { return ['payment_ts'] }
756 $scope.voidBillings = function(bill_list) {
759 angular.forEach(bill_list, function(b) {
760 if (b.voided != 't') {
761 cents += b.amount * 100;
766 if (bill_ids.length == 0) {
771 egCore.audio.play('warning.circ.void_billings_confirmation');
772 egConfirmDialog.open(
773 egCore.strings.CONFIRM_VOID_BILLINGS, '',
774 { billIds : ''+bill_ids,
775 amount : ''+(cents/100),
777 billSvc.voidBills(bill_ids).then(function() {
778 // TODO? $scope.session_voided = ...
780 // refresh bills and summary data
781 // note: no need to update payments
782 patronSvc.fetchUserStats();
784 egBilling.fetchXact(xact_id).then(function(xact) {
795 // batch-edit billing and payment notes, depending on 'type'
796 function editNotes(selected, type) {
797 var notes = selected.map(function(b){ return b.note }).join(',');
798 var ids = selected.map(function(b){ return b.id });
800 // show the note edit prompt
802 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
804 ok : function(value) {
806 var func = 'updateBillNotes';
807 if (type == 'payment') func = 'updatePaymentNotes';
809 billSvc[func](value, ids).then(function() {
810 if (type == 'payment') {
811 paymentGrid.refresh();
821 $scope.editBillNotes = function(selected) {
822 editNotes(selected, 'bill');
825 $scope.editPaymentNotes = function(selected) {
826 editNotes(selected, 'payment');
829 // -- retrieve our data
830 $scope.total_circs = 0; // start with 0 instead of undefined
831 egBilling.fetchXact(xact_id).then(function(xact) {
834 var copyId = xact.circulation().target_copy().id();
836 egCore.pcrud.search('circbyyr',
837 {copy : copyId}, null, {atomic : true})
838 .then(function(counts) {
839 angular.forEach(counts, function(count) {
840 circ_count += Number(count.count());
842 $scope.total_circs = circ_count;
844 // set the title. only needs to be done on initial page load
845 if (xact.circulation()) {
846 if (xact.circulation().target_copy().call_number().id() == -1) {
847 $scope.title = xact.circulation().target_copy().dummy_title();
849 // TODO: shared bib service?
850 $scope.title = xact.circulation().target_copy()
851 .call_number().record().simple_record().title();
852 $scope.title_id = xact.circulation().target_copy()
853 .call_number().record().id();
860 .controller('BillHistoryCtrl',
861 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
862 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
864 $scope.initTab('bills', $routeParams.id);
865 billSvc.userId = $routeParams.id;
866 $scope.bill_tab = $routeParams.history_tab;
869 // link page controller actions defined by sub-controllers here
872 var start = new Date(); // now - 1 year
873 start.setFullYear(start.getFullYear() - 1),
876 xact_finish : new Date()
879 $scope.date_range = function() {
880 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
881 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
882 var today = new Date().toISOString().replace(/T.*/,'');
883 if (end == today) end = 'now';
889 .controller('BillXactHistoryCtrl',
890 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
891 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
893 // generate a grid query with the current date widget values.
894 function current_grid_query() {
897 {'summary.balance_owed' : {'<>' : 0}},
898 {'summary.last_payment_ts' : {'<>' : null}}
900 xact_start : {between : $scope.date_range()},
905 $scope.gridControls = {
906 selectedItems : function(){return []},
907 activateItem : function(item) {
908 $scope.showFullDetails([item]);
910 // this sets the query on page load
911 setQuery : current_grid_query
914 $scope.actions.apply_date_range = function() {
915 // tells the grid to re-draw itself with the new query
916 $scope.gridControls.setQuery(current_grid_query());
919 // TODO; move me to service
920 function selected_payment_info() {
921 var info = {owed : 0, billed : 0, paid : 0};
922 angular.forEach($scope.gridControls.selectedItems(), function(item) {
923 info.owed += Number(item['summary.balance_owed']) * 100;
924 info.billed += Number(item['summary.total_owed']) * 100;
925 info.paid += Number(item['summary.total_paid']) * 100;
933 $scope.totals.selected_billed = function() {
934 return selected_payment_info().billed;
936 $scope.totals.selected_paid = function() {
937 return selected_payment_info().paid;
940 $scope.showFullDetails = function(all) {
942 $location.path('/circ/patron/' +
943 patronSvc.current.id() + '/bill/' + all[0].id);
946 // For now, only adds billing to first selected item.
947 // Could do batches later if needed
948 $scope.addBilling = function(all) {
950 egBilling.showBillDialog({
951 xact : egCore.idl.flatToNestedHash(all[0]),
952 patron : $scope.patron()
954 $scope.gridControls.refresh();
955 patronSvc.fetchUserStats();
960 $scope.printBills = function(selected) { // FIXME: refactor me
961 if (!selected.length) return;
962 // bills print receipt assumes nested hashes, but our grid
963 // stores flattener data. Fetch the selected xacts as
964 // fleshed pcrud objects and hashify.
965 // (Consider an alternate approach..)
966 var ids = selected.map(function(t){ return t.id });
968 egCore.pcrud.search('mbt',
970 {flesh : 5, flesh_fields : {
971 'mbt' : ['summary', 'circulation'],
972 'circ' : ['target_copy'],
973 'acp' : ['call_number'],
975 'bre' : ['simple_record']
978 {authoritative : true}
983 template : 'bills_historical',
985 transactions : xacts,
986 current_location : egCore.idl.toHash(
987 egCore.org.get(egCore.auth.user().ws_ou()))
994 billing_total : xact.billing_total(),
995 billings : xact.billings(),
996 grocery : xact.grocery(),
998 payment_total : xact.payment_total(),
999 payments : xact.payments(),
1000 summary : egCore.idl.toHash(xact.summary()),
1001 unrecovered : xact.unrecovered(),
1002 xact_finish : xact.xact_finish(),
1003 xact_start : xact.xact_start(),
1005 if (xact.circulation()) {
1006 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1007 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1009 xacts.push(newXact);
1015 .controller('BillPaymentHistoryCtrl',
1016 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1017 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1019 // generate a grid query with the current date widget values.
1020 function current_grid_query() {
1022 'payment_ts' : {between : $scope.date_range()},
1023 'xact.usr' : billSvc.userId
1027 $scope.gridControls = {
1028 selectedItems : function(){return []},
1029 activateItem : function(item) {
1030 $scope.showFullDetails([item]);
1032 setSort : function() {
1033 return [{'payment_ts' : 'DESC'}, 'id'];
1035 setQuery : current_grid_query
1038 $scope.actions.apply_date_range = function() {
1039 // tells the grid to re-draw itself with the new query
1040 $scope.gridControls.setQuery(current_grid_query());
1043 $scope.showFullDetails = function(all) {
1045 $location.path('/circ/patron/' +
1046 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
1049 $scope.totals.selected_paid = function() {
1051 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1052 paid += Number(payment.amount) * 100;