]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/po/search.js
Acq: several interface improvements
[Evergreen.git] / Open-ILS / web / js / ui / default / acq / po / search.js
1 dojo.require('dijit.form.Form');
2 dojo.require('dijit.form.Button');
3 dojo.require('dijit.form.CheckBox');
4 dojo.require('dijit.form.FilteringSelect');
5 dojo.require('dijit.form.NumberTextBox');
6 dojo.require('dojo.data.ItemFileWriteStore');
7 dojo.require('dojo.date.locale');
8 dojo.require('dojo.date.stamp');
9 dojo.require('openils.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.widget.AutoGrid');
12 dojo.require('openils.widget.AutoFieldWidget');
13 dojo.require('openils.PermaCrud');
14
15 var metaPO;
16 var _last_fields;
17 var general_po_search_opts = {"order_by": {"acqpo": "edit_time DESC"}};
18
19 function getPOOwner(rowIndex, item) {
20     if(!item) return '';
21     var data = this.grid.store.getValue(item, 'owner');
22     return new openils.User({id:data}).user.usrname();
23 }
24
25 function doSearch(fields) {
26     _last_fields = dojo.clone(fields); /* Save for re-use */
27     var metapo_view = false;
28
29     /* Remove the metapo_view field from 'fields'... we'll use it later */
30     if (fields.metapo_view && fields.metapo_view[0]) {
31         metapo_view = true;
32         delete fields.metapo_view;
33     }
34
35     if (
36         !(fields.id && fields.id.constructor.name == 'Array') && 
37         isNaN(fields.id)
38     ) {
39         delete fields.id;
40         for(var k in fields) {
41             if(fields[k] == '' || fields[k] == null)
42                 delete fields[k];
43         }
44     } else {
45         // ID search trumps other searches
46         fields = {id:fields.id};
47     }
48
49     // no search fields
50     var some = false;
51     for(var k in fields) some = true;
52     if(!some) fields.id = {'!=' : null};
53
54
55     if (metapo_view) {
56         openils.Util.hide("holds_po_grid");
57         loadMetaPO(fields);
58     } else {
59         if (metaPO) metaPO.myHide();
60         openils.Util.show("holds_po_grid");
61         poGrid.resetStore();
62         poGrid.loadAll(general_po_search_opts, fields);
63     }
64 }
65
66 function loadForm() {
67
68     new openils.widget.AutoFieldWidget({
69         fmClass : 'acqpo', 
70         fmField : 'provider', 
71         parentNode : dojo.byId('po-search-provider-selector'),
72         orgLimitPerms : ['VIEW_PURCHASE_ORDER'],
73         dijitArgs : {name:'provider', required:false}
74     }).build();
75
76     new openils.widget.AutoFieldWidget({
77         fmClass : 'acqpo', 
78         fmField : 'ordering_agency', 
79         parentNode : dojo.byId('po-search-agency-selector'),
80         orgLimitPerms : ['VIEW_PURCHASE_ORDER'],
81         dijitArgs : {name:'ordering_agency', required:false}
82     }).build();
83
84     if (poIds && poIds.length > 0) {
85         dijit.byId("metapo_view").attr("checked", true);
86         doSearch({"id": poIds, "metapo_view": [true] /* [sic] */});
87     } else {
88         doSearch({"ordering_agency": openils.User.user.ws_ou()});
89     }
90 }
91
92 function loadMetaPO(fields) {
93     var pcrud = new openils.PermaCrud();
94     var po_list = pcrud.search("acqpo", fields, general_po_search_opts);
95     if (!po_list || !po_list.length) {
96         alert(localeStrings.NO_PO_RESULTS);
97     } else {
98         if (!metaPO) {
99             metaPO = new AcqLiTable();
100             metaPo.enableActionsDropdownOptions("po");
101
102             /* We need to know the width (in cells) of the template row for
103              * the LI table, and we don't want to hardcode it here. */
104             metaPO.n_cells = dojo.query("> td", metaPO.rowTemplate).length;
105
106             metaPO._copy_count_cb = function(liId, count) {
107                 var poId = this.liCache[liId].purchase_order();
108
109                 if (this.copy_counts[poId] == undefined)
110                     this.copy_counts[poId] = {};
111                 this.copy_counts[poId][liId] = count;
112
113                 this.renderCopyCounts(poId);
114                 this.renderSummary("copies");
115             };
116             metaPO.myHide = function() {
117                 this.hide();
118                 openils.Util.hide("oils-acq-holds-metapo-summary");
119             };
120             metaPO.renderSummary = function(part) {
121                 var self = this;
122                 /* The idea here will be that if "part" is defined, we'll
123                  * just update that part of the metaPO summary, otherwise,
124                  * the whole thing. */
125                 if (part != undefined) {
126                     var target = dojo.byId("oils-acq-metapo-summary-" + part);
127                     switch (part) {
128                         case "copies":
129                             target.innerHTML = self.copiesTotal();
130                             break;
131                         case "po":
132                             target.innerHTML = self.working_po_list.length;
133                             break;
134                         /* Any numeric fields should be named here. */
135                         case "amount_encumbered":
136                         case "amount_spent":
137                             target.innerHTML = self.numericFieldTotal(part);
138                             break;
139                         default:
140                             /* assume a field on the acqpo's themselves */
141                             target.innerHTML = self.anyFieldTotal(part);
142                             break;
143                     }
144                 } else {
145                     openils.Util.show("oils-acq-holds-metapo-summary");
146                     self.totalable_fields.forEach(
147                         function(f) { self.renderSummary(f); }
148                     );
149                 }
150             };
151             metaPO.numericFieldTotal = function(field) {
152                 var self = this;
153                 var pennies = self.working_po_list.reduce(
154                     /* working_po_list contains unfleshed acqpo's, so we must
155                      * find the same PO in the poCache */
156                     function(p, c) {
157                         c = self.poCache[c.id()][field]();
158                         return p + Number(c) * 100;
159                     }, 0
160                 );
161                 return pennies / 100;
162             };
163             metaPO.anyFieldTotal = function(field) {
164                 var self = this;
165                 return self.working_po_list.reduce(
166                     /* working_po_list contains unfleshed acqpo's, so we must
167                      * find the same PO in the poCache */
168                     function(p, c) {
169                         c = self.poCache[c.id()][field]();
170                         return p + Number(c);
171                     }, 0
172                 );
173             };
174             metaPO.renderCopyCounts = function(poId) {
175                 try {
176                     dojo.query("td#oils-acq-po-heading-" + poId +
177                         ' span span[attr="copies"]')[0].innerHTML =
178                             this.copiesByPOId(poId);
179                 } catch (E) {
180                     ;
181                 }
182             };
183             metaPO.sectionHeadingById = function(id) {
184                 var headings = dojo.query("#po-heading-" + id, this.tbody);
185                 if (headings.length != 1) {
186                     alert(localeStrings.PO_HEADING_ERROR);
187                     return undefined;
188                 } else {
189                     return headings[0];
190                 }
191             };
192             metaPO.sectionHeadingByPOId = function(poId) {
193                 return this.sectionHeadingById(this.sections_by_poid[poId]);
194             };
195             metaPO.addSection = function(po) {
196                 var s = this.sections_by_poid[po.id()] = this.sections++;
197
198                 this.tbody.appendChild(
199                     dojo.create("tr", {
200                         "class": "acq-lit-po-heading", "id": "po-heading-" + s
201                     })
202                 );
203
204                 return s;
205             };
206             metaPO.addLineitemToSection = function(li, section) {
207                 dojo.place(
208                     this.addLineitem(li, true /* skip_final_placement */),
209                     this.sectionHeadingById(section),
210                     "after"
211                 );
212             };
213             metaPO.generateActivator = function(id) {
214                 return function() {
215                     progressDialog.show(true);
216                     try {
217                         fieldmapper.standardRequest(
218                             ["open-ils.acq",
219                                 "open-ils.acq.purchase_order.activate"], {
220                                 "async": true,
221                                 "params": [openils.User.authtoken, id],
222                                 "oncomplete": function() {
223                                     progressDialog.hide();
224                                     doSearch(_last_fields);
225                                 }
226                             }
227                         );
228                     } catch (E) {
229                         progressDialog.hide();
230                         alert(E); /* XXX */
231                     }
232                 };
233             };
234             metaPO.renderHeading = function(poId) {
235                 var self = this;
236                 var td = dojo.create("td", {"colspan": self.n_cells});
237                 td.id = "oils-acq-po-heading-" + poId;
238
239                 /* Build our HTML structure from the template... */
240                 dojo.query("> span", "oils-acq-po-heading-template").forEach(
241                     function(s) { td.appendChild(s.cloneNode(true)); }
242                 );
243
244                 /* Some fields straight from the PO object... */
245                 self.po_fields_for_display.forEach(
246                     function(f) {
247                         dojo.query('[attr="' + f + '"]', td)[0].innerHTML =
248                             self.poCache[poId][f]();
249                     }
250                 );
251
252                 /* The name field needs special treatment: it's a link */
253                 dojo.attr(
254                     dojo.query('a[attr="name"]', td)[0],
255                     "href",
256                     oilsBasePath + '/acq/po/view/' + poId
257                 );
258
259                 /* Show an "activate" link, or not, based on "state"... */
260                 var a = dojo.query('a[attr="activator"]', td)[0];
261                 if (self.poCache[poId].state() == "pending") {
262                     a.onclick = self.generateActivator(poId);
263                     openils.Util.show(a, "inline");
264                 } else {
265                     openils.Util.hide(a);
266                 }
267
268                 /* Put the new heading cell in place... */
269                 dojo.place(td, self.sectionHeadingByPOId(poId), "only");
270
271                 /* And finally, render copy info (must happen _after_ heading
272                  * is attached to the DOM tree */
273                 this.renderCopyCounts(poId);
274             };
275             metaPO.copiesByPOId = function(poId) {
276                 if (!this.copy_counts[poId]) return undefined;
277                 var total = 0;
278                 for (var liId in this.copy_counts[poId]) {
279                     total += this.copy_counts[poId][liId];
280                 }
281                 return total;
282             };
283             metaPO.copiesTotal = function() {
284                 var total = 0;
285                 for (var poId in this.copy_counts)
286                     total += this.copiesByPOId(poId);
287                 return total;
288             };
289             metaPO.myReset = function() {
290                 this.isMeta = true;
291                 this.sections = 0;
292                 this.sections_by_poid = {};
293                 this.copy_counts = {};
294                 this.po_fields_for_display = [
295                     "name", "lineitem_count", "amount_encumbered",
296                     "amount_spent", "state"
297                 ];
298                 this.totalable_fields = [
299                     "po", "lineitem_count", "copies",
300                     "amount_encumbered", "amount_spent"
301                 ];
302                 openils.Util.hide("oils-acq-holds-metapo-summary");
303             };
304             metaPO.populate = function(list) {
305                 var self = this;
306                 var done = 0;
307
308                 self.working_po_list = [];
309
310                 progressDialog.show(true);
311                 list.forEach(function(po) {
312                     var sec = self.addSection(po);
313                     fieldmapper.standardRequest(
314                         ["open-ils.acq", "open-ils.acq.lineitem.search"], {
315                             "async": true,
316                             "params": [
317                                 openils.User.authtoken,
318                                 {"purchase_order": po.id()},
319                                 {"flesh_attrs": true, "flesh_notes": true}
320                             ],
321                             "onresponse": function(r) {
322                                 var li = openils.Util.readResponse(r);
323                                 if (li) /* sometimes empty string: disregard */
324                                     self.addLineitemToSection(li, sec);
325                             },
326                             "oncomplete": function(r) {
327                                 self.working_po_list.push(po);
328                                 self.renderHeading(po.id());
329                                 self.renderSummary();
330                                 /* This mechanism avoids calling .show() too
331                                  * often or before results are ready, and
332                                  * thus smooths out DOM rendering glitches. */
333                                 if (++done >= list.length) {
334                                     done = -1;
335                                     self.show("list");
336                                     progressDialog.hide();
337                                 }
338                             }
339                         }
340                     );
341                 });
342                 /* This mechanism sees to it that we call .show() at least once
343                  * even if the search result population seems to be timing
344                  * out or failing. */
345                 setTimeout(
346                     function() {
347                         if (done != -1) {
348                             self.show("list");
349                             progressDialog.hide();
350                         }
351                     }, 10000    /* 10 seconds: make this configurable? */
352                 );
353             };
354         }
355
356         metaPO.reset();
357         metaPO.myReset();
358         metaPO.populate(po_list);
359     }
360 }
361
362 openils.Util.addOnLoad(loadForm);