1 if (!dojo._hasResource["openils.FlattenerStore"]) {
2 dojo._hasResource["openils.FlattenerStore"] = true;
4 dojo.provide("openils.FlattenerStore");
6 dojo.require("DojoSRF");
7 dojo.require("openils.User");
8 dojo.require("openils.Util");
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;
17 "openils.FlattenerStore", null, {
19 "_last_fetch": null, /* timestamp. used internally */
20 "_last_fetch_sort": null, /* dijit sort object. used internally */
21 "_flattener_url": "/opac/extras/flattener",
23 /* Everything between here and the constructor can be specified in
24 * the constructor's args object. */
33 "sortFieldReMap": null,
35 "constructor": function(/* object */ args) {
36 dojo.mixin(this, args);
37 this._current_items = {};
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 || [];
45 return (this.baseSort || []).concat(
49 o[d.attribute] = d.descending ? "desc" : "asc";
56 "_remap_sort": function(prepared_sort) {
57 if (this.sortFieldReMap) {
58 return prepared_sort.map(
61 if (typeof exp == "object") {
65 var newkey = (key in this.sortFieldReMap) ?
66 this.sortFieldReMap[key] : key;
71 return (exp in this.sortFieldReMap) ?
72 this.sortFieldReMap[exp] : exp;
82 "_build_flattener_params": function(req) {
85 "ses": openils.User.authtoken
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) {
92 where[this.fmIdentifier] = req.identity;
94 params.where = dojo.toJson(where);
96 params.where = dojo.toJson(req.query);
99 "sort": this._remap_sort(this._prepare_sort(req.sort))
102 if (!req.queryOptions.all) {
104 (!isNaN(req.count) && req.count != Infinity) ?
105 req.count : this.limit;
108 (!isNaN(req.start) && req.start != Infinity) ?
109 req.start : this.offset;
112 if (req.queryOptions.columns)
113 params.columns = req.queryOptions.columns;
114 if (req.queryOptions.labels)
115 params.labels = req.queryOptions.labels;
117 params.slo = dojo.toJson(slo);
121 params.key = this.mapKey;
123 params.map = dojo.toJson(this.mapClause);
126 // for (var key in params)
127 // console.debug("flattener param " + key + " -> " + params[key]);
132 "_display_attributes": function() {
135 return openils.Util.objectProperties(this.mapClause).filter(
136 function(key) { return self.mapClause[key].display; }
140 "_get_map_key": function() {
141 //console.debug("mapClause: " + dojo.toJson(this.mapClause));
142 this.mapKey = fieldmapper.standardRequest(
144 "open-ils.fielder.flattened_search.prepare"], {
145 "params": [openils.User.authtoken, this.fmClass,
152 "_on_http_error": function(response, ioArgs, req, retry_method) {
153 if (response.status == 402) { /* 'Payment Required' stands
155 if (this._retried_map_key_already) {
156 var e = new FlattenerStoreError(
157 "Server won't cache flattener map?"
159 if (typeof req.onError == "function")
160 req.onError.call(callback_scope, e);
164 this._retried_map_key_already = true;
167 return this[retry_method](req);
172 "_fetch_prepare": function(req) {
173 req.queryOptions = req.queryOptions || {};
174 req.abort = function() { console.warn("[unimplemented] abort()"); };
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;
184 var p = this._build_flattener_params(req);
185 console.debug("_fetch_prepare() returning " + dojo.toJson(p));
189 "_fetch_execute": function(params,handle_as,mime_type,onload,onerror) {
191 "url": this._flattener_url,
193 "handleAs": handle_as,
195 "preventCache": true,
196 "headers": {"Accept": mime_type},
202 /* *** Begin dojo.data.api.Read methods *** */
204 "getValue": function(
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");
214 var value = item[attribute];
215 return (typeof value == "undefined") ? defaultValue : value;
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");
223 var result = this.getValue(item, attribute, []);
224 return dojo.isArray(result) ? result : [result];
227 "getAttributes": function(/* object */ item) {
228 //console.log("getAttributes(" + item + ")");
229 if (!this.isItem(item))
230 throw new FlattenerStoreError("getAttributes(): bad args");
232 return this._display_attributes();
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");
240 return dojo.indexOf(this._display_attributes(), attribute) > -1;
244 "containsValue": function(
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");
253 dojo.indexOf(this.getValues(item, attribute), value) >= -1
257 "isItem": function(/* anything */ something) {
258 //console.log("isItem(" + lazy(something) + ")");
259 if (typeof something != "object" || something === null)
262 var fields = this._display_attributes();
264 for (var i = 0; i < fields.length; i++) {
266 if (!(cur in something))
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
280 "close": function(/* object */ request) { /* no-op */ return; },
282 "getLabel": function(/* object */ item) {
283 console.warn("[unimplemented] getLabel()");
286 "getLabelAttributes": function(/* object */ item) {
287 console.warn("[unimplemented] getLabelAttributes()");
290 "loadItem": function(/* object */ keywordArgs) {
291 if (!keywordArgs.force && this.isItemLoaded(keywordArgs.item))
294 keywordArgs.identity = this.getIdentity(keywordArgs.item);
295 return this.fetchItemByIdentity(keywordArgs);
298 "fetch": function(/* request-object */ req) {
299 // Respect the following properties of the *req* object:
301 // query a dojo-style query, which will need modest
302 // translation for our server-side service
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
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
313 var callback_scope = req.scope || dojo.global;
316 /* Special options to support special operations (print and csv): */
317 req.flattenerOptions = dojo.mixin(
318 {}, /* target object */
319 { /* default values */
321 "contentType": "application/json"
323 req.flattenerOptions /* optional input */
327 post_params = this._fetch_prepare(req);
329 if (typeof req.onError == "function")
330 req.onError.call(callback_scope, E);
335 var process_fetch = function(obj, when) {
336 if (when < self._last_fetch) /* Stale response. Discard. */
339 self._retried_map_key_already = false;
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!*
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;
357 might_be_a_lie += obj.length;
360 "process_fetch() calling onBegin with " +
361 might_be_a_lie + ", " + dojo.toJson(req)
363 req.onBegin.call(callback_scope, might_be_a_lie, req);
366 if (req.flattenerOptions.handleAs == "json") {
370 /* Cache items internally. */
371 self._current_items[item[self.fmIdentifier]] = item;
373 if (typeof req.onItem == "function")
374 req.onItem.call(callback_scope, item, req);
379 if (typeof req.onComplete == "function")
380 req.onComplete.call(callback_scope, obj, req);
383 var process_error = dojo.hitch(
384 this, function(response, ioArgs) {
385 this._on_http_error(response, ioArgs, req, "fetch");
389 var fetch_time = this._last_fetch = (new Date().getTime());
393 req.flattenerOptions.handleAs,
394 req.flattenerOptions.contentType,
395 function(obj) { process_fetch(obj, fetch_time); },
402 /* *** Begin dojo.data.api.Identity methods *** */
404 "getIdentity": function(/* object */ item) {
405 if (!this.isItem(item))
406 throw new FlattenerStoreError("not an item");
408 return item[this.fmIdentifier];
411 "getIdentityAttributes": function(/* object */ item) {
412 // console.log("getIdentityAttributes(" + item + ")");
413 return [this.fmIdentifier];
416 "fetchItemByIdentity": function(/* object */ keywordArgs) {
417 var callback_scope = keywordArgs.scope || dojo.global;
418 var identity = keywordArgs.identity;
420 if (typeof identity == "undefined")
421 throw new FlattenerStoreError(
422 "fetchItemByIdentity() needs identity in keywordArgs"
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]
437 post_params = this._fetch_prepare(keywordArgs);
439 if (typeof keywordArgs.onError == "function")
440 keywordArgs.onError.call(callback_scope, E);
445 var process_fetch_one = dojo.hitch(
446 this, function(obj, when) {
447 if (when < this._last_fetch) /* Stale response. Discard. */
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]);
460 if (keywordArgs.onItem)
461 keywordArgs.onItem.call(callback_scope, obj);
463 var e = new FlattenerStoreError("Too many results");
464 if (keywordArgs.onError)
465 keywordArgs.onError.call(callback_scope, e);
470 var e = new FlattenerStoreError("Bad response");
471 if (keywordArgs.onError)
472 keywordArgs.onError.call(callback_scope, e);
479 var process_error = dojo.hitch(
480 this, function(response, ioArgs) {
482 response, ioArgs, keywordArgs, "fetchItemByIdentity"
487 var fetch_time = this._last_fetch = (new Date().getTime());
493 function(obj) { process_fetch_one(obj, fetch_time); },
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. */
502 "deleteItem": function(item) {
503 //console.log("deleteItem()");
505 var identity = this.getIdentity(item);
506 delete this._current_items[identity]; /* safe even if missing */
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)
517 var old_value = dojo.clone(item[attribute]);
519 item[attribute] = dojo.clone(value);
520 this.onSet(item, attribute, old_value, value);
523 "setValues": function(item, attribute, values) {
524 console.warn("[unimplemented] setValues()"); /* unneeded */
527 "newItem": function(keywordArgs, parentInfo) {
528 console.warn("[unimplemented] newItem()"); /* unneeded */
531 "unsetAttribute": function() {
532 console.warn("[unimplemented] unsetAttribute()"); /* unneeded */
536 console.warn("[unimplemented] save()"); /* unneeded */
539 "revert": function() {
540 console.warn("[unimplemented] revert()"); /* unneeded */
543 "isDirty": function() { /* I /think/ this will be ok for our purposes */
544 console.info("[stub] isDirty() will always return false");
549 /* dojo.data.api.Notification - Keep these no-op methods because
550 * clients will dojo.connect() to them. */
552 "onNew" : function(item) { /* no-op */ },
553 "onDelete" : function(item) { /* no-op */ },
554 "onSet": function(item, attr, oldval, newval) { /* no-op */ },
556 /* *** Classes implementing any Dojo APIs do this to list which
557 * APIs they're implementing. *** */
559 "getFeatures": function() {
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 */