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 = { isChecked: false };
163 $scope.warn_amount = 1000;
164 $scope.max_amount = 100000;
165 $scope.amount_verified = false;
166 $scope.disable_auto_print = false;
168 // check receipt_on_pay setting default persisted
169 egCore.hatch.getItem('circ.bills.receiptonpay')
170 .then(function(rcptOnPay){
171 if (rcptOnPay) $scope.receipt_on_pay.isChecked = rcptOnPay;
174 // pre-define list-returning funcs in case we access them
175 // before the grid instantiates
176 $scope.gridControls = {
177 focusRowSelector : false,
178 selectedItems : function(){return []},
179 allItems : function(){return []},
180 itemRetrieved : function(item) {
181 item.payment_pending = 0;
183 activateItem : function(item) {
184 $scope.showFullDetails([item]);
186 setQuery : function() {
188 usr : billSvc.userId,
190 'summary.balance_owed' : {'<>' : 0}
193 setSort : function() {
194 return ['xact_start'];
198 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
200 // given a payment amount, determines how much of that is applied
201 // to selected transactions and how much is left over (change).
202 function pending_payment_info() {
203 var amt = $scope.payment_amount || 0;
204 if (amt >= $scope.owed_selected()) {
206 payment : $scope.owed_selected(),
207 change : amt - $scope.owed_selected()
210 return {payment : amt, change : 0};
213 // calculates amount owed, billed, and paid for selected items
214 // TODO: move me to service
215 function selected_payment_info() {
216 var info = {owed : 0, billed : 0, paid : 0};
217 angular.forEach($scope.gridControls.selectedItems(), function(item) {
218 info.owed += Number(item['summary.balance_owed']) * 100;
219 info.billed += Number(item['summary.total_owed']) * 100;
220 info.paid += Number(item['summary.total_paid']) * 100;
228 $scope.pending_payment = function() {
229 return pending_payment_info().payment;
231 $scope.pending_change = function() {
232 return pending_payment_info().change;
234 $scope.owed_selected = function() {
235 return selected_payment_info().owed;
237 $scope.billed_selected = function() {
238 return selected_payment_info().billed;
240 $scope.paid_selected = function() {
241 return selected_payment_info().paid;
243 $scope.refunds_available = function() {
245 angular.forEach($scope.gridControls.allItems(), function(item) {
246 if (item['summary.balance_owed'] < 0)
247 amount += item['summary.balance_owed'] * 100;
249 return -(amount / 100);
251 $scope.invalid_check_number = function() {
252 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
255 // update the item.payment_pending value each time the user
256 // selects different transactions to pay against.
258 function() {return $scope.gridControls.selectedItems()},
259 function() {updatePendingColumn()},
263 // update the item.payment_pending for each (selected)
264 // transaction any time the user-entered payment amount is modified
265 $scope.$watch('payment_amount', updatePendingColumn);
267 // updates the value of the payment_pending column in the grid.
268 // This has to be managed manually since the display value in the grid
269 // is derived from the value on the stored item and not the contents
270 // of our local scope variables.
271 function updatePendingColumn() {
272 // reset all to zero..
273 angular.forEach($scope.gridControls.allItems(),
274 function(item) {item.payment_pending = 0});
276 var payment_amount = $scope.pending_payment();
278 var selected = $scope.gridControls.selectedItems();
279 for (var i = 0; i < selected.length; i++) { // for/break
280 var item = selected[i];
281 var owed = Number(item['summary.balance_owed']);
283 if (payment_amount > owed) {
284 // pending payment exceeds balance of current item.
285 // pay the entire item.
286 item.payment_pending = owed;
287 payment_amount -= owed;
290 // balance owed on the current item matches or exceeds
291 // the pending payment. Apply the full remainder of
292 // the payment to this item.. and we're done.
293 item.payment_pending = payment_amount;
299 // builds payment arrays ([xact_id, ammount]) for all transactions
300 // which have a pending payment amount.
301 function generatePayments() {
303 angular.forEach($scope.gridControls.selectedItems(), function(item) {
304 if (item.payment_pending == 0) return;
305 payments.push([item.id, item.payment_pending]);
310 function refreshDisplay() {
311 patronSvc.fetchUserStats();
312 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
313 $scope.payment_amount = null;
314 $scope.gridControls.refresh();
317 // generates payments, collects user note if needed, and sends payment
319 function sendPayment(note) {
320 var make_payments = generatePayments();
321 billSvc.applyPayment(
322 $scope.payment_type, make_payments, note, $scope.check_number)
323 .then(function(payment_ids) {
325 if (!$scope.disable_auto_print && $scope.receipt_on_pay.isChecked) {
327 $scope.payment_type, payment_ids, make_payments, note);
334 $scope.onReceiptOnPayChanged = function(){
335 egCore.hatch.setItem('circ.bills.receiptonpay', $scope.receipt_on_pay.isChecked);
338 function printReceipt(type, payment_ids, payments_made, note) {
339 var payment_blobs = [];
340 angular.forEach(payments_made, function(payment) {
341 var xact_id = payment[0];
343 // find the original transaction in the grid..
344 var xact = $scope.gridControls.allItems().filter(
345 function(item) {return item.id == xact_id})[0];
348 xact : egCore.idl.flatToNestedHash(xact),
353 console.log(js2JSON(payment_blobs[0]));
355 // page data not yet refreshed, capture data from current scope
359 previous_balance : Number($scope.summary.balance_owed()),
360 payment_total : Number($scope.payment_amount),
361 payment_applied : $scope.pending_payment(),
362 amount_voided : Number($scope.session_voided),
363 change_given : $scope.pending_change(),
364 payments : payment_blobs,
365 current_location : egCore.idl.toHash(
366 egCore.org.get(egCore.auth.user().ws_ou()))
369 print_data.new_balance = (
370 print_data.previous_balance * 100 -
371 print_data.payment_applied * 100) / 100;
373 for (var i = 0; i < $scope.receipt_count; i++) {
376 template : 'bill_payment',
382 $scope.showHistory = function() {
383 $location.path('/circ/patron/' +
384 patronSvc.current.id() + '/bill_history/transactions');
387 // For now, only adds billing to first selected item.
388 // Could do batches later if needed
389 $scope.addBilling = function(all) {
391 egBilling.showBillDialog({
392 xact : egCore.idl.flatToNestedHash(all[0]),
393 patron : $scope.patron()
394 }).then(refreshDisplay);
398 $scope.showBillDialog = function($event) {
399 egBilling.showBillDialog({
400 patron : $scope.patron()
401 }).then(refreshDisplay);
404 // Select refunds adds all refunds to the existing selection.
405 // It does not /only/ select refunds
406 $scope.selectRefunds = function() {
407 var ids = $scope.gridControls.selectedItems().map(
408 function(i) { return i.id });
409 angular.forEach($scope.gridControls.allItems(), function(item) {
410 if (Number(item['summary.balance_owed']) < 0)
413 $scope.gridControls.selectItems(ids);
417 // determine on initial page load when all of the grid rows should
419 var selectOnLoad = true;
420 billSvc.fetchBillSettings().then(function(s) {
421 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
422 $scope.focus_payment = false; // de-focus the payment box
423 $scope.gridControls.focusRowSelector = true;
424 selectOnLoad = false;
425 // if somehow the grid finishes rendering before our settings
426 // arrive, manually de-select everything.
427 $scope.gridControls.selectItems([]);
429 if (s['ui.circ.billing.amount_warn']) {
430 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
432 if (s['ui.circ.billing.amount_limit']) {
433 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
435 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
436 $scope.disable_auto_print = Boolean(
437 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
442 $scope.gridControls.allItemsRetrieved = function() {
444 selectOnLoad = false; // only for initial controller load.
445 // select all non-refund items
446 $scope.gridControls.selectItems(
447 $scope.gridControls.allItems()
448 .filter(function(i) {return i['summary.balance_owed'] > 0})
449 .map(function(i){return i.id})
456 $scope.printBills = function(selected) {
457 if (!selected.length) return;
458 // bills print receipt assumes nested hashes, but our grid
459 // stores flattener data. Fetch the selected xacts as
460 // fleshed pcrud objects and hashify.
461 // (Consider an alternate approach..)
462 var ids = selected.map(function(t){ return t.id });
464 egCore.pcrud.search('mbt',
466 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
467 {authoritative : true}
472 template : 'bills_current',
474 transactions : xacts,
475 current_location : egCore.idl.toHash(
476 egCore.org.get(egCore.auth.user().ws_ou()))
482 xacts.push(egCore.idl.toHash(xact));
487 $scope.applyPayment = function() {
489 if ($scope.payment_amount > $scope.max_amount ) {
491 egCore.strings.PAYMENT_OVER_MAX,
492 { max_amount : ''+$scope.max_amount,
494 $scope.payment_amount = 0;
501 if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
502 egConfirmDialog.open(
503 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
504 { payment_amount : ''+$scope.payment_amount,
506 $scope.amount_verfied = true;
507 $scope.applyPayment();
509 cancel : function() {
510 $scope.payment_amount = 0;
517 $scope.amount_verfied = false;
519 if ($scope.annotate_payment) {
521 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
522 {ok : function(value) {sendPayment(value)}}
529 $scope.voidAllBillings = function(items) {
533 angular.forEach(items, function(item) {
535 billSvc.fetchBills(item.id).then(function(bills) {
536 angular.forEach(bills, function(b) {
537 if (b.voided() != 't') {
538 cents += b.amount() * 100;
539 bill_ids.push(b.id())
543 if (bill_ids.length == 0) {
552 $q.all(promises).then(function(){
553 egCore.audio.play('warning.circ.void_billings_confirmation');
554 egConfirmDialog.open(
555 egCore.strings.CONFIRM_VOID_BILLINGS, '',
556 { billIds : ''+bill_ids,
557 amount : ''+(cents/100),
559 billSvc.voidBills(bill_ids).then(function() {
560 $scope.session_voided =
561 ($scope.session_voided * 100 + cents) / 100;
570 $scope.adjustToZero = function(items) {
571 if (items.length == 0) return;
573 var ids = items.map(function(item) {return item.id});
575 egCore.audio.play('warning.circ.adjust_to_zero_confirmation');
576 egConfirmDialog.open(
577 egCore.strings.CONFIRM_ADJUST_TO_ZERO, '',
580 billSvc.adjustBillsToZero(ids).then(function() {
589 // note this is functionally equivalent to selecting a neg. transaction
590 // then clicking Apply Payment -- this just adds a speed bump (ditto
592 $scope.refundXact = function(all) {
593 var items = all.filter(function(item) {
594 return item['summary.balance_owed'] < 0
597 if (items.length == 0) return;
599 var ids = items.map(function(item) {return item.id});
601 egCore.audio.play('warning.circ.refund_confirmation');
602 egConfirmDialog.open(
603 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
606 // reset the received payment amount. this ensures
607 // we're not mingling payments with refunds.
608 $scope.payment_amount = 0;
614 // direct the user to the transaction details page
615 $scope.showFullDetails = function(all) {
617 $location.path('/circ/patron/' +
618 patronSvc.current.id() + '/bill/' + all[0].id);
621 $scope.activateBill = function(xact) {
622 $scope.showFullDetails([xact]);
628 * Displays details of a single transaction
630 .controller('XactDetailsCtrl',
631 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling','egConfirmDialog',
632 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling , egConfirmDialog ) {
634 $scope.initTab('bills', $routeParams.id);
635 var xact_id = $routeParams.xact_id;
637 var xactGrid = $scope.xactGridControls = {
638 setQuery : function() { return {xact : xact_id} },
639 setSort : function() { return ['billing_ts'] }
642 var paymentGrid = $scope.paymentGridControls = {
643 setQuery : function() { return {xact : xact_id} },
644 setSort : function() { return ['payment_ts'] }
648 $scope.voidBillings = function(bill_list) {
651 angular.forEach(bill_list, function(b) {
652 if (b.voided != 't') {
653 cents += b.amount * 100;
658 if (bill_ids.length == 0) {
663 egCore.audio.play('warning.circ.void_billings_confirmation');
664 egConfirmDialog.open(
665 egCore.strings.CONFIRM_VOID_BILLINGS, '',
666 { billIds : ''+bill_ids,
667 amount : ''+(cents/100),
669 billSvc.voidBills(bill_ids).then(function() {
670 // TODO? $scope.session_voided = ...
672 // refresh bills and summary data
673 // note: no need to update payments
674 patronSvc.fetchUserStats();
676 egBilling.fetchXact(xact_id).then(function(xact) {
687 // batch-edit billing and payment notes, depending on 'type'
688 function editNotes(selected, type) {
689 var notes = selected.map(function(b){ return b.note }).join(',');
690 var ids = selected.map(function(b){ return b.id });
692 // show the note edit prompt
694 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
696 ok : function(value) {
698 var func = 'updateBillNotes';
699 if (type == 'payment') func = 'updatePaymentNotes';
701 billSvc[func](value, ids).then(function() {
702 if (type == 'payment') {
703 paymentGrid.refresh();
713 $scope.editBillNotes = function(selected) {
714 editNotes(selected, 'bill');
717 $scope.editPaymentNotes = function(selected) {
718 editNotes(selected, 'payment');
721 // -- retrieve our data
722 $scope.total_circs = 0; // start with 0 instead of undefined
723 egBilling.fetchXact(xact_id).then(function(xact) {
726 var copyId = xact.circulation().target_copy().id();
728 egCore.pcrud.search('circbyyr',
729 {copy : copyId}, null, {atomic : true})
730 .then(function(counts) {
731 angular.forEach(counts, function(count) {
732 circ_count += Number(count.count());
734 $scope.total_circs = circ_count;
736 // set the title. only needs to be done on initial page load
737 if (xact.circulation()) {
738 if (xact.circulation().target_copy().call_number().id() == -1) {
739 $scope.title = xact.circulation().target_copy().dummy_title();
741 // TODO: shared bib service?
742 $scope.title = xact.circulation().target_copy()
743 .call_number().record().simple_record().title();
744 $scope.title_id = xact.circulation().target_copy()
745 .call_number().record().id();
752 .controller('BillHistoryCtrl',
753 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
754 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
756 $scope.initTab('bills', $routeParams.id);
757 billSvc.userId = $routeParams.id;
758 $scope.bill_tab = $routeParams.history_tab;
761 // link page controller actions defined by sub-controllers here
764 var start = new Date(); // now - 1 year
765 start.setFullYear(start.getFullYear() - 1),
768 xact_finish : new Date()
771 $scope.date_range = function() {
772 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
773 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
774 var today = new Date().toISOString().replace(/T.*/,'');
775 if (end == today) end = 'now';
781 .controller('BillXactHistoryCtrl',
782 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
783 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
785 // generate a grid query with the current date widget values.
786 function current_grid_query() {
789 {'summary.balance_owed' : {'<>' : 0}},
790 {'summary.last_payment_ts' : {'<>' : null}}
792 xact_start : {between : $scope.date_range()},
797 $scope.gridControls = {
798 selectedItems : function(){return []},
799 activateItem : function(item) {
800 $scope.showFullDetails([item]);
802 // this sets the query on page load
803 setQuery : current_grid_query
806 $scope.actions.apply_date_range = function() {
807 // tells the grid to re-draw itself with the new query
808 $scope.gridControls.setQuery(current_grid_query());
811 // TODO; move me to service
812 function selected_payment_info() {
813 var info = {owed : 0, billed : 0, paid : 0};
814 angular.forEach($scope.gridControls.selectedItems(), function(item) {
815 info.owed += Number(item['summary.balance_owed']) * 100;
816 info.billed += Number(item['summary.total_owed']) * 100;
817 info.paid += Number(item['summary.total_paid']) * 100;
825 $scope.totals.selected_billed = function() {
826 return selected_payment_info().billed;
828 $scope.totals.selected_paid = function() {
829 return selected_payment_info().paid;
832 $scope.showFullDetails = function(all) {
834 $location.path('/circ/patron/' +
835 patronSvc.current.id() + '/bill/' + all[0].id);
838 // For now, only adds billing to first selected item.
839 // Could do batches later if needed
840 $scope.addBilling = function(all) {
842 egBilling.showBillDialog({
843 xact : egCore.idl.flatToNestedHash(all[0]),
844 patron : $scope.patron()
846 $scope.gridControls.refresh();
847 patronSvc.fetchUserStats();
852 $scope.printBills = function(selected) { // FIXME: refactor me
853 if (!selected.length) return;
854 // bills print receipt assumes nested hashes, but our grid
855 // stores flattener data. Fetch the selected xacts as
856 // fleshed pcrud objects and hashify.
857 // (Consider an alternate approach..)
858 var ids = selected.map(function(t){ return t.id });
860 egCore.pcrud.search('mbt',
862 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
863 {authoritative : true}
868 template : 'bills_historical',
870 transactions : xacts,
871 current_location : egCore.idl.toHash(
872 egCore.org.get(egCore.auth.user().ws_ou()))
878 xacts.push(egCore.idl.toHash(xact));
886 .controller('BillPaymentHistoryCtrl',
887 ['$scope','$q','egCore','patronSvc','billSvc','$location',
888 function($scope, $q , egCore , patronSvc , billSvc , $location) {
890 // generate a grid query with the current date widget values.
891 function current_grid_query() {
893 'payment_ts' : {between : $scope.date_range()},
894 'xact.usr' : billSvc.userId
898 $scope.gridControls = {
899 selectedItems : function(){return []},
900 activateItem : function(item) {
901 $scope.showFullDetails([item]);
903 setSort : function() {
904 return [{'payment_ts' : 'DESC'}, 'id'];
906 setQuery : current_grid_query
909 $scope.actions.apply_date_range = function() {
910 // tells the grid to re-draw itself with the new query
911 $scope.gridControls.setQuery(current_grid_query());
914 $scope.showFullDetails = function(all) {
916 $location.path('/circ/patron/' +
917 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
920 $scope.totals.selected_paid = function() {
922 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
923 paid += Number(payment.amount) * 100;