4 angular.module('egPatronApp')
7 ['$q','egCore','patronSvc',
8 function($q , egCore , 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']
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 if (evt = egCore.evt.parse(resp))
45 // payment API returns the update xact id so we can track it
46 // for future payments without having to refresh the user.
47 patronSvc.current.last_xact_id(resp.last_xact_id);
52 service.fetchBills = function(xact_id) {
54 return egCore.pcrud.search('mb',
55 {xact : xact_id}, null,
56 {authoritative : true}
58 function() {return bills},
60 function(bill) {bills.push(bill); return bill}
64 // TODO: no longer needed?
65 service.fetchPayments = function(xact_id) {
66 return egCore.net.request(
68 'open-ils.circ.money.payment.retrieve.all.authoritative',
69 egCore.auth.token(), xact_id
73 service.voidBills = function(bill_ids) {
74 return egCore.net.requestWithParamList(
76 'open-ils.circ.money.billing.void',
77 [egCore.auth.token()].concat(bill_ids)
78 ).then(function(resp) {
79 if (evt = egCore.evt.parse(resp)) return alert(evt);
84 service.updateBillNotes = function(note, ids) {
85 return egCore.net.requestWithParamList(
87 'open-ils.circ.money.billing.note.edit',
88 [egCore.auth.token(), note].concat(ids)
89 ).then(function(resp) {
90 if (evt = egCore.evt.parse(resp)) return alert(evt);
95 service.updatePaymentNotes = function(note, ids) {
96 return egCore.net.requestWithParamList(
98 'open-ils.circ.money.payment.note.edit',
99 [egCore.auth.token(), note].concat(ids)
100 ).then(function(resp) {
101 if (evt = egCore.evt.parse(resp)) return alert(evt);
113 .controller('PatronBillsCtrl',
114 ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
115 'egGridDataProvider','billSvc','patronSvc','egPromptDialog','$modal',
117 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
118 egGridDataProvider , billSvc , patronSvc , egPromptDialog , $modal,
121 $scope.initTab('bills', $routeParams.id);
122 billSvc.userId = $routeParams.id;
124 // set up some defaults
125 $scope.check_number = 0;
126 $scope.payment_amount = 0;
127 $scope.session_voided = 0;
128 $scope.payment_type = 'cash_payment';
129 $scope.focus_payment = true;
130 $scope.annotate_payment = false;
131 $scope.receipt_count = 1;
132 $scope.receipt_on_pay = false;
134 // pre-define list-returning funcs in case we access them
135 // before the grid instantiates
136 $scope.gridControls = {
137 focusRowSelector : false,
138 selectedItems : function(){return []},
139 allItems : function(){return []},
140 itemRetrieved : function(item) {
141 item.payment_pending = 0;
143 activateItem : function(item) {
144 $scope.showFullDetails([item]);
146 setQuery : function() {
148 usr : billSvc.userId,
150 'summary.balance_owed' : {'<>' : 0}
153 setSort : function() {
154 return ['xact_start'];
158 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
160 // given a payment amount, determines how much of that is applied
161 // to selected transactions and how much is left over (change).
162 function pending_payment_info() {
163 var amt = $scope.payment_amount || 0;
164 if (amt >= $scope.owed_selected()) {
166 payment : $scope.owed_selected(),
167 change : amt - $scope.owed_selected()
170 return {payment : amt, change : 0};
173 // calculates amount owed, billed, and paid for selected items
174 // TODO: move me to service
175 function selected_payment_info() {
176 var info = {owed : 0, billed : 0, paid : 0};
177 angular.forEach($scope.gridControls.selectedItems(), function(item) {
178 info.owed += Number(item['summary.balance_owed']) * 100;
179 info.billed += Number(item['summary.total_owed']) * 100;
180 info.paid += Number(item['summary.total_paid']) * 100;
188 $scope.pending_payment = function() {
189 return pending_payment_info().payment;
191 $scope.pending_change = function() {
192 return pending_payment_info().change;
194 $scope.owed_selected = function() {
195 return selected_payment_info().owed;
197 $scope.billed_selected = function() {
198 return selected_payment_info().billed;
200 $scope.paid_selected = function() {
201 return selected_payment_info().paid;
203 $scope.refunds_available = function() {
205 angular.forEach($scope.gridControls.allItems(), function(item) {
206 if (item['summary.balance_owed'] < 0)
207 amount += item['summary.balance_owed'] * 100;
209 return -(amount / 100);
212 // update the item.payment_pending value each time the user
213 // selects different transactions to pay against.
215 function() {return $scope.gridControls.selectedItems()},
216 function() {updatePendingColumn()},
220 // update the item.payment_pending for each (selected)
221 // transaction any time the user-entered payment amount is modified
222 $scope.$watch('payment_amount', updatePendingColumn);
224 // updates the value of the payment_pending column in the grid.
225 // This has to be managed manually since the display value in the grid
226 // is derived from the value on the stored item and not the contents
227 // of our local scope variables.
228 function updatePendingColumn() {
229 // reset all to zero..
230 angular.forEach($scope.gridControls.allItems(),
231 function(item) {item.payment_pending = 0});
233 var payment_amount = $scope.pending_payment();
235 var selected = $scope.gridControls.selectedItems();
236 for (var i = 0; i < selected.length; i++) { // for/break
237 var item = selected[i];
238 var owed = Number(item['summary.balance_owed']);
240 if (payment_amount > owed) {
241 // pending payment exceeds balance of current item.
242 // pay the entire item.
243 item.payment_pending = owed;
244 payment_amount -= owed;
247 // balance owed on the current item matches or exceeds
248 // the pending payment. Apply the full remainder of
249 // the payment to this item.. and we're done.
250 item.payment_pending = payment_amount;
256 // builds payment arrays ([xact_id, ammount]) for all transactions
257 // which have a pending payment amount.
258 function generatePayments() {
260 angular.forEach($scope.gridControls.selectedItems(), function(item) {
261 if (item.payment_pending == 0) return;
262 payments.push([item.id, item.payment_pending]);
267 function refreshDisplay() {
268 patronSvc.fetchUserStats();
269 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
270 $scope.payment_amount = 0;
271 $scope.gridControls.refresh();
274 // generates payments, collects user note if needed, and sends payment
276 function sendPayment(note) {
277 var make_payments = generatePayments();
278 billSvc.applyPayment(
279 $scope.payment_type, make_payments, note, $scope.check_number)
280 .then(function(payment_ids) {
282 if ($scope.receipt_on_pay) {
284 $scope.payment_type, payment_ids, make_payments, note);
291 function printReceipt(type, payment_ids, payments_made, note) {
292 var payment_blobs = [];
293 angular.forEach(payments_made, function(payment) {
294 var xact_id = payment[0];
296 // find the original transaction in the grid..
297 var xact = $scope.gridControls.allItems().filter(
298 function(item) {return item.id == xact_id})[0];
301 xact : egCore.idl.flatToNestedHash(xact),
306 console.log(js2JSON(payment_blobs[0]));
308 // page data not yet refreshed, capture data from current scope
311 previous_balance : Number($scope.summary.balance_owed()),
312 payment_total : Number($scope.payment_amount),
313 payment_applied : $scope.pending_payment(),
314 amount_voided : Number($scope.session_voided),
315 change_given : $scope.pending_change(),
316 payments : payment_blobs,
317 current_location : egCore.idl.toHash(
318 egCore.org.get(egCore.auth.user().ws_ou()))
321 print_data.new_balance = (
322 print_data.previous_balance * 100 -
323 print_data.payment_applied * 100) / 100;
325 for (var i = 0; i < $scope.receipt_count; i++) {
328 template : 'bill_payment',
334 $scope.showHistory = function() {
335 $location.path('/circ/patron/' +
336 patronSvc.current.id() + '/bill_history/transactions');
339 // For now, only adds billing to first selected item.
340 // Could do batches later if needed
341 $scope.addBilling = function(all) {
343 egBilling.showBillDialog({
344 xact : egCore.idl.flatToNestedHash(all[0]),
345 patron : $scope.patron()
346 }).then(refreshDisplay);
350 $scope.showBillDialog = function($event) {
351 egBilling.showBillDialog({
352 patron : $scope.patron()
353 }).then(refreshDisplay);
356 // Select refunds adds all refunds to the existing selection.
357 // It does not /only/ select refunds
358 $scope.selectRefunds = function() {
359 var ids = $scope.gridControls.selectedItems().map(
360 function(i) { return i.id });
361 angular.forEach($scope.gridControls.allItems(), function(item) {
362 if (Number(item['summary.balance_owed']) < 0)
365 $scope.gridControls.selectItems(ids);
369 // determine on initial page load when all of the grid rows should
371 var selectOnLoad = true;
372 billSvc.fetchBillSettings().then(function(s) {
373 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
374 $scope.focus_payment = false; // de-focus the payment box
375 $scope.gridControls.focusRowSelector = true;
376 selectOnLoad = false;
377 // if somehow the grid finishes rendering before our settings
378 // arrive, manually de-select everything.
379 $scope.gridControls.selectItems([]);
383 $scope.gridControls.allItemsRetrieved = function() {
385 selectOnLoad = false; // only for initial controller load.
386 // select all non-refund items
387 $scope.gridControls.selectItems(
388 $scope.gridControls.allItems()
389 .filter(function(i) {return i['summary.balance_owed'] > 0})
390 .map(function(i){return i.id})
397 $scope.printBills = function(selected) {
398 if (!selected.length) return;
399 // bills print receipt assumes nested hashes, but our grid
400 // stores flattener data. Fetch the selected xacts as
401 // fleshed pcrud objects and hashify.
402 // (Consider an alternate approach..)
403 var ids = selected.map(function(t){ return t.id });
405 egCore.pcrud.search('mbt',
407 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
408 {authoritative : true}
413 template : 'bills_current',
415 transactions : xacts,
416 current_location : egCore.idl.toHash(
417 egCore.org.get(egCore.auth.user().ws_ou()))
423 xacts.push(egCore.idl.toHash(xact));
428 $scope.applyPayment = function() {
429 if ($scope.annotate_payment) {
431 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
432 {ok : function(value) {sendPayment(value)}}
439 $scope.voidAllBillings = function(items) {
440 angular.forEach(items, function(item) {
442 billSvc.fetchBills(item.id).then(function(bills) {
445 angular.forEach(bills, function(b) {
446 if (b.voided() != 't') {
447 cents += b.amount() * 100;
448 bill_ids.push(b.id())
452 $scope.session_voided =
453 ($scope.session_voided * 100 + cents) / 100;
455 if (bill_ids.length == 0) {
460 // TODO: alert of pending voiding
462 billSvc.voidBills(bill_ids).then(function() {
469 // note this is functionally equivalent to selecting a neg. transaction
470 // then clicking Apply Payment -- this just adds a speed bump (ditto
472 $scope.refundXact = function(all) {
473 var items = all.filter(function(item) {
474 return item['summary.balance_owed'] < 0
477 if (items.length == 0) return;
479 var ids = items.map(function(item) {return item.id});
481 egConfirmDialog.open(
482 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
485 // reset the received payment amount. this ensures
486 // we're not mingling payments with refunds.
487 $scope.payment_amount = 0;
493 // direct the user to the transaction details page
494 $scope.showFullDetails = function(all) {
496 $location.path('/circ/patron/' +
497 patronSvc.current.id() + '/bill/' + all[0].id);
500 $scope.activateBill = function(xact) {
501 $scope.showFullDetails([xact]);
507 * Displays details of a single transaction
509 .controller('XactDetailsCtrl',
510 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
511 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
513 $scope.initTab('bills', $routeParams.id);
514 var xact_id = $routeParams.xact_id;
516 var xactGrid = $scope.xactGridControls = {
517 setQuery : function() { return {xact : xact_id} },
518 setSort : function() { return ['billing_ts'] }
521 var paymentGrid = $scope.paymentGridControls = {
522 setQuery : function() { return {xact : xact_id} },
523 setSort : function() { return ['payment_ts'] }
527 $scope.voidBillings = function(bill_list) {
529 angular.forEach(bill_list, function(b) {
530 if (b.voided != 't') bill_ids.push(b.id);
533 if (bill_ids.length == 0) {
538 billSvc.voidBills(bill_ids).then(function() {
540 // refresh bills and summary data
541 // note: no need to update payments
542 patronSvc.fetchUserStats();
544 egBilling.fetchXact(xact_id).then(function(xact) {
552 // batch-edit billing and payment notes, depending on 'type'
553 function editNotes(selected, type) {
554 var notes = selected.map(function(b){ return b.note }).join(',');
555 var ids = selected.map(function(b){ return b.id });
557 // show the note edit prompt
559 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
561 ok : function(value) {
563 var func = 'updateBillNotes';
564 if (type == 'payment') func = 'updatePaymentNotes';
566 billSvc[func](value, ids).then(function() {
567 if (type == 'payment') {
568 paymentGrid.refresh();
578 $scope.editBillNotes = function(selected) {
579 editNotes(selected, 'bill');
582 $scope.editPaymentNotes = function(selected) {
583 editNotes(selected, 'payment');
586 // -- retrieve our data
587 egBilling.fetchXact(xact_id).then(function(xact) {
590 // set the title. only needs to be done on initial page load
591 if (xact.circulation()) {
592 if (xact.circulation().target_copy().call_number().id() == -1) {
593 $scope.title = xact.circulation().target_copy().dummy_title();
595 // TODO: shared bib service?
596 $scope.title = xact.circulation().target_copy()
597 .call_number().record().simple_record().title();
598 $scope.title_id = xact.circulation().target_copy()
599 .call_number().record().id();
606 .controller('BillHistoryCtrl',
607 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
608 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
610 $scope.initTab('bills', $routeParams.id);
611 billSvc.userId = $routeParams.id;
612 $scope.bill_tab = $routeParams.history_tab;
615 var start = new Date(); // now - 1 year
616 start.setFullYear(start.getFullYear() - 1),
619 xact_finish : new Date()
622 $scope.date_range = function() {
623 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
624 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
625 var today = new Date().toISOString().replace(/T.*/,'');
626 if (end == today) end = 'now';
632 .controller('BillXactHistoryCtrl',
633 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
634 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
636 $scope.gridControls = {
637 selectedItems : function(){return []},
638 activateItem : function(item) {
639 $scope.showFullDetails([item]);
641 setQuery : function() {
642 // open-ils.actor.user.transactions.history.have_bill_or_payment
645 {'summary.balance_owed' : {'<>' : 0}},
646 {'summary.last_payment_ts' : {'<>' : null}}
648 xact_start : {between : $scope.date_range()},
655 // TODO; move me to service
656 function selected_payment_info() {
657 var info = {owed : 0, billed : 0, paid : 0};
658 angular.forEach($scope.gridControls.selectedItems(), function(item) {
659 info.owed += Number(item['summary.balance_owed']) * 100;
660 info.billed += Number(item['summary.total_owed']) * 100;
661 info.paid += Number(item['summary.total_paid']) * 100;
669 $scope.totals.selected_billed = function() {
670 return selected_payment_info().billed;
672 $scope.totals.selected_paid = function() {
673 return selected_payment_info().paid;
676 $scope.showFullDetails = function(all) {
678 $location.path('/circ/patron/' +
679 patronSvc.current.id() + '/bill/' + all[0].id);
682 // For now, only adds billing to first selected item.
683 // Could do batches later if needed
684 $scope.addBilling = function(all) {
686 egBilling.showBillDialog({
687 xact : egCore.idl.flatToNestedHash(all[0]),
688 patron : $scope.patron()
690 $scope.gridControls.refresh();
691 patronSvc.fetchUserStats();
697 .controller('BillPaymentHistoryCtrl',
698 ['$scope','$q','egCore','patronSvc','billSvc','$location',
699 function($scope, $q , egCore , patronSvc , billSvc , $location) {
701 $scope.gridControls = {
702 selectedItems : function(){return []},
703 activateItem : function(item) {
704 $scope.showFullDetails([item]);
706 setSort : function() {
707 return [{'payment_ts' : 'DESC'}, 'id'];
709 setQuery : function() {
711 'payment_ts' : {between : $scope.date_range()},
712 'xact.usr' : billSvc.userId
717 $scope.showFullDetails = function(all) {
719 $location.path('/circ/patron/' +
720 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
723 $scope.totals.selected_paid = function() {
725 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
726 paid += Number(payment.amount) * 100;