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']
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;
155 // pre-define list-returning funcs in case we access them
156 // before the grid instantiates
157 $scope.gridControls = {
158 focusRowSelector : false,
159 selectedItems : function(){return []},
160 allItems : function(){return []},
161 itemRetrieved : function(item) {
162 item.payment_pending = 0;
164 activateItem : function(item) {
165 $scope.showFullDetails([item]);
167 setQuery : function() {
169 usr : billSvc.userId,
171 'summary.balance_owed' : {'<>' : 0}
174 setSort : function() {
175 return ['xact_start'];
179 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
181 // given a payment amount, determines how much of that is applied
182 // to selected transactions and how much is left over (change).
183 function pending_payment_info() {
184 var amt = $scope.payment_amount || 0;
185 if (amt >= $scope.owed_selected()) {
187 payment : $scope.owed_selected(),
188 change : amt - $scope.owed_selected()
191 return {payment : amt, change : 0};
194 // calculates amount owed, billed, and paid for selected items
195 // TODO: move me to service
196 function selected_payment_info() {
197 var info = {owed : 0, billed : 0, paid : 0};
198 angular.forEach($scope.gridControls.selectedItems(), function(item) {
199 info.owed += Number(item['summary.balance_owed']) * 100;
200 info.billed += Number(item['summary.total_owed']) * 100;
201 info.paid += Number(item['summary.total_paid']) * 100;
209 $scope.pending_payment = function() {
210 return pending_payment_info().payment;
212 $scope.pending_change = function() {
213 return pending_payment_info().change;
215 $scope.owed_selected = function() {
216 return selected_payment_info().owed;
218 $scope.billed_selected = function() {
219 return selected_payment_info().billed;
221 $scope.paid_selected = function() {
222 return selected_payment_info().paid;
224 $scope.refunds_available = function() {
226 angular.forEach($scope.gridControls.allItems(), function(item) {
227 if (item['summary.balance_owed'] < 0)
228 amount += item['summary.balance_owed'] * 100;
230 return -(amount / 100);
232 $scope.invalid_check_number = function() {
233 return $scope.payment_type == 'check_payment' && ! $scope.check_number;
236 // update the item.payment_pending value each time the user
237 // selects different transactions to pay against.
239 function() {return $scope.gridControls.selectedItems()},
240 function() {updatePendingColumn()},
244 // update the item.payment_pending for each (selected)
245 // transaction any time the user-entered payment amount is modified
246 $scope.$watch('payment_amount', updatePendingColumn);
248 // updates the value of the payment_pending column in the grid.
249 // This has to be managed manually since the display value in the grid
250 // is derived from the value on the stored item and not the contents
251 // of our local scope variables.
252 function updatePendingColumn() {
253 // reset all to zero..
254 angular.forEach($scope.gridControls.allItems(),
255 function(item) {item.payment_pending = 0});
257 var payment_amount = $scope.pending_payment();
259 var selected = $scope.gridControls.selectedItems();
260 for (var i = 0; i < selected.length; i++) { // for/break
261 var item = selected[i];
262 var owed = Number(item['summary.balance_owed']);
264 if (payment_amount > owed) {
265 // pending payment exceeds balance of current item.
266 // pay the entire item.
267 item.payment_pending = owed;
268 payment_amount -= owed;
271 // balance owed on the current item matches or exceeds
272 // the pending payment. Apply the full remainder of
273 // the payment to this item.. and we're done.
274 item.payment_pending = payment_amount;
280 // builds payment arrays ([xact_id, ammount]) for all transactions
281 // which have a pending payment amount.
282 function generatePayments() {
284 angular.forEach($scope.gridControls.selectedItems(), function(item) {
285 if (item.payment_pending == 0) return;
286 payments.push([item.id, item.payment_pending]);
291 function refreshDisplay() {
292 patronSvc.fetchUserStats();
293 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
294 $scope.payment_amount = null;
295 $scope.gridControls.refresh();
298 // generates payments, collects user note if needed, and sends payment
300 function sendPayment(note) {
301 var make_payments = generatePayments();
302 billSvc.applyPayment(
303 $scope.payment_type, make_payments, note, $scope.check_number)
304 .then(function(payment_ids) {
306 if ($scope.receipt_on_pay) {
308 $scope.payment_type, payment_ids, make_payments, note);
315 function printReceipt(type, payment_ids, payments_made, note) {
316 var payment_blobs = [];
317 angular.forEach(payments_made, function(payment) {
318 var xact_id = payment[0];
320 // find the original transaction in the grid..
321 var xact = $scope.gridControls.allItems().filter(
322 function(item) {return item.id == xact_id})[0];
325 xact : egCore.idl.flatToNestedHash(xact),
330 console.log(js2JSON(payment_blobs[0]));
332 // page data not yet refreshed, capture data from current scope
336 previous_balance : Number($scope.summary.balance_owed()),
337 payment_total : Number($scope.payment_amount),
338 payment_applied : $scope.pending_payment(),
339 amount_voided : Number($scope.session_voided),
340 change_given : $scope.pending_change(),
341 payments : payment_blobs,
342 current_location : egCore.idl.toHash(
343 egCore.org.get(egCore.auth.user().ws_ou()))
346 print_data.new_balance = (
347 print_data.previous_balance * 100 -
348 print_data.payment_applied * 100) / 100;
350 for (var i = 0; i < $scope.receipt_count; i++) {
353 template : 'bill_payment',
359 $scope.showHistory = function() {
360 $location.path('/circ/patron/' +
361 patronSvc.current.id() + '/bill_history/transactions');
364 // For now, only adds billing to first selected item.
365 // Could do batches later if needed
366 $scope.addBilling = function(all) {
368 egBilling.showBillDialog({
369 xact : egCore.idl.flatToNestedHash(all[0]),
370 patron : $scope.patron()
371 }).then(refreshDisplay);
375 $scope.showBillDialog = function($event) {
376 egBilling.showBillDialog({
377 patron : $scope.patron()
378 }).then(refreshDisplay);
381 // Select refunds adds all refunds to the existing selection.
382 // It does not /only/ select refunds
383 $scope.selectRefunds = function() {
384 var ids = $scope.gridControls.selectedItems().map(
385 function(i) { return i.id });
386 angular.forEach($scope.gridControls.allItems(), function(item) {
387 if (Number(item['summary.balance_owed']) < 0)
390 $scope.gridControls.selectItems(ids);
394 // determine on initial page load when all of the grid rows should
396 var selectOnLoad = true;
397 billSvc.fetchBillSettings().then(function(s) {
398 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
399 $scope.focus_payment = false; // de-focus the payment box
400 $scope.gridControls.focusRowSelector = true;
401 selectOnLoad = false;
402 // if somehow the grid finishes rendering before our settings
403 // arrive, manually de-select everything.
404 $scope.gridControls.selectItems([]);
406 if (s['ui.circ.billing.amount_warn']) {
407 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
409 if (s['ui.circ.billing.amount_limit']) {
410 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
414 $scope.gridControls.allItemsRetrieved = function() {
416 selectOnLoad = false; // only for initial controller load.
417 // select all non-refund items
418 $scope.gridControls.selectItems(
419 $scope.gridControls.allItems()
420 .filter(function(i) {return i['summary.balance_owed'] > 0})
421 .map(function(i){return i.id})
428 $scope.printBills = function(selected) {
429 if (!selected.length) return;
430 // bills print receipt assumes nested hashes, but our grid
431 // stores flattener data. Fetch the selected xacts as
432 // fleshed pcrud objects and hashify.
433 // (Consider an alternate approach..)
434 var ids = selected.map(function(t){ return t.id });
436 egCore.pcrud.search('mbt',
438 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
439 {authoritative : true}
444 template : 'bills_current',
446 transactions : xacts,
447 current_location : egCore.idl.toHash(
448 egCore.org.get(egCore.auth.user().ws_ou()))
454 xacts.push(egCore.idl.toHash(xact));
459 $scope.applyPayment = function() {
461 if ($scope.payment_amount > $scope.max_amount ) {
463 egCore.strings.PAYMENT_OVER_MAX,
464 { max_amount : ''+$scope.max_amount,
466 $scope.payment_amount = 0;
473 if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
474 egConfirmDialog.open(
475 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
476 { payment_amount : ''+$scope.payment_amount,
478 $scope.amount_verfied = true;
479 $scope.applyPayment();
481 cancel : function() {
482 $scope.payment_amount = 0;
489 $scope.amount_verfied = false;
491 if ($scope.annotate_payment) {
493 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
494 {ok : function(value) {sendPayment(value)}}
501 $scope.voidAllBillings = function(items) {
502 angular.forEach(items, function(item) {
504 billSvc.fetchBills(item.id).then(function(bills) {
507 angular.forEach(bills, function(b) {
508 if (b.voided() != 't') {
509 cents += b.amount() * 100;
510 bill_ids.push(b.id())
514 $scope.session_voided =
515 ($scope.session_voided * 100 + cents) / 100;
517 if (bill_ids.length == 0) {
522 // TODO: alert of pending voiding
524 billSvc.voidBills(bill_ids).then(function() {
531 // note this is functionally equivalent to selecting a neg. transaction
532 // then clicking Apply Payment -- this just adds a speed bump (ditto
534 $scope.refundXact = function(all) {
535 var items = all.filter(function(item) {
536 return item['summary.balance_owed'] < 0
539 if (items.length == 0) return;
541 var ids = items.map(function(item) {return item.id});
543 egConfirmDialog.open(
544 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
547 // reset the received payment amount. this ensures
548 // we're not mingling payments with refunds.
549 $scope.payment_amount = 0;
555 // direct the user to the transaction details page
556 $scope.showFullDetails = function(all) {
558 $location.path('/circ/patron/' +
559 patronSvc.current.id() + '/bill/' + all[0].id);
562 $scope.activateBill = function(xact) {
563 $scope.showFullDetails([xact]);
569 * Displays details of a single transaction
571 .controller('XactDetailsCtrl',
572 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
573 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
575 $scope.initTab('bills', $routeParams.id);
576 var xact_id = $routeParams.xact_id;
578 var xactGrid = $scope.xactGridControls = {
579 setQuery : function() { return {xact : xact_id} },
580 setSort : function() { return ['billing_ts'] }
583 var paymentGrid = $scope.paymentGridControls = {
584 setQuery : function() { return {xact : xact_id} },
585 setSort : function() { return ['payment_ts'] }
589 $scope.voidBillings = function(bill_list) {
591 angular.forEach(bill_list, function(b) {
592 if (b.voided != 't') bill_ids.push(b.id);
595 if (bill_ids.length == 0) {
600 billSvc.voidBills(bill_ids).then(function() {
602 // refresh bills and summary data
603 // note: no need to update payments
604 patronSvc.fetchUserStats();
606 egBilling.fetchXact(xact_id).then(function(xact) {
614 // batch-edit billing and payment notes, depending on 'type'
615 function editNotes(selected, type) {
616 var notes = selected.map(function(b){ return b.note }).join(',');
617 var ids = selected.map(function(b){ return b.id });
619 // show the note edit prompt
621 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
623 ok : function(value) {
625 var func = 'updateBillNotes';
626 if (type == 'payment') func = 'updatePaymentNotes';
628 billSvc[func](value, ids).then(function() {
629 if (type == 'payment') {
630 paymentGrid.refresh();
640 $scope.editBillNotes = function(selected) {
641 editNotes(selected, 'bill');
644 $scope.editPaymentNotes = function(selected) {
645 editNotes(selected, 'payment');
648 // -- retrieve our data
649 $scope.total_circs = 0; // start with 0 instead of undefined
650 egBilling.fetchXact(xact_id).then(function(xact) {
653 var copyId = xact.circulation().target_copy().id();
655 egCore.pcrud.search('circbyyr',
656 {copy : copyId}, null, {atomic : true})
657 .then(function(counts) {
658 angular.forEach(counts, function(count) {
659 circ_count += Number(count.count());
661 $scope.total_circs = circ_count;
663 // set the title. only needs to be done on initial page load
664 if (xact.circulation()) {
665 if (xact.circulation().target_copy().call_number().id() == -1) {
666 $scope.title = xact.circulation().target_copy().dummy_title();
668 // TODO: shared bib service?
669 $scope.title = xact.circulation().target_copy()
670 .call_number().record().simple_record().title();
671 $scope.title_id = xact.circulation().target_copy()
672 .call_number().record().id();
679 .controller('BillHistoryCtrl',
680 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
681 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
683 $scope.initTab('bills', $routeParams.id);
684 billSvc.userId = $routeParams.id;
685 $scope.bill_tab = $routeParams.history_tab;
688 // link page controller actions defined by sub-controllers here
691 var start = new Date(); // now - 1 year
692 start.setFullYear(start.getFullYear() - 1),
695 xact_finish : new Date()
698 $scope.date_range = function() {
699 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
700 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
701 var today = new Date().toISOString().replace(/T.*/,'');
702 if (end == today) end = 'now';
708 .controller('BillXactHistoryCtrl',
709 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
710 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
712 // generate a grid query with the current date widget values.
713 function current_grid_query() {
716 {'summary.balance_owed' : {'<>' : 0}},
717 {'summary.last_payment_ts' : {'<>' : null}}
719 xact_start : {between : $scope.date_range()},
724 $scope.gridControls = {
725 selectedItems : function(){return []},
726 activateItem : function(item) {
727 $scope.showFullDetails([item]);
729 // this sets the query on page load
730 setQuery : current_grid_query
733 $scope.actions.apply_date_range = function() {
734 // tells the grid to re-draw itself with the new query
735 $scope.gridControls.setQuery(current_grid_query());
738 // TODO; move me to service
739 function selected_payment_info() {
740 var info = {owed : 0, billed : 0, paid : 0};
741 angular.forEach($scope.gridControls.selectedItems(), function(item) {
742 info.owed += Number(item['summary.balance_owed']) * 100;
743 info.billed += Number(item['summary.total_owed']) * 100;
744 info.paid += Number(item['summary.total_paid']) * 100;
752 $scope.totals.selected_billed = function() {
753 return selected_payment_info().billed;
755 $scope.totals.selected_paid = function() {
756 return selected_payment_info().paid;
759 $scope.showFullDetails = function(all) {
761 $location.path('/circ/patron/' +
762 patronSvc.current.id() + '/bill/' + all[0].id);
765 // For now, only adds billing to first selected item.
766 // Could do batches later if needed
767 $scope.addBilling = function(all) {
769 egBilling.showBillDialog({
770 xact : egCore.idl.flatToNestedHash(all[0]),
771 patron : $scope.patron()
773 $scope.gridControls.refresh();
774 patronSvc.fetchUserStats();
779 $scope.printBills = function(selected) { // FIXME: refactor me
780 if (!selected.length) return;
781 // bills print receipt assumes nested hashes, but our grid
782 // stores flattener data. Fetch the selected xacts as
783 // fleshed pcrud objects and hashify.
784 // (Consider an alternate approach..)
785 var ids = selected.map(function(t){ return t.id });
787 egCore.pcrud.search('mbt',
789 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
790 {authoritative : true}
795 template : 'bills_historical',
797 transactions : xacts,
798 current_location : egCore.idl.toHash(
799 egCore.org.get(egCore.auth.user().ws_ou()))
805 xacts.push(egCore.idl.toHash(xact));
813 .controller('BillPaymentHistoryCtrl',
814 ['$scope','$q','egCore','patronSvc','billSvc','$location',
815 function($scope, $q , egCore , patronSvc , billSvc , $location) {
817 // generate a grid query with the current date widget values.
818 function current_grid_query() {
820 'payment_ts' : {between : $scope.date_range()},
821 'xact.usr' : billSvc.userId
825 $scope.gridControls = {
826 selectedItems : function(){return []},
827 activateItem : function(item) {
828 $scope.showFullDetails([item]);
830 setSort : function() {
831 return [{'payment_ts' : 'DESC'}, 'id'];
833 setQuery : current_grid_query
836 $scope.actions.apply_date_range = function() {
837 // tells the grid to re-draw itself with the new query
838 $scope.gridControls.setQuery(current_grid_query());
841 $scope.showFullDetails = function(all) {
843 $location.path('/circ/patron/' +
844 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
847 $scope.totals.selected_paid = function() {
849 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
850 paid += Number(payment.amount) * 100;