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 egCore.audio.play('warning.circ.refund_confirmation');
550 egConfirmDialog.open(
551 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
554 // reset the received payment amount. this ensures
555 // we're not mingling payments with refunds.
556 $scope.payment_amount = 0;
562 // direct the user to the transaction details page
563 $scope.showFullDetails = function(all) {
565 $location.path('/circ/patron/' +
566 patronSvc.current.id() + '/bill/' + all[0].id);
569 $scope.activateBill = function(xact) {
570 $scope.showFullDetails([xact]);
576 * Displays details of a single transaction
578 .controller('XactDetailsCtrl',
579 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
580 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
582 $scope.initTab('bills', $routeParams.id);
583 var xact_id = $routeParams.xact_id;
585 var xactGrid = $scope.xactGridControls = {
586 setQuery : function() { return {xact : xact_id} },
587 setSort : function() { return ['billing_ts'] }
590 var paymentGrid = $scope.paymentGridControls = {
591 setQuery : function() { return {xact : xact_id} },
592 setSort : function() { return ['payment_ts'] }
596 $scope.voidBillings = function(bill_list) {
598 angular.forEach(bill_list, function(b) {
599 if (b.voided != 't') bill_ids.push(b.id);
602 if (bill_ids.length == 0) {
607 billSvc.voidBills(bill_ids).then(function() {
609 // refresh bills and summary data
610 // note: no need to update payments
611 patronSvc.fetchUserStats();
613 egBilling.fetchXact(xact_id).then(function(xact) {
621 // batch-edit billing and payment notes, depending on 'type'
622 function editNotes(selected, type) {
623 var notes = selected.map(function(b){ return b.note }).join(',');
624 var ids = selected.map(function(b){ return b.id });
626 // show the note edit prompt
628 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
630 ok : function(value) {
632 var func = 'updateBillNotes';
633 if (type == 'payment') func = 'updatePaymentNotes';
635 billSvc[func](value, ids).then(function() {
636 if (type == 'payment') {
637 paymentGrid.refresh();
647 $scope.editBillNotes = function(selected) {
648 editNotes(selected, 'bill');
651 $scope.editPaymentNotes = function(selected) {
652 editNotes(selected, 'payment');
655 // -- retrieve our data
656 $scope.total_circs = 0; // start with 0 instead of undefined
657 egBilling.fetchXact(xact_id).then(function(xact) {
660 var copyId = xact.circulation().target_copy().id();
662 egCore.pcrud.search('circbyyr',
663 {copy : copyId}, null, {atomic : true})
664 .then(function(counts) {
665 angular.forEach(counts, function(count) {
666 circ_count += Number(count.count());
668 $scope.total_circs = circ_count;
670 // set the title. only needs to be done on initial page load
671 if (xact.circulation()) {
672 if (xact.circulation().target_copy().call_number().id() == -1) {
673 $scope.title = xact.circulation().target_copy().dummy_title();
675 // TODO: shared bib service?
676 $scope.title = xact.circulation().target_copy()
677 .call_number().record().simple_record().title();
678 $scope.title_id = xact.circulation().target_copy()
679 .call_number().record().id();
686 .controller('BillHistoryCtrl',
687 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
688 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
690 $scope.initTab('bills', $routeParams.id);
691 billSvc.userId = $routeParams.id;
692 $scope.bill_tab = $routeParams.history_tab;
695 // link page controller actions defined by sub-controllers here
698 var start = new Date(); // now - 1 year
699 start.setFullYear(start.getFullYear() - 1),
702 xact_finish : new Date()
705 $scope.date_range = function() {
706 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
707 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
708 var today = new Date().toISOString().replace(/T.*/,'');
709 if (end == today) end = 'now';
715 .controller('BillXactHistoryCtrl',
716 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
717 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
719 // generate a grid query with the current date widget values.
720 function current_grid_query() {
723 {'summary.balance_owed' : {'<>' : 0}},
724 {'summary.last_payment_ts' : {'<>' : null}}
726 xact_start : {between : $scope.date_range()},
731 $scope.gridControls = {
732 selectedItems : function(){return []},
733 activateItem : function(item) {
734 $scope.showFullDetails([item]);
736 // this sets the query on page load
737 setQuery : current_grid_query
740 $scope.actions.apply_date_range = function() {
741 // tells the grid to re-draw itself with the new query
742 $scope.gridControls.setQuery(current_grid_query());
745 // TODO; move me to service
746 function selected_payment_info() {
747 var info = {owed : 0, billed : 0, paid : 0};
748 angular.forEach($scope.gridControls.selectedItems(), function(item) {
749 info.owed += Number(item['summary.balance_owed']) * 100;
750 info.billed += Number(item['summary.total_owed']) * 100;
751 info.paid += Number(item['summary.total_paid']) * 100;
759 $scope.totals.selected_billed = function() {
760 return selected_payment_info().billed;
762 $scope.totals.selected_paid = function() {
763 return selected_payment_info().paid;
766 $scope.showFullDetails = function(all) {
768 $location.path('/circ/patron/' +
769 patronSvc.current.id() + '/bill/' + all[0].id);
772 // For now, only adds billing to first selected item.
773 // Could do batches later if needed
774 $scope.addBilling = function(all) {
776 egBilling.showBillDialog({
777 xact : egCore.idl.flatToNestedHash(all[0]),
778 patron : $scope.patron()
780 $scope.gridControls.refresh();
781 patronSvc.fetchUserStats();
786 $scope.printBills = function(selected) { // FIXME: refactor me
787 if (!selected.length) return;
788 // bills print receipt assumes nested hashes, but our grid
789 // stores flattener data. Fetch the selected xacts as
790 // fleshed pcrud objects and hashify.
791 // (Consider an alternate approach..)
792 var ids = selected.map(function(t){ return t.id });
794 egCore.pcrud.search('mbt',
796 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
797 {authoritative : true}
802 template : 'bills_historical',
804 transactions : xacts,
805 current_location : egCore.idl.toHash(
806 egCore.org.get(egCore.auth.user().ws_ou()))
812 xacts.push(egCore.idl.toHash(xact));
820 .controller('BillPaymentHistoryCtrl',
821 ['$scope','$q','egCore','patronSvc','billSvc','$location',
822 function($scope, $q , egCore , patronSvc , billSvc , $location) {
824 // generate a grid query with the current date widget values.
825 function current_grid_query() {
827 'payment_ts' : {between : $scope.date_range()},
828 'xact.usr' : billSvc.userId
832 $scope.gridControls = {
833 selectedItems : function(){return []},
834 activateItem : function(item) {
835 $scope.showFullDetails([item]);
837 setSort : function() {
838 return [{'payment_ts' : 'DESC'}, 'id'];
840 setQuery : current_grid_query
843 $scope.actions.apply_date_range = function() {
844 // tells the grid to re-draw itself with the new query
845 $scope.gridControls.setQuery(current_grid_query());
848 $scope.showFullDetails = function(all) {
850 $location.path('/circ/patron/' +
851 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
854 $scope.totals.selected_paid = function() {
856 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
857 paid += Number(payment.amount) * 100;