4 angular.module('egPatronApp')
7 ['$q','egCore','egWorkLog','patronSvc',
8 function($q , egCore , egWorkLog , patronSvc) {
12 // fetch org unit settings specific to the bills display
13 service.fetchBillSettings = function() {
14 if (service.settings) return $q.when(service.settings);
15 return egCore.org.settings([
16 'ui.circ.billing.uncheck_bills_and_unfocus_payment_box',
17 'ui.circ.billing.amount_warn', 'ui.circ.billing.amount_limit',
18 'circ.staff_client.do_not_auto_attempt_print',
19 'circ.disable_patron_credit'
20 ]).then(function(s) {return service.settings = s});
23 // user billing summary
24 service.fetchSummary = function() {
25 return egCore.pcrud.retrieve(
26 'mous', service.userId, {}, {authoritative : true})
27 .then(function(summary) {return service.summary = summary})
30 service.applyPayment = function(
31 type, payments, note, check, cc_args, patron_credit) {
33 return egCore.net.request(
35 'open-ils.circ.money.payment',
36 egCore.auth.token(), {
37 userid : service.userId,
42 patron_credit : patron_credit,
45 patronSvc.current.last_xact_id()
46 ).then(function(resp) {
47 console.debug('payments: ' + js2JSON(resp));
49 if (evt = egCore.evt.parse(resp)) {
50 // Ideally, all scenarios that lead to this alert appearing
51 // will be avoided by the application logic. Leave the alert
52 // in place now to root out any that remain to be addressed.
54 return $q.reject(''+evt);
57 var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
60 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
61 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
62 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
63 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
64 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
65 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
66 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
70 'action' : 'paid_bill',
71 'patron_id' : service.userId,
72 'total_amount' : total
76 // payment API returns the update xact id so we can track it
77 // for future payments without having to refresh the user.
78 patronSvc.current.last_xact_id(resp.last_xact_id);
83 service.fetchBills = function(xact_id) {
85 return egCore.pcrud.search('mb',
86 {xact : xact_id}, null,
87 {authoritative : true}
89 function() {return bills},
91 function(bill) {bills.push(bill); return bill}
95 service.fetchStatement = function(xact_id) {
96 return egCore.net.request(
98 'open-ils.circ.money.statement.retrieve',
99 egCore.auth.token(), xact_id
100 ).then(function(resp) {
101 if (evt = egCore.evt.parse(resp)) return alert(evt);
106 // TODO: no longer needed?
107 service.fetchPayments = function(xact_id) {
108 return egCore.net.request(
110 'open-ils.circ.money.payment.retrieve.all.authoritative',
111 egCore.auth.token(), xact_id
115 service.voidBills = function(bill_ids) {
116 return egCore.net.requestWithParamList(
118 'open-ils.circ.money.billing.void',
119 [egCore.auth.token()].concat(bill_ids)
120 ).then(function(resp) {
121 if (evt = egCore.evt.parse(resp)) return alert(evt);
126 service.adjustBillsToZero = function(bill_ids) {
127 return egCore.net.request(
129 'open-ils.circ.money.billable_xact.adjust_to_zero',
132 ).then(function(resp) {
133 if (evt = egCore.evt.parse(resp)) return alert(evt);
138 service.updateBillNotes = function(note, ids) {
139 return egCore.net.requestWithParamList(
141 'open-ils.circ.money.billing.note.edit',
142 [egCore.auth.token(), note].concat(ids)
143 ).then(function(resp) {
144 if (evt = egCore.evt.parse(resp)) return alert(evt);
149 service.updatePaymentNotes = function(note, ids) {
150 return egCore.net.requestWithParamList(
152 'open-ils.circ.money.payment.note.edit',
153 [egCore.auth.token(), note].concat(ids)
154 ).then(function(resp) {
155 if (evt = egCore.evt.parse(resp)) return alert(evt);
167 .controller('PatronBillsCtrl',
168 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
169 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
170 'egBilling','$uibModal',
171 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
172 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
173 egBilling , $uibModal) {
175 $scope.initTab('bills', $routeParams.id);
176 billSvc.userId = $routeParams.id;
178 // set up some defaults
179 $scope.check_number = null;
180 $scope.payment_amount = null;
181 $scope.session_voided = 0;
182 $scope.payment_type = 'cash_payment';
183 $scope.focus_payment = true;
184 $scope.annotate_payment = false;
185 $scope.receipt_count = 1;
186 $scope.receipt_on_pay = { isChecked: false };
187 $scope.convert_to_credit = {isChecked: false};
188 $scope.warn_amount = 1000;
189 $scope.max_amount = 100000;
190 $scope.amount_verified = false;
191 $scope.disable_auto_print = false;
193 // check receipt_on_pay setting default persisted
194 egCore.hatch.getItem('circ.bills.receiptonpay')
195 .then(function(rcptOnPay){
196 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
199 // pre-define list-returning funcs in case we access them
200 // before the grid instantiates
201 $scope.gridControls = {
202 focusRowSelector : false,
203 selectedItems : function(){return []},
204 allItems : function(){return []},
205 itemRetrieved : function(item) {
206 item.payment_pending = 0;
208 activateItem : function(item) {
209 $scope.showFullDetails([item]);
211 setQuery : function() {
213 usr : billSvc.userId,
215 'summary.balance_owed' : {'<>' : 0}
218 setSort : function() {
219 return ['xact_start'];
223 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
225 // given a payment amount, determines how much of that is applied
226 // to selected transactions and how much is left over (change).
227 function pending_payment_info() {
228 var amt = $scope.payment_amount || 0;
229 if (amt >= $scope.owed_selected()) {
231 payment : $scope.owed_selected(),
232 change : amt - $scope.owed_selected()
235 return {payment : amt, change : 0};
238 // calculates amount owed, billed, and paid for selected items
239 // TODO: move me to service
240 function selected_payment_info() {
241 var info = {owed : 0, billed : 0, paid : 0};
242 angular.forEach($scope.gridControls.selectedItems(), function(item) {
243 info.owed += Number(item['summary.balance_owed']) * 100;
244 info.billed += Number(item['summary.total_owed']) * 100;
245 info.paid += Number(item['summary.total_paid']) * 100;
253 $scope.pending_payment = function() {
254 return pending_payment_info().payment;
256 $scope.pending_change = function() {
257 return pending_payment_info().change;
259 $scope.owed_selected = function() {
260 return selected_payment_info().owed;
262 $scope.billed_selected = function() {
263 return selected_payment_info().billed;
265 $scope.paid_selected = function() {
266 return selected_payment_info().paid;
268 $scope.refunds_available = function() {
270 angular.forEach($scope.gridControls.allItems(), function(item) {
271 if (item['summary.balance_owed'] < 0)
272 amount += item['summary.balance_owed'] * 100;
274 return -(amount / 100);
276 $scope.invalid_check_number = function() {
277 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
280 // update the item.payment_pending value each time the user
281 // selects different transactions to pay against.
283 function() {return $scope.gridControls.selectedItems()},
284 function() {updatePendingColumn()},
288 // update the item.payment_pending for each (selected)
289 // transaction any time the user-entered payment amount is modified
290 $scope.$watch('payment_amount', updatePendingColumn);
292 // updates the value of the payment_pending column in the grid.
293 // This has to be managed manually since the display value in the grid
294 // is derived from the value on the stored item and not the contents
295 // of our local scope variables.
296 function updatePendingColumn() {
297 // reset all to zero..
298 angular.forEach($scope.gridControls.allItems(),
299 function(item) {item.payment_pending = 0});
301 var payment_amount = $scope.pending_payment();
303 var selected = $scope.gridControls.selectedItems();
304 for (var i = 0; i < selected.length; i++) { // for/break
305 var item = selected[i];
306 var owed = Number(item['summary.balance_owed']);
308 if (payment_amount > owed) {
309 // pending payment exceeds balance of current item.
310 // pay the entire item.
311 item.payment_pending = owed;
312 payment_amount -= owed;
315 // balance owed on the current item matches or exceeds
316 // the pending payment. Apply the full remainder of
317 // the payment to this item.. and we're done.
318 item.payment_pending = payment_amount;
324 // builds payment arrays ([xact_id, ammount]) for all transactions
325 // which have a pending payment amount.
326 function generatePayments() {
328 angular.forEach($scope.gridControls.selectedItems(), function(item) {
329 if (item.payment_pending == 0) return;
330 payments.push([item.id, item.payment_pending]);
335 function refreshDisplay() {
336 patronSvc.fetchUserStats();
337 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
338 $scope.payment_amount = null;
339 $scope.gridControls.refresh();
342 // generates payments, collects user note if needed, and sends payment
344 function sendPayment(note, cc_args) {
345 $scope.applyingPayment = true;
346 var make_payments = generatePayments();
347 var patron_credit = $scope.convert_to_credit.isChecked ?
348 $scope.pending_change() : 0;
349 billSvc.applyPayment($scope.payment_type,
350 make_payments, note, $scope.check_number, cc_args, patron_credit)
352 function(payment_ids) {
354 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
356 $scope.payment_type, payment_ids, make_payments, note);
362 console.error('Payment was rejected: ' + msg);
365 .finally(function() { $scope.applyingPayment = false; })
368 $scope.onReceiptOnPayChanged = function(){
369 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
372 function printReceipt(type, payment_ids, payments_made, note) {
373 var payment_blobs = [];
374 var cusr = patronSvc.current;
376 angular.forEach(payments_made, function(payment) {
377 var xact_id = payment[0];
379 // find the original transaction in the grid..
380 var xact = $scope.gridControls.allItems().filter(
381 function(item) {return item.id == xact_id})[0];
384 xact : egCore.idl.flatToNestedHash(xact),
389 console.log(js2JSON(payment_blobs[0]));
391 // page data not yet refreshed, capture data from current scope
395 previous_balance : Number($scope.summary.balance_owed()),
396 payment_total : Number($scope.payment_amount),
397 payment_applied : $scope.pending_payment(),
398 amount_voided : Number($scope.session_voided),
399 change_given : $scope.pending_change(),
400 payments : payment_blobs,
401 current_location : egCore.idl.toHash(
402 egCore.org.get(egCore.auth.user().ws_ou()))
405 // Not a good idea to use patron_stats.fines for this; it's out of date
406 print_data.patron = {
407 prefix : cusr.prefix(),
408 first_given_name : cusr.first_given_name(),
409 second_given_name : cusr.second_given_name(),
410 family_name : cusr.family_name(),
411 suffix : cusr.suffix(),
412 card : { barcode : cusr.card().barcode() },
413 expire_date : cusr.expire_date(),
414 alias : cusr.alias(),
415 has_email : Boolean(patronSvc.current.email() && patronSvc.current.email().match(/.*@.*/).length),
416 has_phone : Boolean(cusr.day_phone() || cusr.evening_phone() || cusr.other_phone())
419 print_data.new_balance = (
420 print_data.previous_balance * 100 -
421 print_data.payment_applied * 100) / 100;
423 for (var i = 0; i < $scope.receipt_count; i++) {
426 template : 'bill_payment',
432 $scope.showHistory = function() {
433 $location.path('/circ/patron/' +
434 patronSvc.current.id() + '/bill_history/transactions');
437 // For now, only adds billing to first selected item.
438 // Could do batches later if needed
439 $scope.addBilling = function(all) {
441 egBilling.showBillDialog({
442 xact : egCore.idl.flatToNestedHash(all[0]),
443 patron : $scope.patron()
444 }).then(refreshDisplay);
448 $scope.showBillDialog = function($event) {
449 egBilling.showBillDialog({
450 patron : $scope.patron()
451 }).then(refreshDisplay);
454 // Select refunds adds all refunds to the existing selection.
455 // It does not /only/ select refunds
456 $scope.selectRefunds = function() {
457 var ids = $scope.gridControls.selectedItems().map(
458 function(i) { return i.id });
459 angular.forEach($scope.gridControls.allItems(), function(item) {
460 if (Number(item['summary.balance_owed']) < 0)
463 $scope.gridControls.selectItems(ids);
467 // determine on initial page load when all of the grid rows should
469 var selectOnLoad = true;
470 billSvc.fetchBillSettings().then(function(s) {
471 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
472 $scope.focus_payment = false; // de-focus the payment box
473 $scope.gridControls.focusRowSelector = true;
474 selectOnLoad = false;
475 // if somehow the grid finishes rendering before our settings
476 // arrive, manually de-select everything.
477 $scope.gridControls.selectItems([]);
479 if (s['ui.circ.billing.amount_warn']) {
480 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
482 if (s['ui.circ.billing.amount_limit']) {
483 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
485 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
486 $scope.disable_auto_print = Boolean(
487 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
490 if (s['circ.disable_patron_credit']) {
491 $scope.disablePatronCredit = true;
495 $scope.gridControls.allItemsRetrieved = function() {
497 selectOnLoad = false; // only for initial controller load.
498 // select all non-refund items
499 $scope.gridControls.selectItems(
500 $scope.gridControls.allItems()
501 .filter(function(i) {return i['summary.balance_owed'] > 0})
502 .map(function(i){return i.id})
509 $scope.printBills = function(selected) {
510 if (!selected.length) return;
511 // bills print receipt assumes nested hashes, but our grid
512 // stores flattener data. Fetch the selected xacts as
513 // fleshed pcrud objects and hashify.
514 // (Consider an alternate approach..)
515 var ids = selected.map(function(t){ return t.id });
517 egCore.pcrud.search('mbt',
519 {flesh : 5, flesh_fields : {
520 'mbt' : ['summary', 'circulation'],
521 'circ' : ['target_copy'],
522 'acp' : ['call_number'],
524 'bre' : ['simple_record']
527 {authoritative : true}
532 template : 'bills_current',
534 transactions : xacts,
535 current_location : egCore.idl.toHash(
536 egCore.org.get(egCore.auth.user().ws_ou()))
543 billing_total : xact.billing_total(),
544 billings : xact.billings(),
545 grocery : xact.grocery(),
547 payment_total : xact.payment_total(),
548 payments : xact.payments(),
549 summary : egCore.idl.toHash(xact.summary()),
550 unrecovered : xact.unrecovered(),
551 xact_finish : xact.xact_finish(),
552 xact_start : xact.xact_start(),
554 if (xact.circulation()) {
555 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
556 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
563 $scope.applyPayment = function() {
565 if ($scope.payment_amount > $scope.max_amount ) {
567 egCore.strings.PAYMENT_OVER_MAX,
568 { max_amount : ''+$scope.max_amount,
570 $scope.payment_amount = 0;
577 verify_payment_amount().then(
578 function() { // amount confirmed
579 add_payment_note().then(function(pay_note) {
580 add_cc_args().then(function(cc_args) {
581 var note_text = pay_note ? pay_note.value || '' : null;
582 sendPayment(note_text, cc_args);
586 function() { // amount rejected
587 console.warn('payment amount rejected');
588 $scope.payment_amount = 0;
593 function verify_payment_amount() {
594 if ($scope.payment_amount < $scope.warn_amount)
597 return egConfirmDialog.open(
598 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE,
599 egCore.strings.PAYMENT_WARN_AMOUNT,
600 {payment_amount : ''+$scope.payment_amount}
604 function add_payment_note() {
605 if (!$scope.annotate_payment) return $q.when();
606 return egPromptDialog.open(
607 egCore.strings.ANNOTATE_PAYMENT_MSG, '').result;
610 function add_cc_args() {
611 if ($scope.payment_type != 'credit_card_payment')
614 return $uibModal.open({
615 templateUrl : './circ/patron/t_cc_payment_dialog',
618 '$scope','$uibModalInstance',
619 function($scope , $uibModalInstance) {
623 where_process : '1', // internal=1 ; external=0
624 type : 'VISA', // external only
625 billing_first : patronSvc.current.first_given_name(),
626 billing_last : patronSvc.current.family_name()
630 var addr = patronSvc.current.billing_address() ||
631 patronSvc.current.mailing_address();
633 var cc = $scope.context.cc;
634 cc.billing_address = addr.street1() +
635 (addr.street2() ? ' ' + addr.street2() : '');
636 cc.billing_city = addr.city();
637 cc.billing_state = addr.state();
638 cc.billing_zip = addr.post_code();
641 $scope.ok = function() {
642 // CC payment form is not a <form>,
643 // so apply validation manually.
644 if ( $scope.context.cc.where_process == 0 &&
645 !$scope.context.cc.approval_code)
648 $uibModalInstance.close($scope.context.cc);
651 $scope.cancel = function() {
652 $uibModalInstance.dismiss();
659 $scope.voidAllBillings = function(items) {
663 angular.forEach(items, function(item) {
665 billSvc.fetchBills(item.id).then(function(bills) {
666 angular.forEach(bills, function(b) {
667 if (b.voided() != 't') {
668 cents += b.amount() * 100;
669 bill_ids.push(b.id())
673 if (bill_ids.length == 0) {
682 $q.all(promises).then(function(){
683 egCore.audio.play('warning.circ.void_billings_confirmation');
684 egConfirmDialog.open(
685 egCore.strings.CONFIRM_VOID_BILLINGS, '',
686 { billIds : ''+bill_ids,
687 amount : ''+(cents/100),
689 billSvc.voidBills(bill_ids).then(function() {
690 $scope.session_voided =
691 ($scope.session_voided * 100 + cents) / 100;
700 $scope.adjustToZero = function(items) {
701 if (items.length == 0) return;
703 var ids = items.map(function(item) {return item.id});
705 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
706 egConfirmDialog.open(
707 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
710 billSvc.adjustBillsToZero(ids).then(function() {
719 // note this is functionally equivalent to selecting a neg. transaction
720 // then clicking Apply Payment -- this just adds a speed bump (ditto
722 $scope.refundXact = function(all) {
723 var items = all.filter(function(item) {
724 return item['summary.balance_owed'] < 0
727 if (items.length == 0) return;
729 var ids = items.map(function(item) {return item.id});
731 egCore.audio.play('warning.circ.refund_confirmation');
732 egConfirmDialog.open(
733 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
736 // reset the received payment amount. this ensures
737 // we're not mingling payments with refunds.
738 $scope.payment_amount = 0;
744 // direct the user to the transaction details page
745 $scope.showFullDetails = function(all) {
747 $location.path('/circ/patron/' +
748 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
751 $scope.activateBill = function(xact) {
752 $scope.showFullDetails([xact]);
758 * Displays details of a single transaction
760 .controller('XactDetailsCtrl',
761 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
762 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
764 $scope.initTab('bills', $routeParams.id);
765 var xact_id = $routeParams.xact_id;
766 $scope.xact_tab = $routeParams.xact_tab;
768 var xactGrid = $scope.xactGridControls = {
769 setQuery : function() { return {xact : xact_id} },
770 setSort : function() { return ['billing_ts'] }
773 var paymentGrid = $scope.paymentGridControls = {
774 setQuery : function() { return {xact : xact_id} },
775 setSort : function() { return ['payment_ts'] }
779 $scope.voidBillings = function(bill_list) {
782 angular.forEach(bill_list, function(b) {
783 if (b.voided != 't') {
784 cents += b.amount * 100;
789 if (bill_ids.length == 0) {
794 egCore.audio.play('warning.circ.void_billings_confirmation');
795 egConfirmDialog.open(
796 egCore.strings.CONFIRM_VOID_BILLINGS, '',
797 { billIds : ''+bill_ids,
798 amount : ''+(cents/100),
800 billSvc.voidBills(bill_ids).then(function() {
801 // TODO? $scope.session_voided = ...
803 // refresh bills and summary data
804 // note: no need to update payments
805 patronSvc.fetchUserStats();
807 egBilling.fetchXact(xact_id).then(function(xact) {
818 // batch-edit billing and payment notes, depending on 'type'
819 function editNotes(selected, type) {
820 var notes = selected.map(function(b){ return b.note }).join(',');
821 var ids = selected.map(function(b){ return b.id });
823 // show the note edit prompt
825 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
827 ok : function(value) {
829 var func = 'updateBillNotes';
830 if (type == 'payment') func = 'updatePaymentNotes';
832 billSvc[func](value, ids).then(function() {
833 if (type == 'payment') {
834 paymentGrid.refresh();
844 $scope.editBillNotes = function(selected) {
845 editNotes(selected, 'bill');
848 $scope.editPaymentNotes = function(selected) {
849 editNotes(selected, 'payment');
852 // -- retrieve our data
853 if ($scope.xact_tab == 'statement') {
854 //fetch combined billing statement data
855 billSvc.fetchStatement(xact_id).then(function(statement) {
856 //console.log(statement);
857 $scope.statement_data = statement;
860 $scope.total_circs = 0; // start with 0 instead of undefined
861 egBilling.fetchXact(xact_id).then(function(xact) {
864 var copyId = xact.circulation().target_copy().id();
866 egCore.pcrud.search('circbyyr',
867 {copy : copyId}, null, {atomic : true})
868 .then(function(counts) {
869 angular.forEach(counts, function(count) {
870 circ_count += Number(count.count());
872 $scope.total_circs = circ_count;
874 // set the title. only needs to be done on initial page load
875 if (xact.circulation()) {
876 if (xact.circulation().target_copy().call_number().id() == -1) {
877 $scope.title = xact.circulation().target_copy().dummy_title();
879 // TODO: shared bib service?
880 $scope.title = xact.circulation().target_copy()
881 .call_number().record().simple_record().title();
882 $scope.title_id = xact.circulation().target_copy()
883 .call_number().record().id();
890 .controller('BillHistoryCtrl',
891 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
892 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
894 $scope.initTab('bills', $routeParams.id);
895 billSvc.userId = $routeParams.id;
896 $scope.bill_tab = $routeParams.history_tab;
899 // link page controller actions defined by sub-controllers here
902 var start = new Date(); // now - 1 year
903 start.setFullYear(start.getFullYear() - 1),
906 xact_finish : new Date()
909 $scope.date_range = function() {
910 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
911 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
912 var today = new Date().toISOString().replace(/T.*/,'');
913 if (end == today) end = 'now';
919 .controller('BillXactHistoryCtrl',
920 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
921 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
923 // generate a grid query with the current date widget values.
924 function current_grid_query() {
927 {'summary.balance_owed' : {'<>' : 0}},
928 {'summary.last_payment_ts' : {'<>' : null}}
930 xact_start : {between : $scope.date_range()},
935 $scope.gridControls = {
936 selectedItems : function(){return []},
937 activateItem : function(item) {
938 $scope.showFullDetails([item]);
940 // this sets the query on page load
941 setQuery : current_grid_query
944 $scope.actions.apply_date_range = function() {
945 // tells the grid to re-draw itself with the new query
946 $scope.gridControls.setQuery(current_grid_query());
949 // TODO; move me to service
950 function selected_payment_info() {
951 var info = {owed : 0, billed : 0, paid : 0};
952 angular.forEach($scope.gridControls.selectedItems(), function(item) {
953 info.owed += Number(item['summary.balance_owed']) * 100;
954 info.billed += Number(item['summary.total_owed']) * 100;
955 info.paid += Number(item['summary.total_paid']) * 100;
963 $scope.totals.selected_billed = function() {
964 return selected_payment_info().billed;
966 $scope.totals.selected_paid = function() {
967 return selected_payment_info().paid;
970 $scope.showFullDetails = function(all) {
972 $location.path('/circ/patron/' +
973 patronSvc.current.id() + '/bill/' + all[0].id + '/statement');
976 // For now, only adds billing to first selected item.
977 // Could do batches later if needed
978 $scope.addBilling = function(all) {
980 egBilling.showBillDialog({
981 xact : egCore.idl.flatToNestedHash(all[0]),
982 patron : $scope.patron()
984 $scope.gridControls.refresh();
985 patronSvc.fetchUserStats();
990 $scope.printBills = function(selected) { // FIXME: refactor me
991 if (!selected.length) return;
992 // bills print receipt assumes nested hashes, but our grid
993 // stores flattener data. Fetch the selected xacts as
994 // fleshed pcrud objects and hashify.
995 // (Consider an alternate approach..)
996 var ids = selected.map(function(t){ return t.id });
998 egCore.pcrud.search('mbt',
1000 {flesh : 5, flesh_fields : {
1001 'mbt' : ['summary', 'circulation'],
1002 'circ' : ['target_copy'],
1003 'acp' : ['call_number'],
1005 'bre' : ['simple_record']
1008 {authoritative : true}
1011 egCore.print.print({
1012 context : 'receipt',
1013 template : 'bills_historical',
1015 transactions : xacts,
1016 current_location : egCore.idl.toHash(
1017 egCore.org.get(egCore.auth.user().ws_ou()))
1024 billing_total : xact.billing_total(),
1025 billings : xact.billings(),
1026 grocery : xact.grocery(),
1028 payment_total : xact.payment_total(),
1029 payments : xact.payments(),
1030 summary : egCore.idl.toHash(xact.summary()),
1031 unrecovered : xact.unrecovered(),
1032 xact_finish : xact.xact_finish(),
1033 xact_start : xact.xact_start(),
1035 if (xact.circulation()) {
1036 newXact.copy_barcode = xact.circulation().target_copy().barcode(),
1037 newXact.title = xact.circulation().target_copy().call_number().record().simple_record().title()
1039 xacts.push(newXact);
1045 .controller('BillPaymentHistoryCtrl',
1046 ['$scope','$q','egCore','patronSvc','billSvc','$location',
1047 function($scope, $q , egCore , patronSvc , billSvc , $location) {
1049 // generate a grid query with the current date widget values.
1050 function current_grid_query() {
1052 'payment_ts' : {between : $scope.date_range()},
1053 'xact.usr' : billSvc.userId
1057 $scope.gridControls = {
1058 selectedItems : function(){return []},
1059 activateItem : function(item) {
1060 $scope.showFullDetails([item]);
1062 setSort : function() {
1063 return [{'payment_ts' : 'DESC'}, 'id'];
1065 setQuery : current_grid_query
1068 $scope.actions.apply_date_range = function() {
1069 // tells the grid to re-draw itself with the new query
1070 $scope.gridControls.setQuery(current_grid_query());
1073 $scope.showFullDetails = function(all) {
1075 $location.path('/circ/patron/' +
1076 patronSvc.current.id() + '/bill/' + all[0]['xact.id'] + '/statement');
1079 $scope.totals.selected_paid = function() {
1081 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
1082 paid += Number(payment.amount) * 100;