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
335 previous_balance : Number($scope.summary.balance_owed()),
336 payment_total : Number($scope.payment_amount),
337 payment_applied : $scope.pending_payment(),
338 amount_voided : Number($scope.session_voided),
339 change_given : $scope.pending_change(),
340 payments : payment_blobs,
341 current_location : egCore.idl.toHash(
342 egCore.org.get(egCore.auth.user().ws_ou()))
345 print_data.new_balance = (
346 print_data.previous_balance * 100 -
347 print_data.payment_applied * 100) / 100;
349 for (var i = 0; i < $scope.receipt_count; i++) {
352 template : 'bill_payment',
358 $scope.showHistory = function() {
359 $location.path('/circ/patron/' +
360 patronSvc.current.id() + '/bill_history/transactions');
363 // For now, only adds billing to first selected item.
364 // Could do batches later if needed
365 $scope.addBilling = function(all) {
367 egBilling.showBillDialog({
368 xact : egCore.idl.flatToNestedHash(all[0]),
369 patron : $scope.patron()
370 }).then(refreshDisplay);
374 $scope.showBillDialog = function($event) {
375 egBilling.showBillDialog({
376 patron : $scope.patron()
377 }).then(refreshDisplay);
380 // Select refunds adds all refunds to the existing selection.
381 // It does not /only/ select refunds
382 $scope.selectRefunds = function() {
383 var ids = $scope.gridControls.selectedItems().map(
384 function(i) { return i.id });
385 angular.forEach($scope.gridControls.allItems(), function(item) {
386 if (Number(item['summary.balance_owed']) < 0)
389 $scope.gridControls.selectItems(ids);
393 // determine on initial page load when all of the grid rows should
395 var selectOnLoad = true;
396 billSvc.fetchBillSettings().then(function(s) {
397 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
398 $scope.focus_payment = false; // de-focus the payment box
399 $scope.gridControls.focusRowSelector = true;
400 selectOnLoad = false;
401 // if somehow the grid finishes rendering before our settings
402 // arrive, manually de-select everything.
403 $scope.gridControls.selectItems([]);
405 if (s['ui.circ.billing.amount_warn']) {
406 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
408 if (s['ui.circ.billing.amount_limit']) {
409 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
413 $scope.gridControls.allItemsRetrieved = function() {
415 selectOnLoad = false; // only for initial controller load.
416 // select all non-refund items
417 $scope.gridControls.selectItems(
418 $scope.gridControls.allItems()
419 .filter(function(i) {return i['summary.balance_owed'] > 0})
420 .map(function(i){return i.id})
427 $scope.printBills = function(selected) {
428 if (!selected.length) return;
429 // bills print receipt assumes nested hashes, but our grid
430 // stores flattener data. Fetch the selected xacts as
431 // fleshed pcrud objects and hashify.
432 // (Consider an alternate approach..)
433 var ids = selected.map(function(t){ return t.id });
435 egCore.pcrud.search('mbt',
437 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
438 {authoritative : true}
443 template : 'bills_current',
445 transactions : xacts,
446 current_location : egCore.idl.toHash(
447 egCore.org.get(egCore.auth.user().ws_ou()))
453 xacts.push(egCore.idl.toHash(xact));
458 $scope.applyPayment = function() {
460 if ($scope.payment_amount > $scope.max_amount ) {
462 egCore.strings.PAYMENT_OVER_MAX,
463 { max_amount : ''+$scope.max_amount,
465 $scope.payment_amount = 0;
472 if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
473 egConfirmDialog.open(
474 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
475 { payment_amount : ''+$scope.payment_amount,
477 $scope.amount_verfied = true;
478 $scope.applyPayment();
480 cancel : function() {
481 $scope.payment_amount = 0;
488 $scope.amount_verfied = false;
490 if ($scope.annotate_payment) {
492 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
493 {ok : function(value) {sendPayment(value)}}
500 $scope.voidAllBillings = function(items) {
501 angular.forEach(items, function(item) {
503 billSvc.fetchBills(item.id).then(function(bills) {
506 angular.forEach(bills, function(b) {
507 if (b.voided() != 't') {
508 cents += b.amount() * 100;
509 bill_ids.push(b.id())
513 $scope.session_voided =
514 ($scope.session_voided * 100 + cents) / 100;
516 if (bill_ids.length == 0) {
521 // TODO: alert of pending voiding
523 billSvc.voidBills(bill_ids).then(function() {
530 // note this is functionally equivalent to selecting a neg. transaction
531 // then clicking Apply Payment -- this just adds a speed bump (ditto
533 $scope.refundXact = function(all) {
534 var items = all.filter(function(item) {
535 return item['summary.balance_owed'] < 0
538 if (items.length == 0) return;
540 var ids = items.map(function(item) {return item.id});
542 egConfirmDialog.open(
543 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
546 // reset the received payment amount. this ensures
547 // we're not mingling payments with refunds.
548 $scope.payment_amount = 0;
554 // direct the user to the transaction details page
555 $scope.showFullDetails = function(all) {
557 $location.path('/circ/patron/' +
558 patronSvc.current.id() + '/bill/' + all[0].id);
561 $scope.activateBill = function(xact) {
562 $scope.showFullDetails([xact]);
568 * Displays details of a single transaction
570 .controller('XactDetailsCtrl',
571 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
572 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
574 $scope.initTab('bills', $routeParams.id);
575 var xact_id = $routeParams.xact_id;
577 var xactGrid = $scope.xactGridControls = {
578 setQuery : function() { return {xact : xact_id} },
579 setSort : function() { return ['billing_ts'] }
582 var paymentGrid = $scope.paymentGridControls = {
583 setQuery : function() { return {xact : xact_id} },
584 setSort : function() { return ['payment_ts'] }
588 $scope.voidBillings = function(bill_list) {
590 angular.forEach(bill_list, function(b) {
591 if (b.voided != 't') bill_ids.push(b.id);
594 if (bill_ids.length == 0) {
599 billSvc.voidBills(bill_ids).then(function() {
601 // refresh bills and summary data
602 // note: no need to update payments
603 patronSvc.fetchUserStats();
605 egBilling.fetchXact(xact_id).then(function(xact) {
613 // batch-edit billing and payment notes, depending on 'type'
614 function editNotes(selected, type) {
615 var notes = selected.map(function(b){ return b.note }).join(',');
616 var ids = selected.map(function(b){ return b.id });
618 // show the note edit prompt
620 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
622 ok : function(value) {
624 var func = 'updateBillNotes';
625 if (type == 'payment') func = 'updatePaymentNotes';
627 billSvc[func](value, ids).then(function() {
628 if (type == 'payment') {
629 paymentGrid.refresh();
639 $scope.editBillNotes = function(selected) {
640 editNotes(selected, 'bill');
643 $scope.editPaymentNotes = function(selected) {
644 editNotes(selected, 'payment');
647 // -- retrieve our data
648 $scope.total_circs = 0; // start with 0 instead of undefined
649 egBilling.fetchXact(xact_id).then(function(xact) {
652 var copyId = xact.circulation().target_copy().id();
654 egCore.pcrud.search('circbyyr',
655 {copy : copyId}, null, {atomic : true})
656 .then(function(counts) {
657 angular.forEach(counts, function(count) {
658 circ_count += Number(count.count());
660 $scope.total_circs = circ_count;
662 // set the title. only needs to be done on initial page load
663 if (xact.circulation()) {
664 if (xact.circulation().target_copy().call_number().id() == -1) {
665 $scope.title = xact.circulation().target_copy().dummy_title();
667 // TODO: shared bib service?
668 $scope.title = xact.circulation().target_copy()
669 .call_number().record().simple_record().title();
670 $scope.title_id = xact.circulation().target_copy()
671 .call_number().record().id();
678 .controller('BillHistoryCtrl',
679 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
680 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
682 $scope.initTab('bills', $routeParams.id);
683 billSvc.userId = $routeParams.id;
684 $scope.bill_tab = $routeParams.history_tab;
687 // link page controller actions defined by sub-controllers here
690 var start = new Date(); // now - 1 year
691 start.setFullYear(start.getFullYear() - 1),
694 xact_finish : new Date()
697 $scope.date_range = function() {
698 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
699 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
700 var today = new Date().toISOString().replace(/T.*/,'');
701 if (end == today) end = 'now';
707 .controller('BillXactHistoryCtrl',
708 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
709 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
711 // generate a grid query with the current date widget values.
712 function current_grid_query() {
715 {'summary.balance_owed' : {'<>' : 0}},
716 {'summary.last_payment_ts' : {'<>' : null}}
718 xact_start : {between : $scope.date_range()},
723 $scope.gridControls = {
724 selectedItems : function(){return []},
725 activateItem : function(item) {
726 $scope.showFullDetails([item]);
728 // this sets the query on page load
729 setQuery : current_grid_query
732 $scope.actions.apply_date_range = function() {
733 // tells the grid to re-draw itself with the new query
734 $scope.gridControls.setQuery(current_grid_query());
737 // TODO; move me to service
738 function selected_payment_info() {
739 var info = {owed : 0, billed : 0, paid : 0};
740 angular.forEach($scope.gridControls.selectedItems(), function(item) {
741 info.owed += Number(item['summary.balance_owed']) * 100;
742 info.billed += Number(item['summary.total_owed']) * 100;
743 info.paid += Number(item['summary.total_paid']) * 100;
751 $scope.totals.selected_billed = function() {
752 return selected_payment_info().billed;
754 $scope.totals.selected_paid = function() {
755 return selected_payment_info().paid;
758 $scope.showFullDetails = function(all) {
760 $location.path('/circ/patron/' +
761 patronSvc.current.id() + '/bill/' + all[0].id);
764 // For now, only adds billing to first selected item.
765 // Could do batches later if needed
766 $scope.addBilling = function(all) {
768 egBilling.showBillDialog({
769 xact : egCore.idl.flatToNestedHash(all[0]),
770 patron : $scope.patron()
772 $scope.gridControls.refresh();
773 patronSvc.fetchUserStats();
779 .controller('BillPaymentHistoryCtrl',
780 ['$scope','$q','egCore','patronSvc','billSvc','$location',
781 function($scope, $q , egCore , patronSvc , billSvc , $location) {
783 // generate a grid query with the current date widget values.
784 function current_grid_query() {
786 'payment_ts' : {between : $scope.date_range()},
787 'xact.usr' : billSvc.userId
791 $scope.gridControls = {
792 selectedItems : function(){return []},
793 activateItem : function(item) {
794 $scope.showFullDetails([item]);
796 setSort : function() {
797 return [{'payment_ts' : 'DESC'}, 'id'];
799 setQuery : current_grid_query
802 $scope.actions.apply_date_range = function() {
803 // tells the grid to re-draw itself with the new query
804 $scope.gridControls.setQuery(current_grid_query());
807 $scope.showFullDetails = function(all) {
809 $location.path('/circ/patron/' +
810 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
813 $scope.totals.selected_paid = function() {
815 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
816 paid += Number(payment.amount) * 100;