]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/bills.js
80be1feac971c5f0306b2c0257549bca6cb62c9e
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / patron / bills.js
1
2 /* Billing Service */
3
4 angular.module('egPatronApp')
5
6 .factory('billSvc', 
7        ['$q','egCore','patronSvc',
8 function($q , egCore , patronSvc) {
9
10     var service = {};
11
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});
18     }
19
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})
25     }
26
27     service.applyPayment = function(type, payments, note, check) {
28         return egCore.net.request(
29             'open-ils.circ',
30             'open-ils.circ.money.payment',
31             egCore.auth.token(), {
32                 userid : service.userId,
33                 note : note || '', 
34                 payment_type : type,
35                 check_number : check,
36                 payments : payments,
37                 patron_credit : 0
38             },
39             patronSvc.current.last_xact_id()
40         ).then(function(resp) {
41             console.debug('payments: ' + js2JSON(resp));
42             if (evt = egCore.evt.parse(resp)) 
43                 return alert(evt);
44
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);
48             return resp.payments;
49         });
50     }
51
52     service.fetchBills = function(xact_id) {
53         var bills = [];
54         return egCore.pcrud.search('mb',
55             {xact : xact_id}, null,
56             {authoritative : true}
57         ).then(
58             function() {return bills},
59             null,
60             function(bill) {bills.push(bill); return bill}
61         );
62     }
63
64     // TODO: no longer needed?
65     service.fetchPayments = function(xact_id) {
66         return egCore.net.request(
67             'open-ils.circ',
68             'open-ils.circ.money.payment.retrieve.all.authoritative',
69             egCore.auth.token(), xact_id
70         );
71     }
72
73     service.voidBills = function(bill_ids) {
74         return egCore.net.requestWithParamList(
75             'open-ils.circ',
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);
80             return resp;
81         });
82     }
83
84     service.updateBillNotes = function(note, ids) {
85         return egCore.net.requestWithParamList(
86             'open-ils.circ',
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);
91             return resp;
92         });
93     }
94
95     service.updatePaymentNotes = function(note, ids) {
96         return egCore.net.requestWithParamList(
97             'open-ils.circ',
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);
102             return resp;
103         });
104     }
105
106     return service;
107 }])
108
109
110 /**
111  * Manages Bills
112  */
113 .controller('PatronBillsCtrl',
114        ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
115         'egGridDataProvider','billSvc','patronSvc','egPromptDialog','$modal',
116         'egBilling',
117 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
118          egGridDataProvider , billSvc , patronSvc , egPromptDialog , $modal,
119          egBilling) {
120
121     $scope.initTab('bills', $routeParams.id);
122     billSvc.userId = $routeParams.id;
123
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
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;
142         },
143         activateItem : function(item) {
144             $scope.showFullDetails([item]);
145         },
146         setQuery : function() {    
147             return {
148                 usr : billSvc.userId, 
149                 xact_finish : null,
150                 'summary.balance_owed' : {'<>' : 0}
151             }
152         }, 
153         setSort : function() {
154             return ['xact_start']; 
155         }
156     }
157
158     billSvc.fetchSummary().then(function(s) {$scope.summary = s});
159
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()) {
165             return {
166                 payment : $scope.owed_selected(),
167                 change : amt - $scope.owed_selected()
168             }
169         } 
170         return {payment : amt, change : 0};
171     }
172
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;
181         });
182         info.owed /= 100;
183         info.billed /= 100;
184         info.paid /= 100;
185         return info;
186     }
187
188     $scope.pending_payment = function() {
189         return pending_payment_info().payment;
190     }
191     $scope.pending_change = function() {
192         return pending_payment_info().change;
193     }
194     $scope.owed_selected = function() {
195         return selected_payment_info().owed; 
196     }
197     $scope.billed_selected = function() {
198         return selected_payment_info().billed;
199     }
200     $scope.paid_selected = function() {
201         return selected_payment_info().paid;
202     }
203     $scope.refunds_available = function() {
204         var amount = 0;
205         angular.forEach($scope.gridControls.allItems(), function(item) {
206             if (item['summary.balance_owed'] < 0) 
207                 amount += item['summary.balance_owed'] * 100;
208         });
209         return -(amount / 100);
210     }
211
212     // update the item.payment_pending value each time the user
213     // selects different transactions to pay against.
214     $scope.$watch(
215         function() {return $scope.gridControls.selectedItems()},
216         function() {updatePendingColumn()},
217         true
218     );
219
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);
223
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});
232
233         var payment_amount = $scope.pending_payment();
234
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']);
239
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;
245
246             } else {
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;
251                 break;
252             }
253         }
254     }
255
256     // builds payment arrays ([xact_id, ammount]) for all transactions
257     // which have a pending payment amount.
258     function generatePayments() {
259         var payments = [];
260         angular.forEach($scope.gridControls.selectedItems(), function(item) {
261             if (item.payment_pending == 0) return;
262             payments.push([item.id, item.payment_pending]);
263         });
264         return payments;
265     }
266
267     function refreshDisplay() {
268         patronSvc.fetchUserStats();
269         billSvc.fetchSummary().then(function(s) {$scope.summary = s});
270         $scope.payment_amount = null;
271         $scope.gridControls.refresh();
272     }
273
274     // generates payments, collects user note if needed, and sends payment
275     // to server.
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) {
281
282             if ($scope.receipt_on_pay) {
283                 printReceipt(
284                     $scope.payment_type, payment_ids, make_payments, note);
285             }
286
287             refreshDisplay();
288         })
289     }
290
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];
295
296             // find the original transaction in the grid..
297             var xact = $scope.gridControls.allItems().filter(
298                 function(item) {return item.id == xact_id})[0];
299
300             payment_blobs.push({
301                 xact : egCore.idl.flatToNestedHash(xact),
302                 amount : payment[1]
303             });
304         });
305
306         console.log(js2JSON(payment_blobs[0]));
307
308         // page data not yet refreshed, capture data from current scope
309         var print_data = {
310             payment_note : note,
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()))
319         }
320
321         print_data.new_balance = (
322             print_data.previous_balance * 100 - 
323             print_data.payment_applied * 100) / 100;
324
325         for (var i = 0; i < $scope.receipt_count; i++) {
326             egCore.print.print({
327                 context : 'receipt', 
328                 template : 'bill_payment', 
329                 scope : print_data
330             });
331         }
332     }
333
334     $scope.showHistory = function() {
335         $location.path('/circ/patron/' + 
336             patronSvc.current.id() + '/bill_history/transactions');
337     }
338     
339     // For now, only adds billing to first selected item.
340     // Could do batches later if needed
341     $scope.addBilling = function(all) {
342         if (all[0]) {
343             egBilling.showBillDialog({
344                 xact : egCore.idl.flatToNestedHash(all[0]),
345                 patron : $scope.patron()
346             }).then(refreshDisplay);
347         }
348     }
349
350     $scope.showBillDialog = function($event) {
351         egBilling.showBillDialog({
352             patron : $scope.patron()
353         }).then(refreshDisplay);
354     }
355
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)
363                 ids.push(item.id);
364         });
365         $scope.gridControls.selectItems(ids);
366     }
367
368     // -------------
369     // determine on initial page load when all of the grid rows should
370     // be selected.
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([]);
380         }
381     });
382
383     $scope.gridControls.allItemsRetrieved = function() {
384         if (selectOnLoad) {
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})
391             );
392         }
393     }
394     // -------------
395
396
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 });
404         var xacts = [];
405         egCore.pcrud.search('mbt', 
406             {id : ids},
407             {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
408             {authoritative : true}
409         ).then(
410             function() {
411                 egCore.print.print({
412                     context : 'receipt', 
413                     template : 'bills_current', 
414                     scope : {   
415                         transactions : xacts,
416                         current_location : egCore.idl.toHash(
417                             egCore.org.get(egCore.auth.user().ws_ou()))
418                     }
419                 });
420             }, 
421             null, 
422             function(xact) {
423                 xacts.push(egCore.idl.toHash(xact));
424             }
425         );
426     }
427
428     $scope.applyPayment = function() {
429         if ($scope.annotate_payment) {
430             egPromptDialog.open(
431                 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
432                 {ok : function(value) {sendPayment(value)}}
433             );
434         } else {
435             sendPayment();
436         }
437     }
438
439     $scope.voidAllBillings = function(items) {
440         angular.forEach(items, function(item) {
441
442             billSvc.fetchBills(item.id).then(function(bills) {
443                 var bill_ids = [];
444                 var cents = 0;
445                 angular.forEach(bills, function(b) {
446                     if (b.voided() != 't') {
447                         cents += b.amount() * 100;
448                         bill_ids.push(b.id())
449                     }
450                 });
451
452                 $scope.session_voided = 
453                     ($scope.session_voided * 100 + cents) / 100;
454
455                 if (bill_ids.length == 0) {
456                     // TODO: warn
457                     return;
458                 }
459
460                 // TODO: alert of pending voiding
461
462                 billSvc.voidBills(bill_ids).then(function() {
463                     refreshDisplay();
464                 });
465             });
466         });
467     }
468
469     // note this is functionally equivalent to selecting a neg. transaction
470     // then clicking Apply Payment -- this just adds a speed bump (ditto
471     // the XUL client).
472     $scope.refundXact = function(all) {
473         var items = all.filter(function(item) {
474             return item['summary.balance_owed'] < 0
475         });
476
477         if (items.length == 0) return;
478
479         var ids = items.map(function(item) {return item.id});
480             
481         egConfirmDialog.open(
482             egCore.strings.CONFIRM_REFUND_PAYMENT, '', 
483             {   xactIds : ''+ids,
484                 ok : function() {
485                     // reset the received payment amount.  this ensures
486                     // we're not mingling payments with refunds.
487                     $scope.payment_amount = 0;
488                 }
489             }
490         );
491     }
492
493     // direct the user to the transaction details page
494     $scope.showFullDetails = function(all) {
495         if (all[0]) 
496             $location.path('/circ/patron/' + 
497                 patronSvc.current.id() + '/bill/' + all[0].id);
498     }
499
500     $scope.activateBill = function(xact) {
501         $scope.showFullDetails([xact]);
502     }
503
504 }])
505
506 /**
507  * Displays details of a single transaction
508  */
509 .controller('XactDetailsCtrl',
510        ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
511 function($scope,  $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
512
513     $scope.initTab('bills', $routeParams.id);
514     var xact_id = $routeParams.xact_id;
515
516     var xactGrid = $scope.xactGridControls = {
517         setQuery : function() { return {xact : xact_id} },
518         setSort : function() { return ['billing_ts'] }
519     }
520
521     var paymentGrid = $scope.paymentGridControls = {
522         setQuery : function() { return {xact : xact_id} },
523         setSort : function() { return ['payment_ts'] }
524     }
525
526     // -- actions
527     $scope.voidBillings = function(bill_list) {
528         var bill_ids = [];
529         angular.forEach(bill_list, function(b) {
530             if (b.voided != 't') bill_ids.push(b.id);
531         });
532
533         if (bill_ids.length == 0) {
534             // TODO: warn
535             return;
536         }
537
538         billSvc.voidBills(bill_ids).then(function() {
539
540             // refresh bills and summary data
541             // note: no need to update payments
542             patronSvc.fetchUserStats();
543
544             egBilling.fetchXact(xact_id).then(function(xact) {
545                 $scope.xact = xact
546             });
547
548             xactGrid.refresh();
549         });
550     }
551
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 });
556
557         // show the note edit prompt
558         egPromptDialog.open(
559             egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
560                 ids : ''+ids,
561                 ok : function(value) {
562
563                     var func = 'updateBillNotes';
564                     if (type == 'payment') func = 'updatePaymentNotes';
565
566                     billSvc[func](value, ids).then(function() {
567                         if (type == 'payment') {
568                             paymentGrid.refresh();
569                         } else {
570                             xactGrid.refresh();
571                         }
572                     });
573                 }
574             }
575         );
576     }
577
578     $scope.editBillNotes = function(selected) {
579         editNotes(selected, 'bill');
580     }
581
582     $scope.editPaymentNotes = function(selected) {
583         editNotes(selected, 'payment');
584     }
585
586     // -- retrieve our data
587     $scope.total_circs = 0; // start with 0 instead of undefined
588     egBilling.fetchXact(xact_id).then(function(xact) {
589         $scope.xact = xact;
590
591         var copyId = xact.circulation().target_copy().id();
592         var circ_count = 0;
593         egCore.pcrud.search('circbyyr',
594             {copy : copyId}, null, {atomic : true})
595         .then(function(counts) {
596             angular.forEach(counts, function(count) {
597                 circ_count += Number(count.count());
598             });
599             $scope.total_circs = circ_count;
600         });
601         // set the title.  only needs to be done on initial page load
602         if (xact.circulation()) {
603             if (xact.circulation().target_copy().call_number().id() == -1) {
604                 $scope.title = xact.circulation().target_copy().dummy_title();
605             } else  {
606                 // TODO: shared bib service?
607                 $scope.title = xact.circulation().target_copy()
608                     .call_number().record().simple_record().title();
609                 $scope.title_id = xact.circulation().target_copy()
610                     .call_number().record().id();
611             }
612         }
613     });
614 }])
615
616
617 .controller('BillHistoryCtrl',
618        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
619 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
620
621     $scope.initTab('bills', $routeParams.id);
622     billSvc.userId = $routeParams.id;
623     $scope.bill_tab = $routeParams.history_tab;
624     $scope.totals = {};
625
626     // link page controller actions defined by sub-controllers here
627     $scope.actions = {};
628
629     var start = new Date(); // now - 1 year
630     start.setFullYear(start.getFullYear() - 1),
631     $scope.dates = {
632         xact_start : start,
633         xact_finish : new Date()
634     }
635
636     $scope.date_range = function() {
637         var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
638         var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
639         var today = new Date().toISOString().replace(/T.*/,'');
640         if (end == today) end = 'now';
641         return [start, end];
642     }
643 }])
644
645
646 .controller('BillXactHistoryCtrl',
647        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
648 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
649
650     // generate a grid query with the current date widget values.
651     function current_grid_query() {
652         return {
653             '-or' : [
654                 {'summary.balance_owed' : {'<>' : 0}},
655                 {'summary.last_payment_ts' : {'<>' : null}}
656             ],
657             xact_start : {between : $scope.date_range()},
658             usr : billSvc.userId
659         }
660     }
661
662     $scope.gridControls = {
663         selectedItems : function(){return []},
664         activateItem : function(item) {
665             $scope.showFullDetails([item]);
666         },
667         // this sets the query on page load
668         setQuery : current_grid_query
669     }
670
671     $scope.actions.apply_date_range = function() {
672         // tells the grid to re-draw itself with the new query
673         $scope.gridControls.setQuery(current_grid_query());
674     }
675
676     // TODO; move me to service
677     function selected_payment_info() {
678         var info = {owed : 0, billed : 0, paid : 0};
679         angular.forEach($scope.gridControls.selectedItems(), function(item) {
680             info.owed   += Number(item['summary.balance_owed']) * 100;
681             info.billed += Number(item['summary.total_owed']) * 100;
682             info.paid   += Number(item['summary.total_paid']) * 100;
683         });
684         info.owed /= 100;
685         info.billed /= 100;
686         info.paid /= 100;
687         return info;
688     }
689
690     $scope.totals.selected_billed = function() {
691         return selected_payment_info().billed;
692     }
693     $scope.totals.selected_paid = function() {
694         return selected_payment_info().paid;
695     }
696
697     $scope.showFullDetails = function(all) {
698         if (all[0]) 
699             $location.path('/circ/patron/' + 
700                 patronSvc.current.id() + '/bill/' + all[0].id);
701     }
702
703     // For now, only adds billing to first selected item.
704     // Could do batches later if needed
705     $scope.addBilling = function(all) {
706         if (all[0]) {
707             egBilling.showBillDialog({
708                 xact : egCore.idl.flatToNestedHash(all[0]),
709                 patron : $scope.patron()
710             }).then(function() { 
711                 $scope.gridControls.refresh();
712                 patronSvc.fetchUserStats();
713             })
714         }
715     }
716 }])
717
718 .controller('BillPaymentHistoryCtrl',
719        ['$scope','$q','egCore','patronSvc','billSvc','$location',
720 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
721
722     // generate a grid query with the current date widget values.
723     function current_grid_query() {
724         return {
725             'payment_ts' : {between : $scope.date_range()},
726             'xact.usr' : billSvc.userId
727         }
728     }
729
730     $scope.gridControls = {
731         selectedItems : function(){return []},
732         activateItem : function(item) {
733             $scope.showFullDetails([item]);
734         },
735         setSort : function() {
736             return [{'payment_ts' : 'DESC'}, 'id'];
737         },
738         setQuery : current_grid_query
739     }
740
741     $scope.actions.apply_date_range = function() {
742         // tells the grid to re-draw itself with the new query
743         $scope.gridControls.setQuery(current_grid_query());
744     }
745
746     $scope.showFullDetails = function(all) {
747         if (all[0]) 
748             $location.path('/circ/patron/' + 
749                 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
750     }
751
752     $scope.totals.selected_paid = function() {
753         var paid = 0;
754         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
755             paid += Number(payment.amount) * 100;
756         });
757         return paid / 100;
758     }
759 }])
760
761
762