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.updateBillNotes = function(note, ids) {
103 return egCore.net.requestWithParamList(
105 'open-ils.circ.money.billing.note.edit',
106 [egCore.auth.token(), note].concat(ids)
107 ).then(function(resp) {
108 if (evt = egCore.evt.parse(resp)) return alert(evt);
113 service.updatePaymentNotes = function(note, ids) {
114 return egCore.net.requestWithParamList(
116 'open-ils.circ.money.payment.note.edit',
117 [egCore.auth.token(), note].concat(ids)
118 ).then(function(resp) {
119 if (evt = egCore.evt.parse(resp)) return alert(evt);
131 .controller('PatronBillsCtrl',
132 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
133 'egGridDataProvider','billSvc','patronSvc','egPromptDialog', 'egAlertDialog',
135 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
136 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
139 $scope.initTab('bills', $routeParams.id);
140 billSvc.userId = $routeParams.id;
142 // set up some defaults
143 $scope.check_number = null;
144 $scope.payment_amount = null;
145 $scope.session_voided = 0;
146 $scope.payment_type = 'cash_payment';
147 $scope.focus_payment = true;
148 $scope.annotate_payment = false;
149 $scope.receipt_count = 1;
150 $scope.receipt_on_pay = false;
151 $scope.warn_amount = 1000;
152 $scope.max_amount = 100000;
153 $scope.amount_verified = false;
154 $scope.disable_auto_print = false;
156 // pre-define list-returning funcs in case we access them
157 // before the grid instantiates
158 $scope.gridControls = {
159 focusRowSelector : false,
160 selectedItems : function(){return []},
161 allItems : function(){return []},
162 itemRetrieved : function(item) {
163 item.payment_pending = 0;
165 activateItem : function(item) {
166 $scope.showFullDetails([item]);
168 setQuery : function() {
170 usr : billSvc.userId,
172 'summary.balance_owed' : {'<>' : 0}
175 setSort : function() {
176 return ['xact_start'];
180 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
182 // given a payment amount, determines how much of that is applied
183 // to selected transactions and how much is left over (change).
184 function pending_payment_info() {
185 var amt = $scope.payment_amount || 0;
186 if (amt >= $scope.owed_selected()) {
188 payment : $scope.owed_selected(),
189 change : amt - $scope.owed_selected()
192 return {payment : amt, change : 0};
195 // calculates amount owed, billed, and paid for selected items
196 // TODO: move me to service
197 function selected_payment_info() {
198 var info = {owed : 0, billed : 0, paid : 0};
199 angular.forEach($scope.gridControls.selectedItems(), function(item) {
200 info.owed += Number(item['summary.balance_owed']) * 100;
201 info.billed += Number(item['summary.total_owed']) * 100;
202 info.paid += Number(item['summary.total_paid']) * 100;
210 $scope.pending_payment = function() {
211 return pending_payment_info().payment;
213 $scope.pending_change = function() {
214 return pending_payment_info().change;
216 $scope.owed_selected = function() {
217 return selected_payment_info().owed;
219 $scope.billed_selected = function() {
220 return selected_payment_info().billed;
222 $scope.paid_selected = function() {
223 return selected_payment_info().paid;
225 $scope.refunds_available = function() {
227 angular.forEach($scope.gridControls.allItems(), function(item) {
228 if (item['summary.balance_owed'] < 0)
229 amount += item['summary.balance_owed'] * 100;
231 return -(amount / 100);
233 $scope.invalid_check_number = function() {
234 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
237 // update the item.payment_pending value each time the user
238 // selects different transactions to pay against.
240 function() {return $scope.gridControls.selectedItems()},
241 function() {updatePendingColumn()},
245 // update the item.payment_pending for each (selected)
246 // transaction any time the user-entered payment amount is modified
247 $scope.$watch('payment_amount', updatePendingColumn);
249 // updates the value of the payment_pending column in the grid.
250 // This has to be managed manually since the display value in the grid
251 // is derived from the value on the stored item and not the contents
252 // of our local scope variables.
253 function updatePendingColumn() {
254 // reset all to zero..
255 angular.forEach($scope.gridControls.allItems(),
256 function(item) {item.payment_pending = 0});
258 var payment_amount = $scope.pending_payment();
260 var selected = $scope.gridControls.selectedItems();
261 for (var i = 0; i < selected.length; i++) { // for/break
262 var item = selected[i];
263 var owed = Number(item['summary.balance_owed']);
265 if (payment_amount > owed) {
266 // pending payment exceeds balance of current item.
267 // pay the entire item.
268 item.payment_pending = owed;
269 payment_amount -= owed;
272 // balance owed on the current item matches or exceeds
273 // the pending payment. Apply the full remainder of
274 // the payment to this item.. and we're done.
275 item.payment_pending = payment_amount;
281 // builds payment arrays ([xact_id, ammount]) for all transactions
282 // which have a pending payment amount.
283 function generatePayments() {
285 angular.forEach($scope.gridControls.selectedItems(), function(item) {
286 if (item.payment_pending == 0) return;
287 payments.push([item.id, item.payment_pending]);
292 function refreshDisplay() {
293 patronSvc.fetchUserStats();
294 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
295 $scope.payment_amount = null;
296 $scope.gridControls.refresh();
299 // generates payments, collects user note if needed, and sends payment
301 function sendPayment(note) {
302 var make_payments = generatePayments();
303 billSvc.applyPayment(
304 $scope.payment_type, make_payments, note, $scope.check_number)
305 .then(function(payment_ids) {
307 if (!$scope.disable_auto_print && $scope.receipt_on_pay) {
309 $scope.payment_type, payment_ids, make_payments, note);
316 function printReceipt(type, payment_ids, payments_made, note) {
317 var payment_blobs = [];
318 angular.forEach(payments_made, function(payment) {
319 var xact_id = payment[0];
321 // find the original transaction in the grid..
322 var xact = $scope.gridControls.allItems().filter(
323 function(item) {return item.id == xact_id})[0];
326 xact : egCore.idl.flatToNestedHash(xact),
331 console.log(js2JSON(payment_blobs[0]));
333 // page data not yet refreshed, capture data from current scope
337 previous_balance : Number($scope.summary.balance_owed()),
338 payment_total : Number($scope.payment_amount),
339 payment_applied : $scope.pending_payment(),
340 amount_voided : Number($scope.session_voided),
341 change_given : $scope.pending_change(),
342 payments : payment_blobs,
343 current_location : egCore.idl.toHash(
344 egCore.org.get(egCore.auth.user().ws_ou()))
347 print_data.new_balance = (
348 print_data.previous_balance * 100 -
349 print_data.payment_applied * 100) / 100;
351 for (var i = 0; i < $scope.receipt_count; i++) {
354 template : 'bill_payment',
360 $scope.showHistory = function() {
361 $location.path('/circ/patron/' +
362 patronSvc.current.id() + '/bill_history/transactions');
365 // For now, only adds billing to first selected item.
366 // Could do batches later if needed
367 $scope.addBilling = function(all) {
369 egBilling.showBillDialog({
370 xact : egCore.idl.flatToNestedHash(all[0]),
371 patron : $scope.patron()
372 }).then(refreshDisplay);
376 $scope.showBillDialog = function($event) {
377 egBilling.showBillDialog({
378 patron : $scope.patron()
379 }).then(refreshDisplay);
382 // Select refunds adds all refunds to the existing selection.
383 // It does not /only/ select refunds
384 $scope.selectRefunds = function() {
385 var ids = $scope.gridControls.selectedItems().map(
386 function(i) { return i.id });
387 angular.forEach($scope.gridControls.allItems(), function(item) {
388 if (Number(item['summary.balance_owed']) < 0)
391 $scope.gridControls.selectItems(ids);
395 // determine on initial page load when all of the grid rows should
397 var selectOnLoad = true;
398 billSvc.fetchBillSettings().then(function(s) {
399 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
400 $scope.focus_payment = false; // de-focus the payment box
401 $scope.gridControls.focusRowSelector = true;
402 selectOnLoad = false;
403 // if somehow the grid finishes rendering before our settings
404 // arrive, manually de-select everything.
405 $scope.gridControls.selectItems([]);
407 if (s['ui.circ.billing.amount_warn']) {
408 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
410 if (s['ui.circ.billing.amount_limit']) {
411 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
413 if (s['circ.staff_client.do_not_auto_attempt_print'] && angular.isArray(s['circ.staff_client.do_not_auto_attempt_print'])) {
414 $scope.disable_auto_print = Boolean(
415 s['circ.staff_client.do_not_auto_attempt_print'].indexOf('Bill Pay') > -1
420 $scope.gridControls.allItemsRetrieved = function() {
422 selectOnLoad = false; // only for initial controller load.
423 // select all non-refund items
424 $scope.gridControls.selectItems(
425 $scope.gridControls.allItems()
426 .filter(function(i) {return i['summary.balance_owed'] > 0})
427 .map(function(i){return i.id})
434 $scope.printBills = function(selected) {
435 if (!selected.length) return;
436 // bills print receipt assumes nested hashes, but our grid
437 // stores flattener data. Fetch the selected xacts as
438 // fleshed pcrud objects and hashify.
439 // (Consider an alternate approach..)
440 var ids = selected.map(function(t){ return t.id });
442 egCore.pcrud.search('mbt',
444 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
445 {authoritative : true}
450 template : 'bills_current',
452 transactions : xacts,
453 current_location : egCore.idl.toHash(
454 egCore.org.get(egCore.auth.user().ws_ou()))
460 xacts.push(egCore.idl.toHash(xact));
465 $scope.applyPayment = function() {
467 if ($scope.payment_amount > $scope.max_amount ) {
469 egCore.strings.PAYMENT_OVER_MAX,
470 { max_amount : ''+$scope.max_amount,
472 $scope.payment_amount = 0;
479 if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
480 egConfirmDialog.open(
481 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
482 { payment_amount : ''+$scope.payment_amount,
484 $scope.amount_verfied = true;
485 $scope.applyPayment();
487 cancel : function() {
488 $scope.payment_amount = 0;
495 $scope.amount_verfied = false;
497 if ($scope.annotate_payment) {
499 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
500 {ok : function(value) {sendPayment(value)}}
507 $scope.voidAllBillings = function(items) {
508 angular.forEach(items, function(item) {
510 billSvc.fetchBills(item.id).then(function(bills) {
513 angular.forEach(bills, function(b) {
514 if (b.voided() != 't') {
515 cents += b.amount() * 100;
516 bill_ids.push(b.id())
520 $scope.session_voided =
521 ($scope.session_voided * 100 + cents) / 100;
523 if (bill_ids.length == 0) {
528 // TODO: alert of pending voiding
530 billSvc.voidBills(bill_ids).then(function() {
537 // note this is functionally equivalent to selecting a neg. transaction
538 // then clicking Apply Payment -- this just adds a speed bump (ditto
540 $scope.refundXact = function(all) {
541 var items = all.filter(function(item) {
542 return item['summary.balance_owed'] < 0
545 if (items.length == 0) return;
547 var ids = items.map(function(item) {return item.id});
549 egConfirmDialog.open(
550 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
553 // reset the received payment amount. this ensures
554 // we're not mingling payments with refunds.
555 $scope.payment_amount = 0;
561 // direct the user to the transaction details page
562 $scope.showFullDetails = function(all) {
564 $location.path('/circ/patron/' +
565 patronSvc.current.id() + '/bill/' + all[0].id);
568 $scope.activateBill = function(xact) {
569 $scope.showFullDetails([xact]);
575 * Displays details of a single transaction
577 .controller('XactDetailsCtrl',
578 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
579 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
581 $scope.initTab('bills', $routeParams.id);
582 var xact_id = $routeParams.xact_id;
584 var xactGrid = $scope.xactGridControls = {
585 setQuery : function() { return {xact : xact_id} },
586 setSort : function() { return ['billing_ts'] }
589 var paymentGrid = $scope.paymentGridControls = {
590 setQuery : function() { return {xact : xact_id} },
591 setSort : function() { return ['payment_ts'] }
595 $scope.voidBillings = function(bill_list) {
597 angular.forEach(bill_list, function(b) {
598 if (b.voided != 't') bill_ids.push(b.id);
601 if (bill_ids.length == 0) {
606 billSvc.voidBills(bill_ids).then(function() {
608 // refresh bills and summary data
609 // note: no need to update payments
610 patronSvc.fetchUserStats();
612 egBilling.fetchXact(xact_id).then(function(xact) {
620 // batch-edit billing and payment notes, depending on 'type'
621 function editNotes(selected, type) {
622 var notes = selected.map(function(b){ return b.note }).join(',');
623 var ids = selected.map(function(b){ return b.id });
625 // show the note edit prompt
627 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
629 ok : function(value) {
631 var func = 'updateBillNotes';
632 if (type == 'payment') func = 'updatePaymentNotes';
634 billSvc[func](value, ids).then(function() {
635 if (type == 'payment') {
636 paymentGrid.refresh();
646 $scope.editBillNotes = function(selected) {
647 editNotes(selected, 'bill');
650 $scope.editPaymentNotes = function(selected) {
651 editNotes(selected, 'payment');
654 // -- retrieve our data
655 $scope.total_circs = 0; // start with 0 instead of undefined
656 egBilling.fetchXact(xact_id).then(function(xact) {
659 var copyId = xact.circulation().target_copy().id();
661 egCore.pcrud.search('circbyyr',
662 {copy : copyId}, null, {atomic : true})
663 .then(function(counts) {
664 angular.forEach(counts, function(count) {
665 circ_count += Number(count.count());
667 $scope.total_circs = circ_count;
669 // set the title. only needs to be done on initial page load
670 if (xact.circulation()) {
671 if (xact.circulation().target_copy().call_number().id() == -1) {
672 $scope.title = xact.circulation().target_copy().dummy_title();
674 // TODO: shared bib service?
675 $scope.title = xact.circulation().target_copy()
676 .call_number().record().simple_record().title();
677 $scope.title_id = xact.circulation().target_copy()
678 .call_number().record().id();
685 .controller('BillHistoryCtrl',
686 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
687 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
689 $scope.initTab('bills', $routeParams.id);
690 billSvc.userId = $routeParams.id;
691 $scope.bill_tab = $routeParams.history_tab;
694 // link page controller actions defined by sub-controllers here
697 var start = new Date(); // now - 1 year
698 start.setFullYear(start.getFullYear() - 1),
701 xact_finish : new Date()
704 $scope.date_range = function() {
705 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
706 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
707 var today = new Date().toISOString().replace(/T.*/,'');
708 if (end == today) end = 'now';
714 .controller('BillXactHistoryCtrl',
715 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
716 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
718 // generate a grid query with the current date widget values.
719 function current_grid_query() {
722 {'summary.balance_owed' : {'<>' : 0}},
723 {'summary.last_payment_ts' : {'<>' : null}}
725 xact_start : {between : $scope.date_range()},
730 $scope.gridControls = {
731 selectedItems : function(){return []},
732 activateItem : function(item) {
733 $scope.showFullDetails([item]);
735 // this sets the query on page load
736 setQuery : current_grid_query
739 $scope.actions.apply_date_range = function() {
740 // tells the grid to re-draw itself with the new query
741 $scope.gridControls.setQuery(current_grid_query());
744 // TODO; move me to service
745 function selected_payment_info() {
746 var info = {owed : 0, billed : 0, paid : 0};
747 angular.forEach($scope.gridControls.selectedItems(), function(item) {
748 info.owed += Number(item['summary.balance_owed']) * 100;
749 info.billed += Number(item['summary.total_owed']) * 100;
750 info.paid += Number(item['summary.total_paid']) * 100;
758 $scope.totals.selected_billed = function() {
759 return selected_payment_info().billed;
761 $scope.totals.selected_paid = function() {
762 return selected_payment_info().paid;
765 $scope.showFullDetails = function(all) {
767 $location.path('/circ/patron/' +
768 patronSvc.current.id() + '/bill/' + all[0].id);
771 // For now, only adds billing to first selected item.
772 // Could do batches later if needed
773 $scope.addBilling = function(all) {
775 egBilling.showBillDialog({
776 xact : egCore.idl.flatToNestedHash(all[0]),
777 patron : $scope.patron()
779 $scope.gridControls.refresh();
780 patronSvc.fetchUserStats();
785 $scope.printBills = function(selected) { // FIXME: refactor me
786 if (!selected.length) return;
787 // bills print receipt assumes nested hashes, but our grid
788 // stores flattener data. Fetch the selected xacts as
789 // fleshed pcrud objects and hashify.
790 // (Consider an alternate approach..)
791 var ids = selected.map(function(t){ return t.id });
793 egCore.pcrud.search('mbt',
795 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
796 {authoritative : true}
801 template : 'bills_historical',
803 transactions : xacts,
804 current_location : egCore.idl.toHash(
805 egCore.org.get(egCore.auth.user().ws_ou()))
811 xacts.push(egCore.idl.toHash(xact));
819 .controller('BillPaymentHistoryCtrl',
820 ['$scope','$q','egCore','patronSvc','billSvc','$location',
821 function($scope, $q , egCore , patronSvc , billSvc , $location) {
823 // generate a grid query with the current date widget values.
824 function current_grid_query() {
826 'payment_ts' : {between : $scope.date_range()},
827 'xact.usr' : billSvc.userId
831 $scope.gridControls = {
832 selectedItems : function(){return []},
833 activateItem : function(item) {
834 $scope.showFullDetails([item]);
836 setSort : function() {
837 return [{'payment_ts' : 'DESC'}, 'id'];
839 setQuery : current_grid_query
842 $scope.actions.apply_date_range = function() {
843 // tells the grid to re-draw itself with the new query
844 $scope.gridControls.setQuery(current_grid_query());
847 $scope.showFullDetails = function(all) {
849 $location.path('/circ/patron/' +
850 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
853 $scope.totals.selected_paid = function() {
855 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
856 paid += Number(payment.amount) * 100;