LP#1586567 Always return Fund Years sorted descending
[working/Evergreen.git] / Open-ILS / web / js / ui / default / acq / financial / list_funds.js
1 dojo.require("dijit.Dialog");
2 dojo.require("dijit.form.FilteringSelect");
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.TooltipDialog');
5 dojo.require('dijit.form.DropDownButton');
6 dojo.require('dijit.form.CheckBox');
7 dojo.require('dojox.grid.DataGrid');
8 dojo.require('dojo.data.ItemFileWriteStore');
9 dojo.require('openils.widget.OrgUnitFilteringSelect');
10 dojo.require('openils.acq.CurrencyType');
11 dojo.require('openils.Event');
12 dojo.require('openils.Util');
13 dojo.require('openils.User');
14 dojo.require('openils.CGI');
15 dojo.require('openils.PermaCrud');
16 dojo.require('openils.widget.AutoGrid');
17 dojo.require('openils.widget.ProgressDialog');
18 dojo.require('fieldmapper.OrgUtils');
19 dojo.requireLocalization('openils.acq', 'acq');
20 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
21
22 dojo.require('openils.XUL');
23 var xulStorage = openils.XUL.localStorage();
24 var storekey = 'eg.acq.fund.list.context_ou_selector';
25
26 var contextOrg;
27 var rolloverResponses;
28 var rolloverMode = false;
29 var fundFleshFields = [
30     'spent_balance', 
31     'combined_balance', 
32     'spent_total', 
33     'encumbrance_total', 
34     'debit_total', 
35     'allocation_total'
36 ];
37
38 var adminPermOrgs = [];
39 var cachedFunds = [];
40
41 function initPage() {
42     contextOrg = xulStorage.getItem(storekey) || openils.User.user.ws_ou();
43
44     // Propagate the context org from the URL data into our org selector.
45     if (lfGrid.urlUserData && lfGrid.urlUserData.contextOrg)
46         contextOrg = lfGrid.urlUserData.contextOrg;
47
48     /* Reveal controls for rollover without money if org units say ok.
49      * Actual ability to do the operation is controlled in the database, of
50      * course. */
51     var ouSettings = fieldmapper.aou.fetchOrgSettingBatch(
52         openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"]
53     );
54     if (
55         ouSettings["acq.fund.allow_rollover_without_money"] &&
56         ouSettings["acq.fund.allow_rollover_without_money"].value
57     ) {
58         dojo.query(".encumb_only").forEach(
59             function(o) { openils.Util.show(o, "table-row"); }
60         );
61     }
62
63     var connect = function() {
64         dojo.connect(contextOrgSelector, 'onChange',
65             function() {
66                 contextOrg = this.attr('value');
67                 xulStorage.setItem(storekey, contextOrg);
68                 dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = 
69                     fieldmapper.aou.findOrgUnit(contextOrg).shortname();
70                 rolloverMode = false;
71                 // tell the grid to pass the context org info along
72                 // with the encoded URL data so we can re-propagate
73                 lfGrid.displayOffset = 0; // new org means a new search
74                 gridDataLoader();
75             }
76         );
77     };
78
79     dojo.connect(refreshButton, 'onClick', 
80         function() { rolloverMode = false; gridDataLoader(); });
81
82     new openils.User().buildPermOrgSelector(
83         ['ADMIN_ACQ_FUND', 'VIEW_FUND'], 
84         contextOrgSelector, contextOrg, connect);
85
86     dojo.byId('oils-acq-rollover-ctxt-org').innerHTML = 
87         fieldmapper.aou.findOrgUnit(contextOrg).shortname();
88
89     loadYearSelector();
90     lfGrid.onItemReceived = function(item) {cachedFunds.push(item)};
91
92     new openils.User().getPermOrgList(
93         'ADMIN_ACQ_FUND',
94         function(list) {
95             adminPermOrgs = list;
96             loadFundGrid(
97                 lfGrid.urlUserData.year
98                     || new openils.CGI().param('year')
99                     || new Date().getFullYear().toString());
100         },
101         true, true
102     );
103 }
104
105 function gridDataLoader() {
106     lfGrid.resetStore();
107     if(rolloverMode) {
108         var offset = lfGrid.displayOffset;
109         for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) {
110             var fund = rolloverResponses[i];
111             if(!fund) break;
112             lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund));
113         }
114     } else {
115         loadFundGrid();
116     }
117 }
118
119 function getBalanceInfo(rowIdx, item) {
120     if (!item) return '';
121     var fundId = this.grid.store.getValue(item, 'id');
122     var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0];
123     var cb = fund.combined_balance();
124     return cb ? cb.amount() : '0';
125 }
126
127 function loadFundGrid(year) {
128     openils.Util.hide('acq-fund-list-rollover-summary');
129     year = year || fundFilterYearSelect.attr('value');
130     cachedFunds = [];
131
132     var order_by = [{'class' : 'acqf', field : 'name'}];
133
134     if (adminPermOrgs.length) {
135         // sort funds I can edit to the front
136         order_by.unshift({   
137             'class' : 'acqf',
138             field : 'org',
139             compare : {'in' : adminPermOrgs},
140             direction : 'desc'
141         });
142     }
143
144     lfGrid.urlUserData.year = year;
145     lfGrid.urlUserData.contextOrg = contextOrg;
146
147     lfGrid.loadAll(
148         {   
149             flesh : 1,  
150             flesh_fields : {acqf : fundFleshFields},
151             order_by : order_by,
152         }, {   
153             year : year, 
154             org : fieldmapper.aou.descendantNodeList(contextOrg, true) 
155         } 
156     );
157 }
158
159 function loadYearSelector() {
160
161     fieldmapper.standardRequest(
162         ['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'],
163         {   async : true,
164             params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}],
165             oncomplete : function(r) {
166
167                 var yearList = openils.Util.readResponse(r);
168                 if(!yearList) return;
169                 yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings
170
171                 var yearStore = {identifier:'year', name:'year', items:yearList};
172                 fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore});
173
174                 // default to this year
175                 fundFilterYearSelect.setValue(
176                     // propagate year from URL if available
177                     lfGrid.urlUserData.year ||
178                         new Date().getFullYear().toString()
179                 );
180
181                 dojo.connect(
182                     fundFilterYearSelect, 
183                     'onChange', 
184                     function() { 
185                         rolloverMode = false;
186                         lfGrid.displayOffset = 0;
187                         gridDataLoader();
188                     }
189                 );
190             }
191         }
192     );
193 }
194
195 function performRollover(args) {
196
197     rolloverMode = true;
198     progressDialog.show(true, "Processing...");
199     rolloverResponses = [];
200
201     var method = 'open-ils.acq.fiscal_rollover';
202
203     if(args.rollover[0] == 'on') {
204         method += '.combined';
205     } else {
206         method += '.propagate';
207     }
208         
209     var dryRun = args.dry_run[0] == 'on';
210     if(dryRun) method += '.dry_run';
211
212     var encumbOnly = args.encumb_only[0] == 'on';
213
214     var count = 0;
215     var amount_rolled = 0;
216     var year = fundFilterYearSelect.attr('value'); // TODO alternate selector?
217     
218     fieldmapper.standardRequest(
219         ['open-ils.acq', method],
220         {
221             async : true,
222
223             params : [
224                 openils.User.authtoken, 
225                 year,
226                 contextOrg,
227                 (args.child_orgs[0] == 'on'),
228                 { encumb_only : encumbOnly }
229             ],
230
231             onresponse : function(r) {
232                 var resp = openils.Util.readResponse(r);
233                 rolloverResponses.push(resp.fund);
234                 count += 1;
235                 amount_rolled += Number(resp.rollover_amount);
236             }, 
237
238             oncomplete : function() {
239                 
240                 var nextYear = Number(year) + 1;
241                 rolloverResponses = rolloverResponses.sort(
242                     function(a, b) {
243                         if(a.code() > b.code())
244                             return 1;
245                         return -1;
246                     }
247                 )
248
249                 // add the new, rolled funds to the cache.  Note that in dry-run 
250                 // mode, these are ephemeral and no longer exist on the server.
251                 cachedFunds = cachedFunds.concat(rolloverResponses);
252
253                 dojo.byId('acq-fund-list-rollover-summary-header').innerHTML = 
254                     dojo.string.substitute(
255                         localeStrings.FUND_LIST_ROLLOVER_SUMMARY,
256                         [nextYear]
257                     );
258
259                 dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML = 
260                     dojo.string.substitute(
261                         localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS,
262                         [nextYear, '<b>' + count + '</b>']
263                     );
264
265                 dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML = 
266                     dojo.string.substitute(
267                         localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT,
268                         [nextYear, '<b>' + amount_rolled + '</b>']
269                     );
270
271                 if(!dryRun) {
272                     openils.Util.hide('acq-fund-list-rollover-summary-dry-run');
273                     
274                     // add the new year to the year selector if it's not already there
275                     fundFilterYearSelect.store.fetch({
276                         query : {year : ''+nextYear}, 
277                         onComplete:
278                             function(list) {
279                                 if(list && list.length > 0) return;
280                                 fundFilterYearSelect.store.newItem({year : nextYear});
281                             }
282                     });
283                 }
284
285                 openils.Util.show('acq-fund-list-rollover-summary');
286                 progressDialog.hide();
287                 gridDataLoader();
288             }
289         }
290     );
291 }
292
293 openils.Util.addOnLoad(initPage);