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','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 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', 'egAlertDialog',
117 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
118 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egAlertDialog,
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 = null;
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;
133 $scope.warn_amount = 1000;
134 $scope.max_amount = 100000;
135 $scope.amount_verified = false;
137 // pre-define list-returning funcs in case we access them
138 // before the grid instantiates
139 $scope.gridControls = {
140 focusRowSelector : false,
141 selectedItems : function(){return []},
142 allItems : function(){return []},
143 itemRetrieved : function(item) {
144 item.payment_pending = 0;
146 activateItem : function(item) {
147 $scope.showFullDetails([item]);
149 setQuery : function() {
151 usr : billSvc.userId,
153 'summary.balance_owed' : {'<>' : 0}
156 setSort : function() {
157 return ['xact_start'];
161 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
163 // given a payment amount, determines how much of that is applied
164 // to selected transactions and how much is left over (change).
165 function pending_payment_info() {
166 var amt = $scope.payment_amount || 0;
167 if (amt >= $scope.owed_selected()) {
169 payment : $scope.owed_selected(),
170 change : amt - $scope.owed_selected()
173 return {payment : amt, change : 0};
176 // calculates amount owed, billed, and paid for selected items
177 // TODO: move me to service
178 function selected_payment_info() {
179 var info = {owed : 0, billed : 0, paid : 0};
180 angular.forEach($scope.gridControls.selectedItems(), function(item) {
181 info.owed += Number(item['summary.balance_owed']) * 100;
182 info.billed += Number(item['summary.total_owed']) * 100;
183 info.paid += Number(item['summary.total_paid']) * 100;
191 $scope.pending_payment = function() {
192 return pending_payment_info().payment;
194 $scope.pending_change = function() {
195 return pending_payment_info().change;
197 $scope.owed_selected = function() {
198 return selected_payment_info().owed;
200 $scope.billed_selected = function() {
201 return selected_payment_info().billed;
203 $scope.paid_selected = function() {
204 return selected_payment_info().paid;
206 $scope.refunds_available = function() {
208 angular.forEach($scope.gridControls.allItems(), function(item) {
209 if (item['summary.balance_owed'] < 0)
210 amount += item['summary.balance_owed'] * 100;
212 return -(amount / 100);
215 // update the item.payment_pending value each time the user
216 // selects different transactions to pay against.
218 function() {return $scope.gridControls.selectedItems()},
219 function() {updatePendingColumn()},
223 // update the item.payment_pending for each (selected)
224 // transaction any time the user-entered payment amount is modified
225 $scope.$watch('payment_amount', updatePendingColumn);
227 // updates the value of the payment_pending column in the grid.
228 // This has to be managed manually since the display value in the grid
229 // is derived from the value on the stored item and not the contents
230 // of our local scope variables.
231 function updatePendingColumn() {
232 // reset all to zero..
233 angular.forEach($scope.gridControls.allItems(),
234 function(item) {item.payment_pending = 0});
236 var payment_amount = $scope.pending_payment();
238 var selected = $scope.gridControls.selectedItems();
239 for (var i = 0; i < selected.length; i++) { // for/break
240 var item = selected[i];
241 var owed = Number(item['summary.balance_owed']);
243 if (payment_amount > owed) {
244 // pending payment exceeds balance of current item.
245 // pay the entire item.
246 item.payment_pending = owed;
247 payment_amount -= owed;
250 // balance owed on the current item matches or exceeds
251 // the pending payment. Apply the full remainder of
252 // the payment to this item.. and we're done.
253 item.payment_pending = payment_amount;
259 // builds payment arrays ([xact_id, ammount]) for all transactions
260 // which have a pending payment amount.
261 function generatePayments() {
263 angular.forEach($scope.gridControls.selectedItems(), function(item) {
264 if (item.payment_pending == 0) return;
265 payments.push([item.id, item.payment_pending]);
270 function refreshDisplay() {
271 patronSvc.fetchUserStats();
272 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
273 $scope.payment_amount = null;
274 $scope.gridControls.refresh();
277 // generates payments, collects user note if needed, and sends payment
279 function sendPayment(note) {
280 var make_payments = generatePayments();
281 billSvc.applyPayment(
282 $scope.payment_type, make_payments, note, $scope.check_number)
283 .then(function(payment_ids) {
285 if ($scope.receipt_on_pay) {
287 $scope.payment_type, payment_ids, make_payments, note);
294 function printReceipt(type, payment_ids, payments_made, note) {
295 var payment_blobs = [];
296 angular.forEach(payments_made, function(payment) {
297 var xact_id = payment[0];
299 // find the original transaction in the grid..
300 var xact = $scope.gridControls.allItems().filter(
301 function(item) {return item.id == xact_id})[0];
304 xact : egCore.idl.flatToNestedHash(xact),
309 console.log(js2JSON(payment_blobs[0]));
311 // page data not yet refreshed, capture data from current scope
314 previous_balance : Number($scope.summary.balance_owed()),
315 payment_total : Number($scope.payment_amount),
316 payment_applied : $scope.pending_payment(),
317 amount_voided : Number($scope.session_voided),
318 change_given : $scope.pending_change(),
319 payments : payment_blobs,
320 current_location : egCore.idl.toHash(
321 egCore.org.get(egCore.auth.user().ws_ou()))
324 print_data.new_balance = (
325 print_data.previous_balance * 100 -
326 print_data.payment_applied * 100) / 100;
328 for (var i = 0; i < $scope.receipt_count; i++) {
331 template : 'bill_payment',
337 $scope.showHistory = function() {
338 $location.path('/circ/patron/' +
339 patronSvc.current.id() + '/bill_history/transactions');
342 // For now, only adds billing to first selected item.
343 // Could do batches later if needed
344 $scope.addBilling = function(all) {
346 egBilling.showBillDialog({
347 xact : egCore.idl.flatToNestedHash(all[0]),
348 patron : $scope.patron()
349 }).then(refreshDisplay);
353 $scope.showBillDialog = function($event) {
354 egBilling.showBillDialog({
355 patron : $scope.patron()
356 }).then(refreshDisplay);
359 // Select refunds adds all refunds to the existing selection.
360 // It does not /only/ select refunds
361 $scope.selectRefunds = function() {
362 var ids = $scope.gridControls.selectedItems().map(
363 function(i) { return i.id });
364 angular.forEach($scope.gridControls.allItems(), function(item) {
365 if (Number(item['summary.balance_owed']) < 0)
368 $scope.gridControls.selectItems(ids);
372 // determine on initial page load when all of the grid rows should
374 var selectOnLoad = true;
375 billSvc.fetchBillSettings().then(function(s) {
376 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
377 $scope.focus_payment = false; // de-focus the payment box
378 $scope.gridControls.focusRowSelector = true;
379 selectOnLoad = false;
380 // if somehow the grid finishes rendering before our settings
381 // arrive, manually de-select everything.
382 $scope.gridControls.selectItems([]);
384 if (s['ui.circ.billing.amount_warn']) {
385 $scope.warn_amount = Number(s['ui.circ.billing.amount_warn']);
387 if (s['ui.circ.billing.amount_limit']) {
388 $scope.max_amount = Number(s['ui.circ.billing.amount_limit']);
392 $scope.gridControls.allItemsRetrieved = function() {
394 selectOnLoad = false; // only for initial controller load.
395 // select all non-refund items
396 $scope.gridControls.selectItems(
397 $scope.gridControls.allItems()
398 .filter(function(i) {return i['summary.balance_owed'] > 0})
399 .map(function(i){return i.id})
406 $scope.printBills = function(selected) {
407 if (!selected.length) return;
408 // bills print receipt assumes nested hashes, but our grid
409 // stores flattener data. Fetch the selected xacts as
410 // fleshed pcrud objects and hashify.
411 // (Consider an alternate approach..)
412 var ids = selected.map(function(t){ return t.id });
414 egCore.pcrud.search('mbt',
416 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
417 {authoritative : true}
422 template : 'bills_current',
424 transactions : xacts,
425 current_location : egCore.idl.toHash(
426 egCore.org.get(egCore.auth.user().ws_ou()))
432 xacts.push(egCore.idl.toHash(xact));
437 $scope.applyPayment = function() {
439 if ($scope.payment_amount > $scope.max_amount ) {
441 egCore.strings.PAYMENT_OVER_MAX,
442 { max_amount : ''+$scope.max_amount,
444 $scope.payment_amount = 0;
451 if (($scope.payment_amount > $scope.warn_amount) && ($scope.amount_verified == false)) {
452 egConfirmDialog.open(
453 egCore.strings.PAYMENT_WARN_AMOUNT_TITLE, egCore.strings.PAYMENT_WARN_AMOUNT,
454 { payment_amount : ''+$scope.payment_amount,
456 $scope.amount_verfied = true;
457 $scope.applyPayment();
459 cancel : function() {
460 $scope.payment_amount = 0;
467 $scope.amount_verfied = false;
469 if ($scope.annotate_payment) {
471 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
472 {ok : function(value) {sendPayment(value)}}
479 $scope.voidAllBillings = function(items) {
480 angular.forEach(items, function(item) {
482 billSvc.fetchBills(item.id).then(function(bills) {
485 angular.forEach(bills, function(b) {
486 if (b.voided() != 't') {
487 cents += b.amount() * 100;
488 bill_ids.push(b.id())
492 $scope.session_voided =
493 ($scope.session_voided * 100 + cents) / 100;
495 if (bill_ids.length == 0) {
500 // TODO: alert of pending voiding
502 billSvc.voidBills(bill_ids).then(function() {
509 // note this is functionally equivalent to selecting a neg. transaction
510 // then clicking Apply Payment -- this just adds a speed bump (ditto
512 $scope.refundXact = function(all) {
513 var items = all.filter(function(item) {
514 return item['summary.balance_owed'] < 0
517 if (items.length == 0) return;
519 var ids = items.map(function(item) {return item.id});
521 egConfirmDialog.open(
522 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
525 // reset the received payment amount. this ensures
526 // we're not mingling payments with refunds.
527 $scope.payment_amount = 0;
533 // direct the user to the transaction details page
534 $scope.showFullDetails = function(all) {
536 $location.path('/circ/patron/' +
537 patronSvc.current.id() + '/bill/' + all[0].id);
540 $scope.activateBill = function(xact) {
541 $scope.showFullDetails([xact]);
547 * Displays details of a single transaction
549 .controller('XactDetailsCtrl',
550 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
551 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
553 $scope.initTab('bills', $routeParams.id);
554 var xact_id = $routeParams.xact_id;
556 var xactGrid = $scope.xactGridControls = {
557 setQuery : function() { return {xact : xact_id} },
558 setSort : function() { return ['billing_ts'] }
561 var paymentGrid = $scope.paymentGridControls = {
562 setQuery : function() { return {xact : xact_id} },
563 setSort : function() { return ['payment_ts'] }
567 $scope.voidBillings = function(bill_list) {
569 angular.forEach(bill_list, function(b) {
570 if (b.voided != 't') bill_ids.push(b.id);
573 if (bill_ids.length == 0) {
578 billSvc.voidBills(bill_ids).then(function() {
580 // refresh bills and summary data
581 // note: no need to update payments
582 patronSvc.fetchUserStats();
584 egBilling.fetchXact(xact_id).then(function(xact) {
592 // batch-edit billing and payment notes, depending on 'type'
593 function editNotes(selected, type) {
594 var notes = selected.map(function(b){ return b.note }).join(',');
595 var ids = selected.map(function(b){ return b.id });
597 // show the note edit prompt
599 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
601 ok : function(value) {
603 var func = 'updateBillNotes';
604 if (type == 'payment') func = 'updatePaymentNotes';
606 billSvc[func](value, ids).then(function() {
607 if (type == 'payment') {
608 paymentGrid.refresh();
618 $scope.editBillNotes = function(selected) {
619 editNotes(selected, 'bill');
622 $scope.editPaymentNotes = function(selected) {
623 editNotes(selected, 'payment');
626 // -- retrieve our data
627 $scope.total_circs = 0; // start with 0 instead of undefined
628 egBilling.fetchXact(xact_id).then(function(xact) {
631 var copyId = xact.circulation().target_copy().id();
633 egCore.pcrud.search('circbyyr',
634 {copy : copyId}, null, {atomic : true})
635 .then(function(counts) {
636 angular.forEach(counts, function(count) {
637 circ_count += Number(count.count());
639 $scope.total_circs = circ_count;
641 // set the title. only needs to be done on initial page load
642 if (xact.circulation()) {
643 if (xact.circulation().target_copy().call_number().id() == -1) {
644 $scope.title = xact.circulation().target_copy().dummy_title();
646 // TODO: shared bib service?
647 $scope.title = xact.circulation().target_copy()
648 .call_number().record().simple_record().title();
649 $scope.title_id = xact.circulation().target_copy()
650 .call_number().record().id();
657 .controller('BillHistoryCtrl',
658 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
659 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
661 $scope.initTab('bills', $routeParams.id);
662 billSvc.userId = $routeParams.id;
663 $scope.bill_tab = $routeParams.history_tab;
666 // link page controller actions defined by sub-controllers here
669 var start = new Date(); // now - 1 year
670 start.setFullYear(start.getFullYear() - 1),
673 xact_finish : new Date()
676 $scope.date_range = function() {
677 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
678 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
679 var today = new Date().toISOString().replace(/T.*/,'');
680 if (end == today) end = 'now';
686 .controller('BillXactHistoryCtrl',
687 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
688 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
690 // generate a grid query with the current date widget values.
691 function current_grid_query() {
694 {'summary.balance_owed' : {'<>' : 0}},
695 {'summary.last_payment_ts' : {'<>' : null}}
697 xact_start : {between : $scope.date_range()},
702 $scope.gridControls = {
703 selectedItems : function(){return []},
704 activateItem : function(item) {
705 $scope.showFullDetails([item]);
707 // this sets the query on page load
708 setQuery : current_grid_query
711 $scope.actions.apply_date_range = function() {
712 // tells the grid to re-draw itself with the new query
713 $scope.gridControls.setQuery(current_grid_query());
716 // TODO; move me to service
717 function selected_payment_info() {
718 var info = {owed : 0, billed : 0, paid : 0};
719 angular.forEach($scope.gridControls.selectedItems(), function(item) {
720 info.owed += Number(item['summary.balance_owed']) * 100;
721 info.billed += Number(item['summary.total_owed']) * 100;
722 info.paid += Number(item['summary.total_paid']) * 100;
730 $scope.totals.selected_billed = function() {
731 return selected_payment_info().billed;
733 $scope.totals.selected_paid = function() {
734 return selected_payment_info().paid;
737 $scope.showFullDetails = function(all) {
739 $location.path('/circ/patron/' +
740 patronSvc.current.id() + '/bill/' + all[0].id);
743 // For now, only adds billing to first selected item.
744 // Could do batches later if needed
745 $scope.addBilling = function(all) {
747 egBilling.showBillDialog({
748 xact : egCore.idl.flatToNestedHash(all[0]),
749 patron : $scope.patron()
751 $scope.gridControls.refresh();
752 patronSvc.fetchUserStats();
758 .controller('BillPaymentHistoryCtrl',
759 ['$scope','$q','egCore','patronSvc','billSvc','$location',
760 function($scope, $q , egCore , patronSvc , billSvc , $location) {
762 // generate a grid query with the current date widget values.
763 function current_grid_query() {
765 'payment_ts' : {between : $scope.date_range()},
766 'xact.usr' : billSvc.userId
770 $scope.gridControls = {
771 selectedItems : function(){return []},
772 activateItem : function(item) {
773 $scope.showFullDetails([item]);
775 setSort : function() {
776 return [{'payment_ts' : 'DESC'}, 'id'];
778 setQuery : current_grid_query
781 $scope.actions.apply_date_range = function() {
782 // tells the grid to re-draw itself with the new query
783 $scope.gridControls.setQuery(current_grid_query());
786 $scope.showFullDetails = function(all) {
788 $location.path('/circ/patron/' +
789 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
792 $scope.totals.selected_paid = function() {
794 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
795 paid += Number(payment.amount) * 100;