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', 'egBilling',
116 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
117 egGridDataProvider , billSvc , patronSvc , egPromptDialog, egBilling) {
119 $scope.initTab('bills', $routeParams.id);
120 billSvc.userId = $routeParams.id;
122 // set up some defaults
123 $scope.check_number = 0;
124 $scope.payment_amount = null;
125 $scope.session_voided = 0;
126 $scope.payment_type = 'cash_payment';
127 $scope.focus_payment = true;
128 $scope.annotate_payment = false;
129 $scope.receipt_count = 1;
130 $scope.receipt_on_pay = false;
132 // pre-define list-returning funcs in case we access them
133 // before the grid instantiates
134 $scope.gridControls = {
135 focusRowSelector : false,
136 selectedItems : function(){return []},
137 allItems : function(){return []},
138 itemRetrieved : function(item) {
139 item.payment_pending = 0;
141 activateItem : function(item) {
142 $scope.showFullDetails([item]);
144 setQuery : function() {
146 usr : billSvc.userId,
148 'summary.balance_owed' : {'<>' : 0}
151 setSort : function() {
152 return ['xact_start'];
156 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
158 // given a payment amount, determines how much of that is applied
159 // to selected transactions and how much is left over (change).
160 function pending_payment_info() {
161 var amt = $scope.payment_amount || 0;
162 if (amt >= $scope.owed_selected()) {
164 payment : $scope.owed_selected(),
165 change : amt - $scope.owed_selected()
168 return {payment : amt, change : 0};
171 // calculates amount owed, billed, and paid for selected items
172 // TODO: move me to service
173 function selected_payment_info() {
174 var info = {owed : 0, billed : 0, paid : 0};
175 angular.forEach($scope.gridControls.selectedItems(), function(item) {
176 info.owed += Number(item['summary.balance_owed']) * 100;
177 info.billed += Number(item['summary.total_owed']) * 100;
178 info.paid += Number(item['summary.total_paid']) * 100;
186 $scope.pending_payment = function() {
187 return pending_payment_info().payment;
189 $scope.pending_change = function() {
190 return pending_payment_info().change;
192 $scope.owed_selected = function() {
193 return selected_payment_info().owed;
195 $scope.billed_selected = function() {
196 return selected_payment_info().billed;
198 $scope.paid_selected = function() {
199 return selected_payment_info().paid;
201 $scope.refunds_available = function() {
203 angular.forEach($scope.gridControls.allItems(), function(item) {
204 if (item['summary.balance_owed'] < 0)
205 amount += item['summary.balance_owed'] * 100;
207 return -(amount / 100);
210 // update the item.payment_pending value each time the user
211 // selects different transactions to pay against.
213 function() {return $scope.gridControls.selectedItems()},
214 function() {updatePendingColumn()},
218 // update the item.payment_pending for each (selected)
219 // transaction any time the user-entered payment amount is modified
220 $scope.$watch('payment_amount', updatePendingColumn);
222 // updates the value of the payment_pending column in the grid.
223 // This has to be managed manually since the display value in the grid
224 // is derived from the value on the stored item and not the contents
225 // of our local scope variables.
226 function updatePendingColumn() {
227 // reset all to zero..
228 angular.forEach($scope.gridControls.allItems(),
229 function(item) {item.payment_pending = 0});
231 var payment_amount = $scope.pending_payment();
233 var selected = $scope.gridControls.selectedItems();
234 for (var i = 0; i < selected.length; i++) { // for/break
235 var item = selected[i];
236 var owed = Number(item['summary.balance_owed']);
238 if (payment_amount > owed) {
239 // pending payment exceeds balance of current item.
240 // pay the entire item.
241 item.payment_pending = owed;
242 payment_amount -= owed;
245 // balance owed on the current item matches or exceeds
246 // the pending payment. Apply the full remainder of
247 // the payment to this item.. and we're done.
248 item.payment_pending = payment_amount;
254 // builds payment arrays ([xact_id, ammount]) for all transactions
255 // which have a pending payment amount.
256 function generatePayments() {
258 angular.forEach($scope.gridControls.selectedItems(), function(item) {
259 if (item.payment_pending == 0) return;
260 payments.push([item.id, item.payment_pending]);
265 function refreshDisplay() {
266 patronSvc.fetchUserStats();
267 billSvc.fetchSummary().then(function(s) {$scope.summary = s});
268 $scope.payment_amount = null;
269 $scope.gridControls.refresh();
272 // generates payments, collects user note if needed, and sends payment
274 function sendPayment(note) {
275 var make_payments = generatePayments();
276 billSvc.applyPayment(
277 $scope.payment_type, make_payments, note, $scope.check_number)
278 .then(function(payment_ids) {
280 if ($scope.receipt_on_pay) {
282 $scope.payment_type, payment_ids, make_payments, note);
289 function printReceipt(type, payment_ids, payments_made, note) {
290 var payment_blobs = [];
291 angular.forEach(payments_made, function(payment) {
292 var xact_id = payment[0];
294 // find the original transaction in the grid..
295 var xact = $scope.gridControls.allItems().filter(
296 function(item) {return item.id == xact_id})[0];
299 xact : egCore.idl.flatToNestedHash(xact),
304 console.log(js2JSON(payment_blobs[0]));
306 // page data not yet refreshed, capture data from current scope
309 previous_balance : Number($scope.summary.balance_owed()),
310 payment_total : Number($scope.payment_amount),
311 payment_applied : $scope.pending_payment(),
312 amount_voided : Number($scope.session_voided),
313 change_given : $scope.pending_change(),
314 payments : payment_blobs,
315 current_location : egCore.idl.toHash(
316 egCore.org.get(egCore.auth.user().ws_ou()))
319 print_data.new_balance = (
320 print_data.previous_balance * 100 -
321 print_data.payment_applied * 100) / 100;
323 for (var i = 0; i < $scope.receipt_count; i++) {
326 template : 'bill_payment',
332 $scope.showHistory = function() {
333 $location.path('/circ/patron/' +
334 patronSvc.current.id() + '/bill_history/transactions');
337 // For now, only adds billing to first selected item.
338 // Could do batches later if needed
339 $scope.addBilling = function(all) {
341 egBilling.showBillDialog({
342 xact : egCore.idl.flatToNestedHash(all[0]),
343 patron : $scope.patron()
344 }).then(refreshDisplay);
348 $scope.showBillDialog = function($event) {
349 egBilling.showBillDialog({
350 patron : $scope.patron()
351 }).then(refreshDisplay);
354 // Select refunds adds all refunds to the existing selection.
355 // It does not /only/ select refunds
356 $scope.selectRefunds = function() {
357 var ids = $scope.gridControls.selectedItems().map(
358 function(i) { return i.id });
359 angular.forEach($scope.gridControls.allItems(), function(item) {
360 if (Number(item['summary.balance_owed']) < 0)
363 $scope.gridControls.selectItems(ids);
367 // determine on initial page load when all of the grid rows should
369 var selectOnLoad = true;
370 billSvc.fetchBillSettings().then(function(s) {
371 if (s['ui.circ.billing.uncheck_bills_and_unfocus_payment_box']) {
372 $scope.focus_payment = false; // de-focus the payment box
373 $scope.gridControls.focusRowSelector = true;
374 selectOnLoad = false;
375 // if somehow the grid finishes rendering before our settings
376 // arrive, manually de-select everything.
377 $scope.gridControls.selectItems([]);
381 $scope.gridControls.allItemsRetrieved = function() {
383 selectOnLoad = false; // only for initial controller load.
384 // select all non-refund items
385 $scope.gridControls.selectItems(
386 $scope.gridControls.allItems()
387 .filter(function(i) {return i['summary.balance_owed'] > 0})
388 .map(function(i){return i.id})
395 $scope.printBills = function(selected) {
396 if (!selected.length) return;
397 // bills print receipt assumes nested hashes, but our grid
398 // stores flattener data. Fetch the selected xacts as
399 // fleshed pcrud objects and hashify.
400 // (Consider an alternate approach..)
401 var ids = selected.map(function(t){ return t.id });
403 egCore.pcrud.search('mbt',
405 {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
406 {authoritative : true}
411 template : 'bills_current',
413 transactions : xacts,
414 current_location : egCore.idl.toHash(
415 egCore.org.get(egCore.auth.user().ws_ou()))
421 xacts.push(egCore.idl.toHash(xact));
426 $scope.applyPayment = function() {
427 if ($scope.annotate_payment) {
429 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
430 {ok : function(value) {sendPayment(value)}}
437 $scope.voidAllBillings = function(items) {
438 angular.forEach(items, function(item) {
440 billSvc.fetchBills(item.id).then(function(bills) {
443 angular.forEach(bills, function(b) {
444 if (b.voided() != 't') {
445 cents += b.amount() * 100;
446 bill_ids.push(b.id())
450 $scope.session_voided =
451 ($scope.session_voided * 100 + cents) / 100;
453 if (bill_ids.length == 0) {
458 // TODO: alert of pending voiding
460 billSvc.voidBills(bill_ids).then(function() {
467 // note this is functionally equivalent to selecting a neg. transaction
468 // then clicking Apply Payment -- this just adds a speed bump (ditto
470 $scope.refundXact = function(all) {
471 var items = all.filter(function(item) {
472 return item['summary.balance_owed'] < 0
475 if (items.length == 0) return;
477 var ids = items.map(function(item) {return item.id});
479 egConfirmDialog.open(
480 egCore.strings.CONFIRM_REFUND_PAYMENT, '',
483 // reset the received payment amount. this ensures
484 // we're not mingling payments with refunds.
485 $scope.payment_amount = 0;
491 // direct the user to the transaction details page
492 $scope.showFullDetails = function(all) {
494 $location.path('/circ/patron/' +
495 patronSvc.current.id() + '/bill/' + all[0].id);
498 $scope.activateBill = function(xact) {
499 $scope.showFullDetails([xact]);
505 * Displays details of a single transaction
507 .controller('XactDetailsCtrl',
508 ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
509 function($scope, $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
511 $scope.initTab('bills', $routeParams.id);
512 var xact_id = $routeParams.xact_id;
514 var xactGrid = $scope.xactGridControls = {
515 setQuery : function() { return {xact : xact_id} },
516 setSort : function() { return ['billing_ts'] }
519 var paymentGrid = $scope.paymentGridControls = {
520 setQuery : function() { return {xact : xact_id} },
521 setSort : function() { return ['payment_ts'] }
525 $scope.voidBillings = function(bill_list) {
527 angular.forEach(bill_list, function(b) {
528 if (b.voided != 't') bill_ids.push(b.id);
531 if (bill_ids.length == 0) {
536 billSvc.voidBills(bill_ids).then(function() {
538 // refresh bills and summary data
539 // note: no need to update payments
540 patronSvc.fetchUserStats();
542 egBilling.fetchXact(xact_id).then(function(xact) {
550 // batch-edit billing and payment notes, depending on 'type'
551 function editNotes(selected, type) {
552 var notes = selected.map(function(b){ return b.note }).join(',');
553 var ids = selected.map(function(b){ return b.id });
555 // show the note edit prompt
557 egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
559 ok : function(value) {
561 var func = 'updateBillNotes';
562 if (type == 'payment') func = 'updatePaymentNotes';
564 billSvc[func](value, ids).then(function() {
565 if (type == 'payment') {
566 paymentGrid.refresh();
576 $scope.editBillNotes = function(selected) {
577 editNotes(selected, 'bill');
580 $scope.editPaymentNotes = function(selected) {
581 editNotes(selected, 'payment');
584 // -- retrieve our data
585 $scope.total_circs = 0; // start with 0 instead of undefined
586 egBilling.fetchXact(xact_id).then(function(xact) {
589 var copyId = xact.circulation().target_copy().id();
591 egCore.pcrud.search('circbyyr',
592 {copy : copyId}, null, {atomic : true})
593 .then(function(counts) {
594 angular.forEach(counts, function(count) {
595 circ_count += Number(count.count());
597 $scope.total_circs = circ_count;
599 // set the title. only needs to be done on initial page load
600 if (xact.circulation()) {
601 if (xact.circulation().target_copy().call_number().id() == -1) {
602 $scope.title = xact.circulation().target_copy().dummy_title();
604 // TODO: shared bib service?
605 $scope.title = xact.circulation().target_copy()
606 .call_number().record().simple_record().title();
607 $scope.title_id = xact.circulation().target_copy()
608 .call_number().record().id();
615 .controller('BillHistoryCtrl',
616 ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
617 function($scope, $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
619 $scope.initTab('bills', $routeParams.id);
620 billSvc.userId = $routeParams.id;
621 $scope.bill_tab = $routeParams.history_tab;
624 // link page controller actions defined by sub-controllers here
627 var start = new Date(); // now - 1 year
628 start.setFullYear(start.getFullYear() - 1),
631 xact_finish : new Date()
634 $scope.date_range = function() {
635 var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
636 var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
637 var today = new Date().toISOString().replace(/T.*/,'');
638 if (end == today) end = 'now';
644 .controller('BillXactHistoryCtrl',
645 ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
646 function($scope, $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
648 // generate a grid query with the current date widget values.
649 function current_grid_query() {
652 {'summary.balance_owed' : {'<>' : 0}},
653 {'summary.last_payment_ts' : {'<>' : null}}
655 xact_start : {between : $scope.date_range()},
660 $scope.gridControls = {
661 selectedItems : function(){return []},
662 activateItem : function(item) {
663 $scope.showFullDetails([item]);
665 // this sets the query on page load
666 setQuery : current_grid_query
669 $scope.actions.apply_date_range = function() {
670 // tells the grid to re-draw itself with the new query
671 $scope.gridControls.setQuery(current_grid_query());
674 // TODO; move me to service
675 function selected_payment_info() {
676 var info = {owed : 0, billed : 0, paid : 0};
677 angular.forEach($scope.gridControls.selectedItems(), function(item) {
678 info.owed += Number(item['summary.balance_owed']) * 100;
679 info.billed += Number(item['summary.total_owed']) * 100;
680 info.paid += Number(item['summary.total_paid']) * 100;
688 $scope.totals.selected_billed = function() {
689 return selected_payment_info().billed;
691 $scope.totals.selected_paid = function() {
692 return selected_payment_info().paid;
695 $scope.showFullDetails = function(all) {
697 $location.path('/circ/patron/' +
698 patronSvc.current.id() + '/bill/' + all[0].id);
701 // For now, only adds billing to first selected item.
702 // Could do batches later if needed
703 $scope.addBilling = function(all) {
705 egBilling.showBillDialog({
706 xact : egCore.idl.flatToNestedHash(all[0]),
707 patron : $scope.patron()
709 $scope.gridControls.refresh();
710 patronSvc.fetchUserStats();
716 .controller('BillPaymentHistoryCtrl',
717 ['$scope','$q','egCore','patronSvc','billSvc','$location',
718 function($scope, $q , egCore , patronSvc , billSvc , $location) {
720 // generate a grid query with the current date widget values.
721 function current_grid_query() {
723 'payment_ts' : {between : $scope.date_range()},
724 'xact.usr' : billSvc.userId
728 $scope.gridControls = {
729 selectedItems : function(){return []},
730 activateItem : function(item) {
731 $scope.showFullDetails([item]);
733 setSort : function() {
734 return [{'payment_ts' : 'DESC'}, 'id'];
736 setQuery : current_grid_query
739 $scope.actions.apply_date_range = function() {
740 // tells the grid to re-draw itself with the new query
741 $scope.gridControls.setQuery(current_grid_query());
744 $scope.showFullDetails = function(all) {
746 $location.path('/circ/patron/' +
747 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
750 $scope.totals.selected_paid = function() {
752 angular.forEach($scope.gridControls.selectedItems(), function(payment) {
753 paid += Number(payment.amount) * 100;