]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/bills.js
LP#1350042 Browser client templates/scripts (phase 1)
[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) {
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                 payments : payments,
36                 patron_credit : 0
37             },
38             patronSvc.current.last_xact_id()
39         ).then(function(resp) {
40             console.debug('payments: ' + js2JSON(resp));
41             if (evt = egCore.evt.parse(resp)) 
42                 return alert(evt);
43
44             // payment API returns the update xact id so we can track it
45             // for future payments without having to refresh the user.
46             patronSvc.current.last_xact_id(resp.last_xact_id);
47             return resp.payments;
48         });
49     }
50
51     service.fetchBills = function(xact_id) {
52         var bills = [];
53         return egCore.pcrud.search('mb',
54             {xact : xact_id}, null,
55             {authoritative : true}
56         ).then(
57             function() {return bills},
58             null,
59             function(bill) {bills.push(bill); return bill}
60         );
61     }
62
63     // TODO: no longer needed?
64     service.fetchPayments = function(xact_id) {
65         return egCore.net.request(
66             'open-ils.circ',
67             'open-ils.circ.money.payment.retrieve.all.authoritative',
68             egCore.auth.token(), xact_id
69         );
70     }
71
72     service.voidBills = function(bill_ids) {
73         return egCore.net.requestWithParamList(
74             'open-ils.circ',
75             'open-ils.circ.money.billing.void',
76             [egCore.auth.token()].concat(bill_ids)
77         ).then(function(resp) {
78             if (evt = egCore.evt.parse(resp)) return alert(evt);
79             return resp;
80         });
81     }
82
83     service.updateBillNotes = function(note, ids) {
84         return egCore.net.requestWithParamList(
85             'open-ils.circ',
86             'open-ils.circ.money.billing.note.edit',
87             [egCore.auth.token(), note].concat(ids)
88         ).then(function(resp) {
89             if (evt = egCore.evt.parse(resp)) return alert(evt);
90             return resp;
91         });
92     }
93
94     service.updatePaymentNotes = function(note, ids) {
95         return egCore.net.requestWithParamList(
96             'open-ils.circ',
97             'open-ils.circ.money.payment.note.edit',
98             [egCore.auth.token(), note].concat(ids)
99         ).then(function(resp) {
100             if (evt = egCore.evt.parse(resp)) return alert(evt);
101             return resp;
102         });
103     }
104
105     return service;
106 }])
107
108
109 /**
110  * Manages Bills
111  */
112 .controller('PatronBillsCtrl',
113        ['$scope','$q','$routeParams','egCore','egConfirmDialog','$location',
114         'egGridDataProvider','billSvc','patronSvc','egPromptDialog','$modal',
115         'egBilling',
116 function($scope , $q , $routeParams , egCore , egConfirmDialog , $location,
117          egGridDataProvider , billSvc , patronSvc , egPromptDialog , $modal,
118          egBilling) {
119
120     $scope.initTab('bills', $routeParams.id);
121     billSvc.userId = $routeParams.id;
122
123     // set up some defaults
124     $scope.payment_amount = 0;
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 = 0;
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)
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     egBilling.fetchXact(xact_id).then(function(xact) {
586         $scope.xact = xact;
587
588         // set the title.  only needs to be done on initial page load
589         if (xact.circulation()) {
590             if (xact.circulation().target_copy().call_number().id() == -1) {
591                 $scope.title = xact.circulation().target_copy().dummy_title();
592             } else  {
593                 // TODO: shared bib service?
594                 $scope.title = xact.circulation().target_copy()
595                     .call_number().record().simple_record().title();
596                 $scope.title_id = xact.circulation().target_copy()
597                     .call_number().record().id();
598             }
599         }
600     });
601 }])
602
603
604 .controller('BillHistoryCtrl',
605        ['$scope','$q','$routeParams','egCore','patronSvc','billSvc','egPromptDialog','$location',
606 function($scope,  $q , $routeParams , egCore , patronSvc , billSvc , egPromptDialog , $location) {
607
608     $scope.initTab('bills', $routeParams.id);
609     billSvc.userId = $routeParams.id;
610     $scope.bill_tab = $routeParams.history_tab;
611     $scope.totals = {};
612
613     var start = new Date(); // now - 1 year
614     start.setFullYear(start.getFullYear() - 1),
615     $scope.dates = {
616         xact_start : start,
617         xact_finish : new Date()
618     }
619
620     $scope.date_range = function() {
621         var start = $scope.dates.xact_start.toISOString().replace(/T.*/,'');
622         var end = $scope.dates.xact_finish.toISOString().replace(/T.*/,'');
623         var today = new Date().toISOString().replace(/T.*/,'');
624         if (end == today) end = 'now';
625         return [start, end];
626     }
627 }])
628
629
630 .controller('BillXactHistoryCtrl',
631        ['$scope','$q','egCore','patronSvc','billSvc','egPromptDialog','$location','egBilling',
632 function($scope,  $q , egCore , patronSvc , billSvc , egPromptDialog , $location , egBilling) {
633
634     $scope.gridControls = {
635         selectedItems : function(){return []},
636         activateItem : function(item) {
637             $scope.showFullDetails([item]);
638         },
639         setQuery : function() {
640             // open-ils.actor.user.transactions.history.have_bill_or_payment
641             return {
642                 '-or' : [
643                     {'summary.balance_owed' : {'<>' : 0}},
644                     {'summary.last_payment_ts' : {'<>' : null}}
645                 ],
646                 xact_start : {between : $scope.date_range()},
647                 usr : billSvc.userId
648             }
649         }
650     }
651
652
653     // TODO; move me to service
654     function selected_payment_info() {
655         var info = {owed : 0, billed : 0, paid : 0};
656         angular.forEach($scope.gridControls.selectedItems(), function(item) {
657             info.owed   += Number(item['summary.balance_owed']) * 100;
658             info.billed += Number(item['summary.total_owed']) * 100;
659             info.paid   += Number(item['summary.total_paid']) * 100;
660         });
661         info.owed /= 100;
662         info.billed /= 100;
663         info.paid /= 100;
664         return info;
665     }
666
667     $scope.totals.selected_billed = function() {
668         return selected_payment_info().billed;
669     }
670     $scope.totals.selected_paid = function() {
671         return selected_payment_info().paid;
672     }
673
674     $scope.showFullDetails = function(all) {
675         if (all[0]) 
676             $location.path('/circ/patron/' + 
677                 patronSvc.current.id() + '/bill/' + all[0].id);
678     }
679
680     // For now, only adds billing to first selected item.
681     // Could do batches later if needed
682     $scope.addBilling = function(all) {
683         if (all[0]) {
684             egBilling.showBillDialog({
685                 xact : egCore.idl.flatToNestedHash(all[0]),
686                 patron : $scope.patron()
687             }).then(function() { 
688                 $scope.gridControls.refresh();
689                 patronSvc.fetchUserStats();
690             })
691         }
692     }
693 }])
694
695 .controller('BillPaymentHistoryCtrl',
696        ['$scope','$q','egCore','patronSvc','billSvc','$location',
697 function($scope,  $q , egCore , patronSvc , billSvc , $location) {
698
699     $scope.gridControls = {
700         selectedItems : function(){return []},
701         activateItem : function(item) {
702             $scope.showFullDetails([item]);
703         },
704         setSort : function() {
705             return [{'payment_ts' : 'DESC'}, 'id'];
706         },
707         setQuery : function() {
708             return {
709                 'payment_ts' : {between : $scope.date_range()},
710                 'xact.usr' : billSvc.userId
711             }
712         }
713     }
714
715     $scope.showFullDetails = function(all) {
716         if (all[0]) 
717             $location.path('/circ/patron/' + 
718                 patronSvc.current.id() + '/bill/' + all[0]['xact.id']);
719     }
720
721     $scope.totals.selected_paid = function() {
722         var paid = 0;
723         angular.forEach($scope.gridControls.selectedItems(), function(payment) {
724             paid += Number(payment.amount) * 100;
725         });
726         return paid / 100;
727     }
728 }])
729
730
731