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) {
28 return egCore.net.request(
30 'open-ils.circ.money.payment',
31 egCore.auth.token(), {
32 userid : service.userId,
39 patronSvc.current.last_xact_id()
40 ).then(function(resp) {
41 console.debug('payments: ' + js2JSON(resp));
42 var total = 0; angular.forEach(payments,function(p) { total += p[1]; });
45 case 'cash_payment' : msg = egCore.strings.EG_WORK_LOG_CASH_PAYMENT; break;
46 case 'check_payment' : msg = egCore.strings.EG_WORK_LOG_CHECK_PAYMENT; break;
47 case 'credit_card_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_CARD_PAYMENT; break;
48 case 'credit_payment' : msg = egCore.strings.EG_WORK_LOG_CREDIT_PAYMENT; break;
49 case 'work_payment' : msg = egCore.strings.EG_WORK_LOG_WORK_PAYMENT; break;
50 case 'forgive_payment' : msg = egCore.strings.EG_WORK_LOG_FORGIVE_PAYMENT; break;
51 case 'goods_payment' : msg = egCore.strings.EG_WORK_LOG_GOODS_PAYMENT; break;
55 'action' : 'paid_bill',
56 'patron_id' : service.userId,
57 'total_amount' : total
60 if (evt = egCore.evt.parse(resp))
63 // payment API returns the update xact id so we can track it
64 // for future payments without having to refresh the user.
65 patronSvc.current.last_xact_id(resp.last_xact_id);
70 service.fetchBills = function(xact_id) {
72 return egCore.pcrud.search('mb',
73 {xact : xact_id}, null,
74 {authoritative : true}
76 function() {return bills},
78 function(bill) {bills.push(bill); return bill}
82 // TODO: no longer needed?
83 service.fetchPayments = function(xact_id) {
84 return egCore.net.request(
86 'open-ils.circ.money.payment.retrieve.all.authoritative',
87 egCore.auth.token(), xact_id
91 service.voidBills = function(bill_ids) {
92 return egCore.net.requestWithParamList(
94 'open-ils.circ.money.billing.void',
95 [egCore.auth.token()].concat(bill_ids)
96 ).then(function(resp) {
97 if (evt = egCore.evt.parse(resp)) return alert(evt);
102 service.adjustBillsToZero = function(bill_ids) {
103 return egCore.net.request(
105 'open-ils.circ.money.billable_xact.adjust_to_zero',
108 ).then(function(resp) {
109 if (evt = egCore.evt.parse(resp)) return alert(evt);
114 service.updateBillNotes = function(note, ids) {
115 return egCore.net.requestWithParamList(
117 'open-ils.circ.money.billing.note.edit',
118 [egCore.auth.token(), note].concat(ids)
119 ).then(function(resp) {
120 if (evt = egCore.evt.parse(resp)) return alert(evt);
125 service.updatePaymentNotes = function(note, ids) {
126 return egCore.net.requestWithParamList(
128 'open-ils.circ.money.payment.note.edit',
129 [egCore.auth.token(), note].concat(ids)
130 ).then(function(resp) {
131 if (evt = egCore.evt.parse(resp)) return alert(evt);
143 .controller('PatronBillsCtrl',
144 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
145 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
147 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
148 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
151 $scope.initTab('bills', $routeParams.id);
152 billSvc.userId = $routeParams.id;
154 // set up some defaults
155 $scope.check_number = null;
156 $scope.payment_amount = null;
157 $scope.session_voided = 0;
158 $scope.payment_type = 'cash_payment';
159 $scope.focus_payment = true;
160 $scope.annotate_payment = false;
161 $scope.receipt_count = 1;
162 $scope.receipt_on_pay = false;
163 $scope.warn_amount = 1000;
164 $scope.max_amount = 100000;
165 $scope.amount_verified = false;
166 $scope.disable_auto_print = false;
168 // pre-define list-returning funcs in case we access them
169 // before the grid instantiates
170 $scope.gridControls = {
171 focusRowSelector : false,
172 selectedItems : function(){return []},
173 allItems : function(){return []},
174 itemRetrieved : function(item) {
175 item.payment_pending = 0;
177 activateItem : function(item) {
178 $scope.showFullDetails([item]);
180 setQuery : function() {
182 usr : billSvc.userId,
184 'summary.balance_owed' : {'<>' : 0}
187 setSort : function() {
188 return ['xact_start'];
192 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
194 // given a payment amount, determines how much of that is applied
195 // to selected transactions and how much is left over (change).
196 function pending_payment_info() {
197 var amt = $scope.payment_amount || 0;
198 if (amt >= $scope.owed_selected()) {
200 payment : $scope.owed_selected(),
201 change : amt - $scope.owed_selected()
204 return {payment : amt, change : 0};
207 // calculates amount owed, billed, and paid for selected items
208 // TODO: move me to service
209 function selected_payment_info() {
210 var info = {owed : 0, billed : 0, paid : 0};
211 angular.forEach($scope.gridControls.selectedItems(), function(item) {
212 info.owed += Number(item['summary.balance_owed']) * 100;
213 info.billed += Number(item['summary.total_owed']) * 100;
214 info.paid += Number(item['summary.total_paid']) * 100;
222 $scope.pending_payment = function() {
223 return pending_payment_info().payment;
225 $scope.pending_change = function() {
226 return pending_payment_info().change;
228 $scope.owed_selected = function() {
229 return selected_payment_info().owed;
231 $scope.billed_selected = function() {
232 return selected_payment_info().billed;
234 $scope.paid_selected = function() {
235 return selected_payment_info().paid;
237 $scope.refunds_available = function() {
239 angular.forEach($scope.gridControls.allItems(), function(item) {
240 if (item['summary.balance_owed'] < 0)
241 amount += item['summary.balance_owed'] * 100;
243 return -(amount / 100);
245 $scope.invalid_check_number = function() {
246 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
249 // update the item.payment_pending value each time the user
250 // selects different transactions to pay against.
252 function() {return $scope.gridControls.selectedItems()},
253 function() {updatePendingColumn()},
257 // update the item.payment_pending for each (selected)
258 // transaction any time the user-entered payment amount is modified
259 $scope.$watch('payment_amount', updatePendingColumn);
261 // updates the value of the payment_pending column in the grid.
262 // This has to be managed manually since the display value in the grid
263 // is derived from the value on the stored item and not the contents
264 // of our local scope variables.
265 function updatePendingColumn() {
266 // reset all to zero..
267 angular.forEach($scope.gridControls.allItems(),
268 function(item) {item.payment_pending = 0});
270 var payment_amount = $scope.pending_payment();
272 var selected = $scope.gridControls.selectedItems();
273 for (var i = 0; i < selected.length; i++) { // for/break
274 var item = selected[i];
275 var owed = Number(item['summary.balance_owed']);
277 if (payment_amount > owed) {
278 // pending payment exceeds balance of current item.
279 // pay the entire item.
280 item.payment_pending = owed;
281 payment_amount -= owed;
284 // balance owed on the current item matches or exceeds
285 // the pending payment. Apply the full remainder of
286 // the payment to this item.. and we're done.
287 item.payment_pending = payment_amount;
293 // builds payment arrays ([xact_id, ammount]) for all transactions
294 // which have a pending payment amount.
295 function generatePayments() {
297 angular.forEach($scope.gridControls.selectedItems(), function(item) {
298 if (item.payment_pending == 0) return;
299 payments.push([item.id, item.payment_pending]);
304 function refreshDisplay() {
305 patronSvc.fetchUserStats();
306 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
307 $scope.payment_amount = null;
308 $scope.gridControls.refresh();
311 // generates payments, collects user note if needed, and sends payment
313 function sendPayment(note) {
314 var make_payments = generatePayments();
315 billSvc.applyPayment(
316 $scope.payment_type, make_payments, note, $scope.check_number)
317 .then(function(payment_ids) {
319 if (!$scope.disable_auto_print && $scope.receipt_on_pay) {
321 $scope.payment_type, payment_ids, make_payments, note);
328 function printReceipt(type, payment_ids, payments_made, note) {
329 var payment_blobs = [];
330 angular.forEach(payments_made, function(payment) {
331 var xact_id = payment[0];
333 // find the original transaction in the grid..
334 var xact = $scope.gridControls.allItems().filter(
335 function(item) {return item.id == xact_id})[0];
338 xact : egCore.idl.flatToNestedHash(xact),
343 console.log(js2JSON(payment_blobs[0]));
345 // page data not yet refreshed, capture data from current scope
349 previous_balance : Number($scope.summary.balance_owed()),
350 payment_total : Number($scope.payment_amount),
351 payment_applied : $scope.pending_payment(),
352 amount_voided : Number($scope.session_voided),
353 change_given : $scope.pending_change(),
354 payments : payment_blobs,
355 current_location : egCore.idl.toHash(
356 egCore.org.get(egCore.auth.user().ws_ou()))
359 print_data.new_balance = (
360 print_data.previous_balance * 100 -
361 print_data.payment_applied * 100) / 100;
363 for (var i = 0; i < $scope.receipt_count; i++) {
366 template : 'bill_payment',
372 $scope.showHistory = function() {
373 $location.path('/circ/patron/' +
374 patronSvc.current.id() + '/bill_history/transactions');
377 // For now, only adds billing to first selected item.
378 // Could do batches later if needed
379 $scope.addBilling = function(all) {
381 egBilling.showBillDialog({
382 xact : egCore.idl.flatToNestedHash(all[0]),
383 patron : $scope.patron()
384 }).then(refreshDisplay);
388 $scope.showBillDialog = function($event) {
389 egBilling.showBillDialog({
390 patron : $scope.patron()
391 }).then(refreshDisplay);
394 // Select refunds adds all refunds to the existing selection.
395 // It does not /only/ select refunds
396 $scope.selectRefunds = function() {
397 var ids = $scope.gridControls.selectedItems().map(
398 function(i) { return i.id });
399 angular.forEach($scope.gridControls.allItems(), function(item) {
400 if (Number(item['summary.balance_owed']) < 0)
403 $scope.gridControls.selectItems(ids);
407 // determine on initial page load when all of the grid rows should
409 var selectOnLoad = true;
410 billSvc.fetchBillSettings().then(function(s) {
411 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
412 $scope.focus_payment = false; // de-focus the payment box
413 $scope.gridControls.focusRowSelector = true;
414 selectOnLoad = false;
415 // if somehow the grid finishes rendering before our settings
416 // arrive, manually de-select everything.
417 $scope.gridControls.selectItems([]);
419 if (s['ui.circ.billing.amount_warn']) {
420 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
422 if (s['ui.circ.billing.amount_limit']) {
423 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
425 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
426 $scope.disable_auto_print = Boolean(
427 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
432 $scope.gridControls.allItemsRetrieved = function() {
434 selectOnLoad = false; // only for initial controller load.
435 // select all non-refund items
436 $scope.gridControls.selectItems(
437 $scope.gridControls.allItems()
438 .filter(function(i) {return i['summary.balance_owed'] > 0})
439 .map(function(i){return i.id})
446 $scope.printBills = function(selected) {
447 if (!selected.length) return;
448 // bills print receipt assumes nested hashes, but our grid
449 // stores flattener data. Fetch the selected xacts as
450 // fleshed pcrud objects and hashify.
451 // (Consider an alternate approach..)
452 var ids = selected.map(function(t){ return t.id });
454 egCore.pcrud.search('mbt',
456 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
457 {authoritative : true}
462 template : 'bills_current',
464 transactions : xacts,
465 current_location : egCore.idl.toHash(
466 egCore.org.get(egCore.auth.user().ws_ou()))
472 xacts.push(egCore.idl.toHash(xact));
477 $scope.applyPayment = function() {
479 if ($scope.payment_amount > $scope.max_amount ) {
481 egCore.strings.PAYMENT_OVER_MAX,
482 { max_amount : ''+$scope.max_amount,
484 $scope.payment_amount = 0;
491 if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
492 egConfirmDialog.open(
493 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
494 { payment_amount : ''+$scope.payment_amount,
496 $scope.amount_verfied = true;
497 $scope.applyPayment();
499 cancel : function() {
500 $scope.payment_amount = 0;
507 $scope.amount_verfied = false;
509 if ($scope.annotate_payment) {
511 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
512 {ok : function(value) {sendPayment(value)}}
519 $scope.voidAllBillings = function(items) {
520 angular.forEach(items, function(item) {
522 billSvc.fetchBills(item.id).then(function(bills) {
525 angular.forEach(bills, function(b) {
526 if (b.voided() != 't') {
527 cents += b.amount() * 100;
528 bill_ids.push(b.id())
532 $scope.session_voided =
533 ($scope.session_voided * 100 + cents) / 100;
535 if (bill_ids.length == 0) {
540 // TODO: alert of pending voiding
542 billSvc.voidBills(bill_ids).then(function() {
549 $scope.adjustToZero = function(items) {
550 if (items.length == 0) return;
552 var ids = items.map(function(item) {return item.id});
554 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
555 egConfirmDialog.open(
556 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
559 billSvc.adjustBillsToZero(ids).then(function() {
568 // note this is functionally equivalent to selecting a neg. transaction
569 // then clicking Apply Payment -- this just adds a speed bump (ditto
571 $scope.refundXact = function(all) {
572 var items = all.filter(function(item) {
573 return item['summary.balance_owed'] < 0
576 if (items.length == 0) return;
578 var ids = items.map(function(item) {return item.id});
580 egCore.audio.play('warning.circ.refund_confirmation');
581 egConfirmDialog.open(
582 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
585 // reset the received payment amount. this ensures
586 // we're not mingling payments with refunds.
587 $scope.payment_amount = 0;
593 // direct the user to the transaction details page
594 $scope.showFullDetails = function(all) {
596 $location.path('/circ/patron/' +
597 patronSvc.current.id() + '/bill/' + all[0].id);
600 $scope.activateBill = function(xact) {
601 $scope.showFullDetails([xact]);
607 * Displays details of a single transaction
609 .controller('XactDetailsCtrl',
610 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
611 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
613 $scope.initTab('bills', $routeParams.id);
614 var xact_id = $routeParams.xact_id;
616 var xactGrid = $scope.xactGridControls = {
617 setQuery : function() { return {xact : xact_id} },
618 setSort : function() { return ['billing_ts'] }
621 var paymentGrid = $scope.paymentGridControls = {
622 setQuery : function() { return {xact : xact_id} },
623 setSort : function() { return ['payment_ts'] }
627 $scope.voidBillings = function(bill_list) {
629 angular.forEach(bill_list, function(b) {
630 if (b.voided != 't') bill_ids.push(b.id);
633 if (bill_ids.length == 0) {
638 billSvc.voidBills(bill_ids).then(function() {
640 // refresh bills and summary data
641 // note: no need to update payments
642 patronSvc.fetchUserStats();
644 egBilling.fetchXact(xact_id).then(function(xact) {
652 // batch-edit billing and payment notes, depending on 'type'
653 function editNotes(selected, type) {
654 var notes = selected.map(function(b){ return b.note }).join(',');
655 var ids = selected.map(function(b){ return b.id });
657 // show the note edit prompt
659 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
661 ok : function(value) {
663 var func = 'updateBillNotes';
664 if (type == 'payment') func = 'updatePaymentNotes';
666 billSvc[func](value, ids).then(function() {
667 if (type == 'payment') {
668 paymentGrid.refresh();
678 $scope.editBillNotes = function(selected) {
679 editNotes(selected, 'bill');
682 $scope.editPaymentNotes = function(selected) {
683 editNotes(selected, 'payment');
686 // -- retrieve our data
687 $scope.total_circs = 0; // start with 0 instead of undefined
688 egBilling.fetchXact(xact_id).then(function(xact) {
691 var copyId = xact.circulation().target_copy().id();
693 egCore.pcrud.search('circbyyr',
694 {copy : copyId}, null, {atomic : true})
695 .then(function(counts) {
696 angular.forEach(counts, function(count) {
697 circ_count += Number(count.count());
699 $scope.total_circs = circ_count;
701 // set the title. only needs to be done on initial page load
702 if (xact.circulation()) {
703 if (xact.circulation().target_copy().call_number().id() == -1) {
704 $scope.title = xact.circulation().target_copy().dummy_title();
706 // TODO: shared bib service?
707 $scope.title = xact.circulation().target_copy()
708 .call_number().record().simple_record().title();
709 $scope.title_id = xact.circulation().target_copy()
710 .call_number().record().id();
717 .controller('BillHistoryCtrl',
718 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
719 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
721 $scope.initTab('bills', $routeParams.id);
722 billSvc.userId = $routeParams.id;
723 $scope.bill_tab = $routeParams.history_tab;
726 // link page controller actions defined by sub-controllers here
729 var start = new Date(); // now - 1 year
730 start.setFullYear(start.getFullYear() - 1),
733 xact_finish : new Date()
736 $scope.date_range = function() {
737 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
738 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
739 var today = new Date().toISOString().replace(/T.*/,'');
740 if (end == today) end = 'now';
746 .controller('BillXactHistoryCtrl',
747 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
748 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
750 // generate a grid query with the current date widget values.
751 function current_grid_query() {
754 {'summary.balance_owed' : {'<>' : 0}},
755 {'summary.last_payment_ts' : {'<>' : null}}
757 xact_start : {between : $scope.date_range()},
762 $scope.gridControls = {
763 selectedItems : function(){return []},
764 activateItem : function(item) {
765 $scope.showFullDetails([item]);
767 // this sets the query on page load
768 setQuery : current_grid_query
771 $scope.actions.apply_date_range = function() {
772 // tells the grid to re-draw itself with the new query
773 $scope.gridControls.setQuery(current_grid_query());
776 // TODO; move me to service
777 function selected_payment_info() {
778 var info = {owed : 0, billed : 0, paid : 0};
779 angular.forEach($scope.gridControls.selectedItems(), function(item) {
780 info.owed += Number(item['summary.balance_owed']) * 100;
781 info.billed += Number(item['summary.total_owed']) * 100;
782 info.paid += Number(item['summary.total_paid']) * 100;
790 $scope.totals.selected_billed = function() {
791 return selected_payment_info().billed;
793 $scope.totals.selected_paid = function() {
794 return selected_payment_info().paid;
797 $scope.showFullDetails = function(all) {
799 $location.path('/circ/patron/' +
800 patronSvc.current.id() + '/bill/' + all[0].id);
803 // For now, only adds billing to first selected item.
804 // Could do batches later if needed
805 $scope.addBilling = function(all) {
807 egBilling.showBillDialog({
808 xact : egCore.idl.flatToNestedHash(all[0]),
809 patron : $scope.patron()
811 $scope.gridControls.refresh();
812 patronSvc.fetchUserStats();
817 $scope.printBills = function(selected) { // FIXME: refactor me
818 if (!selected.length) return;
819 // bills print receipt assumes nested hashes, but our grid
820 // stores flattener data. Fetch the selected xacts as
821 // fleshed pcrud objects and hashify.
822 // (Consider an alternate approach..)
823 var ids = selected.map(function(t){ return t.id });
825 egCore.pcrud.search('mbt',
827 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
828 {authoritative : true}
833 template : 'bills_historical',
835 transactions : xacts,
836 current_location : egCore.idl.toHash(
837 egCore.org.get(egCore.auth.user().ws_ou()))
843 xacts.push(egCore.idl.toHash(xact));
851 .controller('BillPaymentHistoryCtrl',
852 ['$scope','$q','egCore','patronSvc','billSvc','$location',
853 function($scope, $q , egCore , patronSvc , billSvc , $location) {
855 // generate a grid query with the current date widget values.
856 function current_grid_query() {
858 'payment_ts' : {between : $scope.date_range()},
859 'xact.usr' : billSvc.userId
863 $scope.gridControls = {
864 selectedItems : function(){return []},
865 activateItem : function(item) {
866 $scope.showFullDetails([item]);
868 setSort : function() {
869 return [{'payment_ts' : 'DESC'}, 'id'];
871 setQuery : current_grid_query
874 $scope.actions.apply_date_range = function() {
875 // tells the grid to re-draw itself with the new query
876 $scope.gridControls.setQuery(current_grid_query());
879 $scope.showFullDetails = function(all) {
881 $location.path('/circ/patron/' +
882 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
885 $scope.totals.selected_paid = function() {
887 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
888 paid += Number(payment.amount) * 100;