]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/dojo/openils/FlattenerStore.js
Link checker: Some UI tweaks suggested by George Duimovich
[working/Evergreen.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,
177              * try to use the last cached sort order, if any. */
178             req.sort = req.sort || this._last_fetch_sort;
179             this._last_fetch_sort = req.sort;
180
181             if (!this.mapKey)
182                 this._get_map_key();
183
184             var p = this._build_flattener_params(req);
185             console.debug("_fetch_prepare() returning " + dojo.toJson(p));
186             return p;
187         },
188
189         "_fetch_execute": function(params,handle_as,mime_type,onload,onerror) {
190             dojo.xhrPost({
191                 "url": this._flattener_url,
192                 "content": params,
193                 "handleAs": handle_as,
194                 "sync": false,
195                 "preventCache": true,
196                 "headers": {"Accept": mime_type},
197                 "load": onload,
198                 "error": onerror
199             });
200         },
201
202         /* *** Begin dojo.data.api.Read methods *** */
203
204         "getValue": function(
205             /* object */ item,
206             /* string */ attribute,
207             /* anything */ defaultValue) {
208             //console.log("getValue(" + lazy(item) + ", " + attribute + ", " + defaultValue + ")")
209             if (!this.isItem(item))
210                 throw new FlattenerStoreError("getValue(): bad item " + item);
211             else if (typeof attribute != "string")
212                 throw new FlattenerStoreError("getValue(): bad attribute");
213
214             var value = item[attribute];
215             return (typeof value == "undefined") ? defaultValue : value;
216         },
217
218         "getValues": function(/* object */ item, /* string */ attribute) {
219             //console.log("getValues(" + item + ", " + attribute + ")");
220             if (!this.isItem(item) || typeof attribute != "string")
221                 throw new FlattenerStoreError("bad arguments");
222
223             var result = this.getValue(item, attribute, []);
224             return dojo.isArray(result) ? result : [result];
225         },
226
227         "getAttributes": function(/* object */ item) {
228             //console.log("getAttributes(" + item + ")");
229             if (!this.isItem(item))
230                 throw new FlattenerStoreError("getAttributes(): bad args");
231             else
232                 return this._display_attributes();
233         },
234
235         "hasAttribute": function(/* object */ item, /* string */ attribute) {
236             //console.log("hasAttribute(" + item + ", " + attribute + ")");
237             if (!this.isItem(item) || typeof attribute != "string") {
238                 throw new FlattenerStoreError("hasAttribute(): bad args");
239             } else {
240                 return dojo.indexOf(this._display_attributes(), attribute) > -1;
241             }
242         },
243
244         "containsValue": function(
245             /* object */ item,
246             /* string */ attribute,
247             /* anything */ value) {
248             //console.log("containsValue(" + item + ", " + attribute + ", " + value + ")");
249             if (!this.isItem(item) || typeof attribute != "string")
250                 throw new FlattenerStoreError("bad data");
251             else
252                 return (
253                     dojo.indexOf(this.getValues(item, attribute), value) >= -1
254                 );
255         },
256
257         "isItem": function(/* anything */ something) {
258             //console.log("isItem(" + lazy(something) + ")");
259             if (typeof something != "object" || something === null)
260                 return false;
261
262             var fields = this._display_attributes();
263
264             for (var i = 0; i < fields.length; i++) {
265                 var cur = fields[i];
266                 if (!(cur in something))
267                     return false;
268             }
269             return true;
270         },
271
272         "isItemLoaded": function(/* anything */ something) {
273             /* XXX if 'something' is not an item at all, are we just supposed
274              * to return false or throw an exception? */
275             return this.isItem(something) && (
276                 something[this.fmIdentifier] in this._current_items
277             );
278         },
279
280         "close": function(/* object */ request) { /* no-op */ return; },
281
282         "getLabel": function(/* object */ item) {
283             console.warn("[unimplemented] getLabel()");
284         },
285
286         "getLabelAttributes": function(/* object */ item) {
287             console.warn("[unimplemented] getLabelAttributes()");
288         },
289
290         "loadItem": function(/* object */ keywordArgs) {
291             if (!keywordArgs.force && this.isItemLoaded(keywordArgs.item))
292                 return;
293
294             keywordArgs.identity = this.getIdentity(keywordArgs.item);
295             return this.fetchItemByIdentity(keywordArgs);
296         },
297
298         "fetch": function(/* request-object */ req) {
299             //  Respect the following properties of the *req* object:
300             //
301             //      query    a dojo-style query, which will need modest
302             //                  translation for our server-side service
303             //      count    an int
304             //      onBegin  a callback that takes the number of items
305             //                  that this call to fetch() *could* have
306             //                  returned, with a higher limit. We do
307             //                  tricks with this.
308             //      onItem   a callback that takes each item as we get it
309             //      onComplete  a callback that takes the list of items
310             //                      after they're all fetched
311
312             var self = this;
313             var callback_scope = req.scope || dojo.global;
314             var post_params;
315
316             /* Special options to support special operations (print and csv): */
317             req.flattenerOptions = dojo.mixin(
318                 {}, /* target object */
319                 {   /* default values */
320                     "handleAs": "json",
321                     "contentType": "application/json"
322                 },
323                 req.flattenerOptions /* optional input */
324             );
325
326             try {
327                 post_params = this._fetch_prepare(req);
328             } catch (E) {
329                 if (typeof req.onError == "function")
330                     req.onError.call(callback_scope, E);
331                 else
332                     throw E;
333             }
334
335             var process_fetch = function(obj, when) {
336                 if (when < self._last_fetch) /* Stale response. Discard. */
337                     return;
338
339                 self._retried_map_key_already = false;
340
341                 /* The following is apparently the "right" way to call onBegin,
342                  * and is very necessary (at least in Dojo 1.3.3) to get
343                  * the Grid's fetch-more-when-I-need-it logic to work
344                  * correctly. *grumble* crummy documentation *snarl!*
345                  */
346                 if (typeof req.onBegin == "function") {
347                     /* We lie to onBegin like this because we don't know how
348                      * many more rows we might be able to fetch if the
349                      * user keeps scrolling.  Once we get a number of
350                      * results that is less than the limit we asked for,
351                      * we stop exaggerating, and the grid is smart enough to
352                      * know we're at the end and it does the right thing. */
353                     var might_be_a_lie = req.start;
354                     if (obj.length >= req.count)
355                         might_be_a_lie += obj.length + req.count;
356                     else
357                         might_be_a_lie += obj.length;
358
359                     console.debug(
360                         "process_fetch() calling onBegin with " +
361                         might_be_a_lie + ", " + dojo.toJson(req)
362                     );
363                     req.onBegin.call(callback_scope, might_be_a_lie, req);
364                 }
365
366                 if (req.flattenerOptions.handleAs == "json") {
367                     dojo.forEach(
368                         obj,
369                         function(item) {
370                             /* Cache items internally. */
371                             self._current_items[item[self.fmIdentifier]] = item;
372
373                             if (typeof req.onItem == "function")
374                                 req.onItem.call(callback_scope, item, req);
375                         }
376                     );
377                 }
378
379                 if (typeof req.onComplete == "function")
380                     req.onComplete.call(callback_scope, obj, req);
381             };
382
383             var process_error = dojo.hitch(
384                 this, function(response, ioArgs) {
385                     this._on_http_error(response, ioArgs, req, "fetch");
386                 }
387             );
388
389             var fetch_time = this._last_fetch = (new Date().getTime());
390
391             this._fetch_execute(
392                 post_params,
393                 req.flattenerOptions.handleAs,
394                 req.flattenerOptions.contentType,
395                 function(obj) { process_fetch(obj, fetch_time); },
396                 process_error
397             );
398
399             return req;
400         },
401
402         /* *** Begin dojo.data.api.Identity methods *** */
403
404         "getIdentity": function(/* object */ item) {
405             if (!this.isItem(item))
406                 throw new FlattenerStoreError("not an item");
407
408             return item[this.fmIdentifier];
409         },
410
411         "getIdentityAttributes": function(/* object */ item) {
412             // console.log("getIdentityAttributes(" + item + ")");
413             return [this.fmIdentifier];
414         },
415
416         "fetchItemByIdentity": function(/* object */ keywordArgs) {
417             var callback_scope = keywordArgs.scope || dojo.global;
418             var identity = keywordArgs.identity;
419
420             if (typeof identity == "undefined")
421                 throw new FlattenerStoreError(
422                     "fetchItemByIdentity() needs identity in keywordArgs"
423                 );
424
425             /* First of force's two implications:
426              * fetch even if already loaded. */
427             if (this._current_items[identity] && !keywordArgs.force) {
428                 keywordArgs.onItem.call(
429                     callback_scope, this._current_items[identity]
430                 );
431
432                 return;
433             }
434
435             var post_params;
436             try {
437                 post_params = this._fetch_prepare(keywordArgs);
438             } catch (E) {
439                 if (typeof keywordArgs.onError == "function")
440                     keywordArgs.onError.call(callback_scope, E);
441                 else
442                     throw E;
443             }
444
445             var process_fetch_one = dojo.hitch(
446                 this, function(obj, when) {
447                     if (when < this._last_fetch) /* Stale response. Discard. */
448                         return;
449
450                     if (dojo.isArray(obj)) {
451                         if (obj.length <= 1) {
452                             obj = obj.pop() || null;    /* safe enough */
453                             /* Second of force's two implications: call setValue
454                              * ourselves.  Makes a DataGrid update. */
455                             if (keywordArgs.force && obj &&
456                                 (origitem = this._current_items[identity])) {
457                                 for (var prop in origitem)
458                                     this.setValue(origitem, prop, obj[prop]);
459                             }
460                             if (keywordArgs.onItem)
461                                 keywordArgs.onItem.call(callback_scope, obj);
462                         } else {
463                             var e = new FlattenerStoreError("Too many results");
464                             if (keywordArgs.onError)
465                                 keywordArgs.onError.call(callback_scope, e);
466                             else
467                                 throw e;
468                         }
469                     } else {
470                         var e = new FlattenerStoreError("Bad response");
471                         if (keywordArgs.onError)
472                             keywordArgs.onError.call(callback_scope, e);
473                         else
474                             throw e;
475                     }
476                 }
477             );
478
479             var process_error = dojo.hitch(
480                 this, function(response, ioArgs) {
481                     this._on_http_error(
482                         response, ioArgs, keywordArgs, "fetchItemByIdentity"
483                     );
484                 }
485             );
486
487             var fetch_time = this._last_fetch = (new Date().getTime());
488
489             this._fetch_execute(
490                 post_params,
491                 "json",
492                 "application/json",
493                 function(obj) { process_fetch_one(obj, fetch_time); },
494                 process_error
495             );
496         },
497
498         /* dojo.data.api.Write - only very partially implemented, because
499          * for FlattenerGrid, the intended client of this store, we don't
500          * need most of the methods. */
501
502         "deleteItem": function(item) {
503             //console.log("deleteItem()");
504
505             var identity = this.getIdentity(item);
506             delete this._current_items[identity];   /* safe even if missing */
507
508             this.onDelete(item);
509         },
510
511         "setValue": function(item, attribute, value) {
512             /* Silently do nothing when setValue()'s caller wants to change
513              * the identifier.  They must be confused anyway. */
514             if (attribute == this.fmIdentifier)
515                 return;
516
517             var old_value = dojo.clone(item[attribute]);
518
519             item[attribute] = dojo.clone(value);
520             this.onSet(item, attribute, old_value, value);
521         },
522
523         "setValues": function(item, attribute, values) {
524             console.warn("[unimplemented] setValues()");    /* unneeded */
525         },
526
527         "newItem": function(keywordArgs, parentInfo) {
528             console.warn("[unimplemented] newItem()");    /* unneeded */
529         },
530
531         "unsetAttribute": function() {
532             console.warn("[unimplemented] unsetAttribute()");   /* unneeded */
533         },
534
535         "save": function() {
536             console.warn("[unimplemented] save()"); /* unneeded */
537         },
538
539         "revert": function() {
540             console.warn("[unimplemented] revert()");   /* unneeded */
541         },
542
543         "isDirty": function() { /* I /think/ this will be ok for our purposes */
544             console.info("[stub] isDirty() will always return false");
545
546             return false;
547         },
548
549         /* dojo.data.api.Notification - Keep these no-op methods because
550          * clients will dojo.connect() to them.  */
551
552         "onNew" : function(item) { /* no-op */ },
553         "onDelete" : function(item) { /* no-op */ },
554         "onSet": function(item, attr, oldval, newval) { /* no-op */ },
555
556         /* *** Classes implementing any Dojo APIs do this to list which
557          *     APIs they're implementing. *** */
558
559         "getFeatures": function() {
560             return {
561                 "dojo.data.api.Read": true,
562                 "dojo.data.api.Identity": true,
563                 "dojo.data.api.Notification": true,
564                 "dojo.data.api.Write": true     /* well, only partly */
565             };
566         }
567     });
568 }