]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/bills.js
LP#1554714 angular-bootstrap 1.4 uibModal migration
[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', 'egBilling',
116 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
117          egGridDataProvider , billSvc , patronSvc , egPromptDialog, egBilling) {
118
119     $scope.initTab('bills', $routeParams.id);
120     billSvc.userId = $routeParams.id;
121
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;
131
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;
140         },
141         activateItem : function(item) {
142             $scope.showFullDetails([item]);
143         },
144         setQuery : function() {    
145             return {
146                 usr : billSvc.userId, 
147                 xact_finish : null,
148                 'summary.balance_owed' : {'<>' : 0}
149             }
150         }, 
151         setSort : function() {
152             return ['xact_start']; 
153         }
154     }
155
156     billSvc.fetchSummary().then(function(s) {$scope.summary = s});
157
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()) {
163             return {
164                 payment : $scope.owed_selected(),
165                 change : amt - $scope.owed_selected()
166             }
167         } 
168         return {payment : amt, change : 0};
169     }
170
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;
179         });
180         info.owed /= 100;
181         info.billed /= 100;
182         info.paid /= 100;
183         return info;
184     }
185
186     $scope.pending_payment = function() {
187         return pending_payment_info().payment;
188     }
189     $scope.pending_change = function() {
190         return pending_payment_info().change;
191     }
192     $scope.owed_selected = function() {
193         return selected_payment_info().owed; 
194     }
195     $scope.billed_selected = function() {
196         return selected_payment_info().billed;
197     }
198     $scope.paid_selected = function() {
199         return selected_payment_info().paid;
200     }
201     $scope.refunds_available = function() {
202         var amount = 0;
203         angular.forEach($scope.gridControls.allItems(), function(item) {
204             if (item['summary.balance_owed'] < 0) 
205                 amount += item['summary.balance_owed'] * 100;
206         });
207         return -(amount / 100);
208     }
209
210     // update the item.payment_pending value each time the user
211     // selects different transactions to pay against.
212     $scope.$watch(
213         function() {return $scope.gridControls.selectedItems()},
214         function() {updatePendingColumn()},
215         true
216     );
217
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);
221
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});
230
231         var payment_amount = $scope.pending_payment();
232
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']);
237
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;
243
244             } else {
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;
249                 break;
250             }
251         }
252     }
253
254     // builds payment arrays ([xact_id, ammount]) for all transactions
255     // which have a pending payment amount.
256     function generatePayments() {
257         var payments = [];
258         angular.forEach($scope.gridControls.selectedItems(), function(item) {
259             if (item.payment_pending == 0) return;
260             payments.push([item.id, item.payment_pending]);
261         });
262         return payments;
263     }
264
265     function refreshDisplay() {
266         patronSvc.fetchUserStats();
267         billSvc.fetchSummary().then(function(s) {$scope.summary = s});
268         $scope.payment_amount = null;
269         $scope.gridControls.refresh();
270     }
271
272     // generates payments, collects user note if needed, and sends payment
273     // to server.
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) {
279
280             if ($scope.receipt_on_pay) {
281                 printReceipt(
282                     $scope.payment_type, payment_ids, make_payments, note);
283             }
284
285             refreshDisplay();
286         })
287     }
288
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];
293
294             // find the original transaction in the grid..
295             var xact = $scope.gridControls.allItems().filter(
296                 function(item) {return item.id == xact_id})[0];
297
298             payment_blobs.push({
299                 xact : egCore.idl.flatToNestedHash(xact),
300                 amount : payment[1]
301             });
302         });
303
304         console.log(js2JSON(payment_blobs[0]));
305
306         // page data not yet refreshed, capture data from current scope
307         var print_data = {
308             payment_note : note,
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()))
317         }
318
319         print_data.new_balance = (
320             print_data.previous_balance * 100 - 
321             print_data.payment_applied * 100) / 100;
322
323         for (var i = 0; i < $scope.receipt_count; i++) {
324             egCore.print.print({
325                 context : 'receipt', 
326                 template : 'bill_payment', 
327                 scope : print_data
328             });
329         }
330     }
331
332     $scope.showHistory = function() {
333         $location.path('/circ/patron/' + 
334             patronSvc.current.id() + '/bill_history/transactions');
335     }
336     
337     // For now, only adds billing to first selected item.
338     // Could do batches later if needed
339     $scope.addBilling = function(all) {
340         if (all[0]) {
341             egBilling.showBillDialog({
342                 xact : egCore.idl.flatToNestedHash(all[0]),
343                 patron : $scope.patron()
344             }).then(refreshDisplay);
345         }
346     }
347
348     $scope.showBillDialog = function($event) {
349         egBilling.showBillDialog({
350             patron : $scope.patron()
351         }).then(refreshDisplay);
352     }
353
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)
361                 ids.push(item.id);
362         });
363         $scope.gridControls.selectItems(ids);
364     }
365
366     // -------------
367     // determine on initial page load when all of the grid rows should
368     // be selected.
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([]);
378         }
379     });
380
381     $scope.gridControls.allItemsRetrieved = function() {
382         if (selectOnLoad) {
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})
389             );
390         }
391     }
392     // -------------
393
394
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 });
402         var xacts = [];
403         egCore.pcrud.search('mbt', 
404             {id : ids},
405             {flesh : 1, flesh_fields : {'mbt' : ['summary']}},
406             {authoritative : true}
407         ).then(
408             function() {
409                 egCore.print.print({
410                     context : 'receipt', 
411                     template : 'bills_current', 
412                     scope : {   
413                         transactions : xacts,
414                         current_location : egCore.idl.toHash(
415                             egCore.org.get(egCore.auth.user().ws_ou()))
416                     }
417                 });
418             }, 
419             null, 
420             function(xact) {
421                 xacts.push(egCore.idl.toHash(xact));
422             }
423         );
424     }
425
426     $scope.applyPayment = function() {
427         if ($scope.annotate_payment) {
428             egPromptDialog.open(
429                 egCore.strings.ANNOTATE_PAYMENT_MSG, '',
430                 {ok : function(value) {sendPayment(value)}}
431             );
432         } else {
433             sendPayment();
434         }
435     }
436
437     $scope.voidAllBillings = function(items) {
438         angular.forEach(items, function(item) {
439
440             billSvc.fetchBills(item.id).then(function(bills) {
441                 var bill_ids = [];
442                 var cents = 0;
443                 angular.forEach(bills, function(b) {
444                     if (b.voided() != 't') {
445                         cents += b.amount() * 100;
446                         bill_ids.push(b.id())
447                     }
448                 });
449
450                 $scope.session_voided = 
451                     ($scope.session_voided * 100 + cents) / 100;
452
453                 if (bill_ids.length == 0) {
454                     // TODO: warn
455                     return;
456                 }
457
458                 // TODO: alert of pending voiding
459
460                 billSvc.voidBills(bill_ids).then(function() {
461                     refreshDisplay();
462                 });
463             });
464         });
465     }
466
467     // note this is functionally equivalent to selecting a neg. transaction
468     // then clicking Apply Payment -- this just adds a speed bump (ditto
469     // the XUL client).
470     $scope.refundXact = function(all) {
471         var items = all.filter(function(item) {
472             return item['summary.balance_owed'] < 0
473         });
474
475         if (items.length == 0) return;
476
477         var ids = items.map(function(item) {return item.id});
478             
479         egConfirmDialog.open(
480             egCore.strings.CONFIRM_REFUND_PAYMENT, '', 
481             {   xactIds : ''+ids,
482                 ok : function() {
483                     // reset the received payment amount.  this ensures
484                     // we're not mingling payments with refunds.
485                     $scope.payment_amount = 0;
486                 }
487             }
488         );
489     }
490
491     // direct the user to the transaction details page
492     $scope.showFullDetails = function(all) {
493         if (all[0]) 
494             $location.path('/circ/patron/' + 
495                 patronSvc.current.id() + '/bill/' + all[0].id);
496     }
497
498     $scope.activateBill = function(xact) {
499         $scope.showFullDetails([xact]);
500     }
501
502 }])
503
504 /**
505  * Displays details of a single transaction
506  */
507 .controller('XactDetailsCtrl',
508        ['$scope','$q','$routeParams','egCore','egGridDataProvider','patronSvc','billSvc','egPromptDialog','egBilling',
509 function($scope,  $q , $routeParams , egCore , egGridDataProvider , patronSvc , billSvc , egPromptDialog , egBilling) {
510
511     $scope.initTab('bills', $routeParams.id);
512     var xact_id = $routeParams.xact_id;
513
514     var xactGrid = $scope.xactGridControls = {
515         setQuery : function() { return {xact : xact_id} },
516         setSort : function() { return ['billing_ts'] }
517     }
518
519     var paymentGrid = $scope.paymentGridControls = {
520         setQuery : function() { return {xact : xact_id} },
521         setSort : function() { return ['payment_ts'] }
522     }
523
524     // -- actions
525     $scope.voidBillings = function(bill_list) {
526         var bill_ids = [];
527         angular.forEach(bill_list, function(b) {
528             if (b.voided != 't') bill_ids.push(b.id);
529         });
530
531         if (bill_ids.length == 0) {
532             // TODO: warn
533             return;
534         }
535
536         billSvc.voidBills(bill_ids).then(function() {
537
538             // refresh bills and summary data
539             // note: no need to update payments
540             patronSvc.fetchUserStats();
541
542             egBilling.fetchXact(xact_id).then(function(xact) {
543                 $scope.xact = xact
544             });
545
546             xactGrid.refresh();
547         });
548     }
549
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 });
554
555         // show the note edit prompt
556         egPromptDialog.open(
557             egCore.strings.EDIT_BILL_PAY_NOTE, notes, {
558                 ids : ''+ids,
559                 ok : function(value) {
560
561                     var func = 'updateBillNotes';
562                     if (type == 'payment') func = 'updatePaymentNotes';
563
564                     billSvc[func](value, ids).then(function() {
565                         if (type == 'payment') {
566                             paymentGrid.refresh();
567                         } else {
568                             xactGrid.refresh();
569                         }
570                     });
571                 }
572             }
573         );
574     }
575
576     $scope.editBillNotes = function(selected) {
577         editNotes(selected, 'bill');
578     }
579
580     $scope.editPaymentNotes = function(selected) {
581         editNotes(selected, 'payment');
582     }
583
584     // -- retrieve our data
585     $scope.total_circs = 0; // start with 0 instead of undefined
586     egBilling.fetchXact(xact_id).then(function(xact) {
587         $scope.xact = xact;
588
589         var copyId = xact.circulation().target_copy().id();
590         var circ_count = 0;
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());
596             });
597             $scope.total_circs = circ_count;
598         });
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();
603             } else  {
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();
609             }
610         }
611     });
612 }])
613
614
615 .controller('BillHistoryCtrl',
616        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
617 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
618
619     $scope.initTab('bills', $routeParams.id);
620     billSvc.userId = $routeParams.id;
621     $scope.bill_tab = $routeParams.history_tab;
622     $scope.totals = {};
623
624     // link page controller actions defined by sub-controllers here
625     $scope.actions = {};
626
627     var start = new Date(); // now - 1 year
628     start.setFullYear(start.getFullYear() - 1),
629     $scope.dates = {
630         xact_start : start,
631         xact_finish : new Date()
632     }
633
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';
639         return [start, end];
640     }
641 }])
642
643
644 .controller('BillXactHistoryCtrl',
645        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
646 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
647
648     // generate a grid query with the current date widget values.
649     function current_grid_query() {
650         return {
651             '-or' : [
652                 {'summary.balance_owed' : {'<>' : 0}},
653                 {'summary.last_payment_ts' : {'<>' : null}}
654             ],
655             xact_start : {between : $scope.date_range()},
656             usr : billSvc.userId
657         }
658     }
659
660     $scope.gridControls = {
661         selectedItems : function(){return []},
662         activateItem : function(item) {
663             $scope.showFullDetails([item]);
664         },
665         // this sets the query on page load
666         setQuery : current_grid_query
667     }
668
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());
672     }
673
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;
681         });
682         info.owed /= 100;
683         info.billed /= 100;
684         info.paid /= 100;
685         return info;
686     }
687
688     $scope.totals.selected_billed = function() {
689         return selected_payment_info().billed;
690     }
691     $scope.totals.selected_paid = function() {
692         return selected_payment_info().paid;
693     }
694
695     $scope.showFullDetails = function(all) {
696         if (all[0]) 
697             $location.path('/circ/patron/' + 
698                 patronSvc.current.id() + '/bill/' + all[0].id);
699     }
700
701     // For now, only adds billing to first selected item.
702     // Could do batches later if needed
703     $scope.addBilling = function(all) {
704         if (all[0]) {
705             egBilling.showBillDialog({
706                 xact : egCore.idl.flatToNestedHash(all[0]),
707                 patron : $scope.patron()
708             }).then(function() { 
709                 $scope.gridControls.refresh();
710                 patronSvc.fetchUserStats();
711             })
712         }
713     }
714 }])
715
716 .controller('BillPaymentHistoryCtrl',
717        ['$scope','$q','egCore','patronSvc','billSvc','$location',
718 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
719
720     // generate a grid query with the current date widget values.
721     function current_grid_query() {
722         return {
723             'payment_ts' : {between : $scope.date_range()},
724             'xact.usr' : billSvc.userId
725         }
726     }
727
728     $scope.gridControls = {
729         selectedItems : function(){return []},
730         activateItem : function(item) {
731             $scope.showFullDetails([item]);
732         },
733         setSort : function() {
734             return [{'payment_ts' : 'DESC'}, 'id'];
735         },
736         setQuery : current_grid_query
737     }
738
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());
742     }
743
744     $scope.showFullDetails = function(all) {
745         if (all[0]) 
746             $location.path('/circ/patron/' + 
747                 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
748     }
749
750     $scope.totals.selected_paid = function() {
751         var paid = 0;
752         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
753             paid += Number(payment.amount) * 100;
754         });
755         return paid / 100;
756     }
757 }])
758
759
760