Fix sorting when printing from FlattenerGrid-based interfaces
[transitory.git] / Open-ILS / web / js / dojo / openils / FlattenerStore.js
1 if (!dojo._hasResource["openils.FlattenerStore"]) {
2     dojo._hasResource["openils.FlattenerStore"] = true;
3
4     dojo.provide("openils.FlattenerStore");
5
6     dojo.require("DojoSRF");
7     dojo.require("openils.User");
8     dojo.require("openils.Util");
9
10     /* An exception class specific to openils.FlattenerStore */
11     function FlattenerStoreError(message) { this.message = message; }
12     FlattenerStoreError.prototype.toString = function() {
13         return "openils.FlattenerStore: " + this.message;
14     };
15
16     dojo.declare(
17         "openils.FlattenerStore", null, {
18
19         "_last_fetch": null,        /* timestamp. used internally */
20         "_last_fetch_sort": null,   /* dijit sort object. used internally */
21         "_flattener_url": "/opac/extras/flattener",
22
23         /* Everything between here and the constructor can be specified in
24          * the constructor's args object. */
25
26         "fmClass": null,
27         "mapClause": null,
28         "sloClause": null,
29         "limit": 25,
30         "offset": 0,
31         "baseSort": null,
32         "defaultSort": null,
33         "sortFieldReMap": null,
34
35         "constructor": function(/* object */ args) {
36             dojo.mixin(this, args);
37             this._current_items = {};
38         },
39
40         /* turn dojo-style sort into flattener-style sort */
41         "_prepare_sort": function(dsort) {
42             if (!dsort || !dsort.length)
43                 return this.baseSort || this.defaultSort || [];
44
45             return (this.baseSort || []).concat(
46                 dsort.map(
47                     function(d) {
48                         var o = {};
49                         o[d.attribute] = d.descending ? "desc" : "asc";
50                         return o;
51                     }
52                 )
53             );
54         },
55
56         "_remap_sort": function(prepared_sort) {
57             if (this.sortFieldReMap) {
58                 return prepared_sort.map(
59                     dojo.hitch(
60                         this, function(exp) {
61                             if (typeof exp == "object") {
62                                 var key;
63                                 for (key in exp)
64                                     break;
65                                 var newkey = (key in this.sortFieldReMap) ?
66                                     this.sortFieldReMap[key] : key;
67                                 var o = {};
68                                 o[newkey] = exp[key];
69                                 return o;
70                             } else {
71                                 return (exp in this.sortFieldReMap) ?
72                                     this.sortFieldReMap[exp] : exp;
73                             }
74                         }
75                     )
76                 );
77             } else {
78                 return prepared_sort;
79             }
80         },
81
82         "_build_flattener_params": function(req) {
83             var params = {
84                 "hint": this.fmClass,
85                 "ses": openils.User.authtoken
86             };
87
88             /* If we're asked for a specific identity, we don't use
89              * any query or sort/count/start (sort/limit/offset).  */
90             if ("identity" in req) {
91                 var where = {};
92                 where[this.fmIdentifier] = req.identity;
93
94                 params.where = dojo.toJson(where);
95             } else {
96                 params.where =  dojo.toJson(req.query);
97
98                 var slo = {
99                     "sort": this._remap_sort(this._prepare_sort(req.sort))
100                 };
101
102                 if (!req.queryOptions.all) {
103                     slo.limit =
104                         (!isNaN(req.count) && req.count != Infinity) ?
105                             req.count : this.limit;
106
107                     slo.offset =
108                         (!isNaN(req.start) && req.start != Infinity) ?
109                             req.start : this.offset;
110                 }
111
112                 if (req.queryOptions.columns)
113                     params.columns = req.queryOptions.columns;
114                 if (req.queryOptions.labels)
115                     params.labels = req.queryOptions.labels;
116
117                 params.slo = dojo.toJson(slo);
118             }
119
120             if (this.mapKey) {
121                 params.key = this.mapKey;
122             } else {
123                 params.map = dojo.toJson(this.mapClause);
124             }
125
126 //            for (var key in params)
127 //                console.debug("flattener param " + key + " -> " + params[key]);
128
129             return params;
130         },
131
132         "_display_attributes": function() {
133             var self = this;
134
135             return openils.Util.objectProperties(this.mapClause).filter(
136                 function(key) { return self.mapClause[key].display; }
137             );
138         },
139
140         "_get_map_key": function() {
141             //console.debug("mapClause: " + dojo.toJson(this.mapClause));
142             this.mapKey = fieldmapper.standardRequest(
143                 ["open-ils.fielder",
144                     "open-ils.fielder.flattened_search.prepare"], {
145                     "params": [openils.User.authtoken, this.fmClass,
146                         this.mapClause],
147                     "async": false
148                 }
149             );
150         },
151
152         "_on_http_error": function(response, ioArgs, req, retry_method) {
153             if (response.status == 402) {   /* 'Payment Required' stands
154                                                in for cache miss */
155                 if (this._retried_map_key_already) {
156                     var e = new FlattenerStoreError(
157                         "Server won't cache flattener map?"
158                     );
159                     if (typeof req.onError == "function")
160                         req.onError.call(callback_scope, e);
161                     else
162                         throw e;
163                 } else {
164                     this._retried_map_key_already = true;
165                     delete this.mapKey;
166                     if (retry_method)
167                         return this[retry_method](req);
168                 }
169             }
170         },
171
172         "_fetch_prepare": function(req) {
173             req.queryOptions = req.queryOptions || {};
174             req.abort = function() { console.warn("[unimplemented] abort()"); };
175
176             /* If we were asked to fetch without any sort order specified (as
177              * will happen when coming from fetchToPrint(), try to use the
178              * last cached sort order, if any. */
179             req.sort = req.sort || this._last_fetch_sort;
180             this._last_fetch_sort = req.sort;
181
182             if (!this.mapKey)
183                 this._get_map_key();
184
185             return this._build_flattener_params(req);
186         },
187
188         "_fetch_execute": function(params,handle_as,mime_type,onload,onerror) {
189             dojo.xhrPost({
190                 "url": this._flattener_url,
191                 "content": params,
192                 "handleAs": handle_as,
193                 "sync": false,
194                 "preventCache": true,
195                 "headers": {"Accept": mime_type},
196                 "load": onload,
197                 "error": onerror
198             });
199         },
200
201         /* *** Nonstandard but public API - Please think hard about doing
202          * things the Dojo Way whenever possible before extending the API
203          * here. *** */
204
205         /* fetchToPrint() acts like a lot like fetch(), but doesn't call
206          * onBegin or onComplete.  */
207         "fetchToPrint": function(req) {
208             var callback_scope = req.scope || dojo.global;
209             var post_params;
210
211             try {
212                 post_params = this._fetch_prepare(req);
213             } catch (E) {
214                 if (typeof req.onError == "function")
215                     req.onError.call(callback_scope, E);
216                 else
217                     throw E;
218             }
219
220             var process_fetch_all = dojo.hitch(
221                 this, function(text) {
222                     this._retried_map_key_already = false;
223
224                     if (typeof req.onComplete == "function")
225                         req.onComplete.call(callback_scope, text, req);
226                 }
227             );
228
229             var process_error = dojo.hitch(
230                 this, function(response, ioArgs) {
231                     this._on_http_error(response, ioArgs, req, "fetchToPrint");
232                 }
233             );
234
235             this._fetch_execute(
236                 post_params,
237                 "text",
238                 "text/html",
239                 process_fetch_all,
240                 process_error
241             );
242
243             return req;
244         },
245
246         /* *** Begin dojo.data.api.Read methods *** */
247
248         "getValue": function(
249             /* object */ item,
250             /* string */ attribute,
251             /* anything */ defaultValue) {
252             //console.log("getValue(" + lazy(item) + ", " + attribute + ", " + defaultValue + ")")
253             if (!this.isItem(item))
254                 throw new FlattenerStoreError("getValue(): bad item " + item);
255             else if (typeof attribute != "string")
256                 throw new FlattenerStoreError("getValue(): bad attribute");
257
258             var value = item[attribute];
259             return (typeof value == "undefined") ? defaultValue : value;
260         },
261
262         "getValues": function(/* object */ item, /* string */ attribute) {
263             //console.log("getValues(" + item + ", " + attribute + ")");
264             if (!this.isItem(item) || typeof attribute != "string")
265                 throw new FlattenerStoreError("bad arguments");
266
267             var result = this.getValue(item, attribute, []);
268             return dojo.isArray(result) ? result : [result];
269         },
270
271         "getAttributes": function(/* object */ item) {
272             //console.log("getAttributes(" + item + ")");
273             if (!this.isItem(item))
274                 throw new FlattenerStoreError("getAttributes(): bad args");
275             else
276                 return this._display_attributes();
277         },
278
279         "hasAttribute": function(/* object */ item, /* string */ attribute) {
280             //console.log("hasAttribute(" + item + ", " + attribute + ")");
281             if (!this.isItem(item) || typeof attribute != "string") {
282                 throw new FlattenerStoreError("hasAttribute(): bad args");
283             } else {
284                 return dojo.indexOf(this._display_attributes(), attribute) > -1;
285             }
286         },
287
288         "containsValue": function(
289             /* object */ item,
290             /* string */ attribute,
291             /* anything */ value) {
292             //console.log("containsValue(" + item + ", " + attribute + ", " + value + ")");
293             if (!this.isItem(item) || typeof attribute != "string")
294                 throw new FlattenerStoreError("bad data");
295             else
296                 return (
297                     dojo.indexOf(this.getValues(item, attribute), value) >= -1
298                 );
299         },
300
301         "isItem": function(/* anything */ something) {
302             //console.log("isItem(" + lazy(something) + ")");
303             if (typeof something != "object" || something === null)
304                 return false;
305
306             var fields = this._display_attributes();
307
308             for (var i = 0; i < fields.length; i++) {
309                 var cur = fields[i];
310                 if (!(cur in something))
311                     return false;
312             }
313             return true;
314         },
315
316         "isItemLoaded": function(/* anything */ something) {
317             /* XXX if 'something' is not an item at all, are we just supposed
318              * to return false or throw an exception? */
319             return this.isItem(something) && (
320                 something[this.fmIdentifier] in this._current_items
321             );
322         },
323
324         "close": function(/* object */ request) { /* no-op */ return; },
325
326         "getLabel": function(/* object */ item) {
327             console.warn("[unimplemented] getLabel()");
328         },
329
330         "getLabelAttributes": function(/* object */ item) {
331             console.warn("[unimplemented] getLabelAttributes()");
332         },
333
334         "loadItem": function(/* object */ keywordArgs) {
335             if (!keywordArgs.force && this.isItemLoaded(keywordArgs.item))
336                 return;
337
338             keywordArgs.identity = this.getIdentity(keywordArgs.item);
339             return this.fetchItemByIdentity(keywordArgs);
340         },
341
342         "fetch": function(/* request-object */ req) {
343             //  Respect the following properties of the *req* object:
344             //
345             //      query    a dojo-style query, which will need modest
346             //                  translation for our server-side service
347             //      count    an int
348             //      onBegin  a callback that takes the number of items
349             //                  that this call to fetch() *could* have
350             //                  returned, with a higher limit. We do
351             //                  tricks with this.
352             //      onItem   a callback that takes each item as we get it
353             //      onComplete  a callback that takes the list of items
354             //                      after they're all fetched
355
356             var self = this;
357             var callback_scope = req.scope || dojo.global;
358             var post_params;
359
360             try {
361                 post_params = this._fetch_prepare(req);
362             } catch (E) {
363                 if (typeof req.onError == "function")
364                     req.onError.call(callback_scope, E);
365                 else
366                     throw E;
367             }
368
369             var process_fetch = function(obj, when) {
370                 if (when < self._last_fetch) /* Stale response. Discard. */
371                     return;
372
373                 self._retried_map_key_already = false;
374
375                 /* The following is apparently the "right" way to call onBegin,
376                  * and is very necessary (at least in Dojo 1.3.3) to get
377                  * the Grid's fetch-more-when-I-need-it logic to work
378                  * correctly. *grumble* crummy documentation *snarl!*
379                  */
380                 if (typeof req.onBegin == "function") {
381                     /* We lie to onBegin like this because we don't know how
382                      * many more rows we might be able to fetch if the
383                      * user keeps scrolling.  Once we get a number of
384                      * results that is less than the limit we asked for,
385                      * we stop exaggerating, and the grid is smart enough to
386                      * know we're at the end and it does the right thing. */
387                     var might_be_a_lie = req.start;
388                     if (obj.length >= req.count)
389                         might_be_a_lie += obj.length + req.count;
390                     else
391                         might_be_a_lie += obj.length;
392
393                     req.onBegin.call(callback_scope, might_be_a_lie, req);
394                 }
395
396                 dojo.forEach(
397                     obj,
398                     function(item) {
399                         /* Cache items internally. */
400                         self._current_items[item[self.fmIdentifier]] = item;
401
402                         if (typeof req.onItem == "function")
403                             req.onItem.call(callback_scope, item, req);
404                     }
405                 );
406
407                 if (typeof req.onComplete == "function")
408                     req.onComplete.call(callback_scope, obj, req);
409             };
410
411             var process_error = dojo.hitch(
412                 this, function(response, ioArgs) {
413                     this._on_http_error(response, ioArgs, req, "fetch");
414                 }
415             );
416
417             var fetch_time = this._last_fetch = (new Date().getTime());
418
419             this._fetch_execute(
420                 post_params,
421                 "json",
422                 "application/json",
423                 function(obj) { process_fetch(obj, fetch_time); },
424                 process_error
425             );
426
427             return req;
428         },
429
430         /* *** Begin dojo.data.api.Identity methods *** */
431
432         "getIdentity": function(/* object */ item) {
433             if (!this.isItem(item))
434                 throw new FlattenerStoreError("not an item");
435
436             return item[this.fmIdentifier];
437         },
438
439         "getIdentityAttributes": function(/* object */ item) {
440             // console.log("getIdentityAttributes(" + item + ")");
441             return [this.fmIdentifier];
442         },
443
444         "fetchItemByIdentity": function(/* object */ keywordArgs) {
445             var callback_scope = keywordArgs.scope || dojo.global;
446             var identity = keywordArgs.identity;
447
448             if (typeof identity == "undefined")
449                 throw new FlattenerStoreError(
450                     "fetchItemByIdentity() needs identity in keywordArgs"
451                 );
452
453             /* First of force's two implications:
454              * fetch even if already loaded. */
455             if (this._current_items[identity] && !keywordArgs.force) {
456                 keywordArgs.onItem.call(
457                     callback_scope, this._current_items[identity]
458                 );
459
460                 return;
461             }
462
463             var post_params;
464             try {
465                 post_params = this._fetch_prepare(keywordArgs);
466             } catch (E) {
467                 if (typeof keywordArgs.onError == "function")
468                     keywordArgs.onError.call(callback_scope, E);
469                 else
470                     throw E;
471             }
472
473             var process_fetch_one = dojo.hitch(
474                 this, function(obj, when) {
475                     if (when < this._last_fetch) /* Stale response. Discard. */
476                         return;
477
478                     if (dojo.isArray(obj)) {
479                         if (obj.length <= 1) {
480                             obj = obj.pop() || null;    /* safe enough */
481                             /* Second of force's two implications: call setValue
482                              * ourselves.  Makes a DataGrid update. */
483                             if (keywordArgs.force && obj &&
484                                 (origitem = this._current_items[identity])) {
485                                 for (var prop in origitem)
486                                     this.setValue(origitem, prop, obj[prop]);
487                             }
488                             if (keywordArgs.onItem)
489                                 keywordArgs.onItem.call(callback_scope, obj);
490                         } else {
491                             var e = new FlattenerStoreError("Too many results");
492                             if (keywordArgs.onError)
493                                 keywordArgs.onError.call(callback_scope, e);
494                             else
495                                 throw e;
496                         }
497                     } else {
498                         var e = new FlattenerStoreError("Bad response");
499                         if (keywordArgs.onError)
500                             keywordArgs.onError.call(callback_scope, e);
501                         else
502                             throw e;
503                     }
504                 }
505             );
506
507             var process_error = dojo.hitch(
508                 this, function(response, ioArgs) {
509                     this._on_http_error(
510                         response, ioArgs, keywordArgs, "fetchItemByIdentity"
511                     );
512                 }
513             );
514
515             var fetch_time = this._last_fetch = (new Date().getTime());
516
517             this._fetch_execute(
518                 post_params,
519                 "json",
520                 "application/json",
521                 function(obj) { process_fetch_one(obj, fetch_time); },
522                 process_error
523             );
524         },
525
526         /* dojo.data.api.Write - only very partially implemented, because
527          * for FlattenerGrid, the intended client of this store, we don't
528          * need most of the methods. */
529
530         "deleteItem": function(item) {
531             //console.log("deleteItem()");
532
533             var identity = this.getIdentity(item);
534             delete this._current_items[identity];   /* safe even if missing */
535
536             this.onDelete(item);
537         },
538
539         "setValue": function(item, attribute, value) {
540             /* Silently do nothing when setValue()'s caller wants to change
541              * the identifier.  They must be confused anyway. */
542             if (attribute == this.fmIdentifier)
543                 return;
544
545             var old_value = dojo.clone(item[attribute]);
546
547             item[attribute] = dojo.clone(value);
548             this.onSet(item, attribute, old_value, value);
549         },
550
551         "setValues": function(item, attribute, values) {
552             console.warn("[unimplemented] setValues()");    /* unneeded */
553         },
554
555         "newItem": function(keywordArgs, parentInfo) {
556             console.warn("[unimplemented] newItem()");    /* unneeded */
557         },
558
559         "unsetAttribute": function() {
560             console.warn("[unimplemented] unsetAttribute()");   /* unneeded */
561         },
562
563         "save": function() {
564             console.warn("[unimplemented] save()"); /* unneeded */
565         },
566
567         "revert": function() {
568             console.warn("[unimplemented] revert()");   /* unneeded */
569         },
570
571         "isDirty": function() { /* I /think/ this will be ok for our purposes */
572             console.info("[stub] isDirty() will always return false");
573
574             return false;
575         },
576
577         /* dojo.data.api.Notification - Keep these no-op methods because
578          * clients will dojo.connect() to them.  */
579
580         "onNew" : function(item) { /* no-op */ },
581         "onDelete" : function(item) { /* no-op */ },
582         "onSet": function(item, attr, oldval, newval) { /* no-op */ },
583
584         /* *** Classes implementing any Dojo APIs do this to list which
585          *     APIs they're implementing. *** */
586
587         "getFeatures": function() {
588             return {
589                 "dojo.data.api.Read": true,
590                 "dojo.data.api.Identity": true,
591                 "dojo.data.api.Notification": true,
592                 "dojo.data.api.Write": true     /* well, only partly */
593             };
594         }
595     });
596 }