LP#1329920 Add fund year to distribution formula fund dropdown menu
[working/Evergreen.git] / Open-ILS / web / js / ui / default / conify / global / acq / distribution_formula.js
1 dojo.require("dojo.dnd.Container");
2 dojo.require("dojo.dnd.Source");
3 dojo.require('openils.widget.AutoGrid');
4 dojo.require('dijit.form.FilteringSelect');
5 dojo.require('openils.PermaCrud');
6 dojo.require('openils.widget.AutoFieldWidget');
7 dojo.requireLocalization('openils.conify', 'conify');
8 var localeStrings = dojo.i18n.getLocalization('openils.conify', 'conify');
9
10
11 var formCache = {};
12 var formula, entryTbody, entryTemplate, dndSource;
13 var virtualId = -1;
14 var pcrud;
15 var _collection_code_textboxes = [];
16 var _collection_code_kludge_active = false;
17 var fundSearchFilter = {active : 't'};
18 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
19
20
21 function gridDataLoader() {
22     fListGrid.resetStore();
23     fListGrid.showLoadProgressIndicator();
24     fieldmapper.standardRequest(
25         ["open-ils.acq", "open-ils.acq.distribution_formula.ranged.retrieve"], {
26             "async": true,
27             "params": [
28                 openils.User.authtoken,
29                 fListGrid.displayOffset,
30                 fListGrid.displayLimit
31             ],
32             "onresponse": function(r) {
33                 var form = openils.Util.readResponse(r);
34                 formCache[form.id()] = form;
35                 fListGrid.store.newItem(form.toStoreItem());
36             },
37             "oncomplete": function() {
38                 fListGrid.hideLoadProgressIndicator();
39             }
40         }
41     );
42 }
43
44 function setFundSearchFilter(callback) {
45     new openils.User().getPermOrgList(
46         ['ADMIN_ACQ_DISTRIB_FORMULA'],
47         function(orgs) { 
48             fundSearchFilter.org = orgs;
49             if (callback) callback();
50         },
51         true, true // descendants, id_list
52     );
53 }
54
55 function draw() {
56
57     pcrud = new openils.PermaCrud();
58
59     if(formulaId) {
60         openils.Util.hide('formula-list-div');
61         setFundSearchFilter(drawFormulaSummary);
62     } else {
63
64         openils.Util.hide('formula-entry-div');
65         fListGrid.onPostCreate = function(fmObject) {
66             location.href = location.href + '/' + fmObject.id();
67         }
68
69         fListGrid.dataLoader = gridDataLoader;
70         gridDataLoader();
71     }
72 }
73
74 function cloneSelectedFormula() {
75     var item = fListGrid.getSelectedItems()[0];
76     if(!item) return;
77     var formula = new fieldmapper.acqf().fromStoreItem(item);
78     fieldmapper.standardRequest(
79         ['open-ils.acq', 'open-ils.acq.distribution_formula.clone'],
80         {
81             asnyc : true,
82             params : [
83                 openils.User.authtoken, 
84                 formula.id(), 
85                 dojo.string.substitute(localeStrings.ACQ_DISTRIB_FORMULA_NAME_CLONE, [formula.name()])
86             ],
87             oncomplete : function(r) {
88                 if(r = openils.Util.readResponse(r)) {
89                     location.href = oilsBasePath + '/conify/global/acq/distribution_formula/' + r;
90                 }
91             }
92         }
93     );
94 }
95
96 openils.Util.addOnLoad(draw);
97
98 function getItemCount(rowIndex, item) {
99     if(!item) return '';
100     var form = formCache[this.grid.store.getValue(item, "id")];
101     if(!form) return 0;
102     var count = 0;
103     dojo.forEach(form.entries(), function(e) { count = count + e.item_count(); });
104     return count;
105 }
106
107 function byName(node, name) {
108     return dojo.query('[name='+name+']', node)[0];
109 }
110
111 function drawFormulaSummary() {
112     openils.Util.show('formula-entry-div');
113
114     var entries = pcrud.search('acqdfe', {formula: formulaId}, {order_by:{acqdfe : 'position'}});
115     formula = pcrud.retrieve('acqdf', formulaId);
116     formula.entries(entries);
117
118     dojo.byId('formula_head').innerHTML = formula.name();
119     dojo.byId('formula_head').onclick = function() {
120         var name = prompt(localeStrings.ACQ_DISTRIB_FORMULA_NAME_PROMPT, formula.name());
121         if(name && name != formula.name()) {
122             formula.name(name);
123             pcrud = new openils.PermaCrud();
124             pcrud.update(formula);
125             dojo.byId('formula_head').innerHTML = name;
126         }
127     }
128
129     dojo.forEach(entries, function(entry) { addEntry(entry); } );
130 }
131
132 function addEntry(entry) {
133
134     if(!entryTbody) {
135         entryTbody = dojo.byId('formula-entry-tbody');
136         entryTemplate = entryTbody.removeChild(dojo.byId('formula-entry-tempate'));
137         dndSource = new dojo.dnd.Source(entryTbody);
138         dndSource.selectAll(); 
139         dndSource.deleteSelectedNodes();
140         dndSource.clearItems();
141     }
142
143     if(!entry) {
144         entry = new fieldmapper.acqdfe();
145         entry.formula(formulaId);
146         entry.item_count(1);
147         entry.owning_lib(openils.User.user.ws_ou());
148         entry.id(virtualId--);
149         entry.isnew(true);
150         formula.entries().push(entry);
151     }
152
153     var row = entryTbody.appendChild(entryTemplate.cloneNode(true));
154     row.setAttribute('entry', entry.id());
155     dndSource.insertNodes(false, [row]);
156     byName(row, 'delete').onclick = function() {
157         entry.isdeleted(true);
158         entryTbody.removeChild(row);
159         dndSource.sync();
160     };
161
162     dojo.forEach(
163         ['owning_lib', 'location', 'fund', 'circ_modifier', 'collection_code', 'item_count'],
164         function(field) {
165             new openils.widget.AutoFieldWidget({
166                 forceSync : true,
167                 fmField : field, 
168                 fmObject : entry,
169                 fmClass : 'acqdfe',
170                 labelFormat: (field == 'fund') ? fundLabelFormat : null,
171                 searchFilter : (field == 'fund') ? fundSearchFilter : null,
172                 parentNode : byName(row, field),
173                 orgDefaultsToWs : true,
174                 orgLimitPerms : ['ADMIN_ACQ_DISTRIB_FORMULA'],
175                 widgetClass : (field == 'item_count') ? 'dijit.form.NumberSpinner' : null,
176                 dijitArgs : (field == 'item_count') ? {min:1, places:0} : null
177             }).build(
178                 function(w, ww) {
179                     if (field == "collection_code") {
180                         /* kludge for glitchy textbox */
181                         _collection_code_textboxes.push(w);
182                     }
183                     dojo.connect(w, 'onChange', 
184                         function(newVal) {
185                             entry[field]( newVal );
186                             entry.ischanged(true);
187                         }
188                     )
189                 }
190             );
191         }
192     );
193
194     /* For some reason (bug) the dndSource intercepts onMouseDown events
195      * that should hit dijit textboxes in our table thingy. Other dijits
196      * (buttons, filteringselects, etc) seem not to be affected.  This
197      * workaround deals with the only textboxes we have for now: the ones
198      * for the collection_code field. */
199     if (!_collection_code_kludge_active) {
200         _collection_code_kludge_active = true;
201         var original = dojo.hitch(dndSource, dndSource.onMouseDown);
202         dndSource.onMouseDown = function(e) {
203             var hits = _collection_code_textboxes.filter(
204                 function(w) {
205                     var c = dojo.coords(w.domNode);
206                     if (e.clientX >= c.x && e.clientX < c.x + c.w) {
207                         if (e.clientY >= c.y && e.clientY < c.y + c.h) {
208                             return true;
209                         }
210                     }
211                     return false;
212                 }
213             );
214
215             if (hits.length) {
216                 hits[0].focus();
217             } else {
218                 original(e);
219             }
220         };
221     }
222 }
223
224 function saveFormula() {
225     var pos = 1;
226     var updatedEntries = [];
227     var deletedEntries = [];
228
229     // remove deleted entries from consideration for collision protection
230     for(var i = 0; i < formula.entries().length; i++) {
231         if(formula.entries()[i].isdeleted())
232             deletedEntries.push(formula.entries().splice(i--, 1)[0])
233     }
234
235     // update entry positions and create temporary collision avoidance entries
236     dojo.forEach(
237         dndSource.getAllNodes(),
238         function(node) {
239
240             var entryId = node.getAttribute('entry');
241             var entry = formula.entries().filter(function(e) {return (e.id() == entryId)})[0];
242
243             if(entry.position() != pos) {
244
245                 // update the position
246                 var changedEntry = entry.clone();
247                 changedEntry.position(pos);
248                 changedEntry.ischanged(true);
249                 updatedEntries.push(changedEntry);
250
251                 // clear the virtual ID
252                 if(changedEntry.isnew())
253                     changedEntry.id(null); 
254
255                 var oldEntry = formula.entries().filter(function(e) {return (e.position() == pos)})[0];
256
257                 if(oldEntry) {
258                     // move the entry currently in that spot temporarily into negative territory
259                     var moveMe = oldEntry.clone();
260                     moveMe.ischanged(true);
261                     moveMe.position(moveMe.position() * -1); 
262                     updatedEntries.unshift(moveMe);
263                 }
264             }
265             pos++;
266         }
267     );
268
269     // finally, for every entry that changed w/o changing position
270     // throw it on the list for update
271     dojo.forEach(
272         formula.entries(),
273         function(entry) {
274             if(entry.ischanged() && !entry.isdeleted() && !entry.isnew()) {
275                 if(updatedEntries.filter(function(e) { return (e.id() == entry.id()) }).length == 0)
276                     updatedEntries.push(entry);
277             }
278         }
279     );
280
281     updatedEntries = deletedEntries.concat(updatedEntries);
282     if(updatedEntries.length) {
283         pcrud = new openils.PermaCrud();
284         try { 
285             pcrud.apply(updatedEntries);
286         } catch(E) {
287             alert('error updating: ' + E);
288             return;
289         }
290         location.href = location.href;
291     }
292 }
293
294