Code coverage report for api/data_list/DataList.js

Statements: 76.06% (197 / 259)      Branches: 68.45% (115 / 168)      Functions: 82.69% (43 / 52)      Lines: 76.06% (197 / 259)      Ignored: none     

All files » api/data_list/ » DataList.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603    1 1 1 1 1 1                                           1 900 814   900 900       900 900         1             301     226                                                         203     886           9     790           3345     448                   5684     588 588 588 8   588   588 588 588                 307 5 5 12   5     302 9 9   293     302 8   294 294   302                                                                                   2       2   2           3     3                             2   2       2     2 2   2   4     4   4 4         4   2   2     2                   60     60 60 54 54 54         54     6 5 5 5 5 5         5             1                 1 1 1 1 1 1       1 1   1 1     1   1 3 3 3 3       3 3 3       1     1   1 1   1   1               1     1           45 45                     964 964                           211 211 130 130 867 867     211     43 4   39   4   35       35 35 15   35 96 96 96 96       96 96 96               6 6     6 6                       1     1   1 1   1     1 1 1 3 3     3 3     3 3 3         1     1             1       1     1       1 3         3 2 2 2   1   1 1           1     1     1     1       1 1 1 2 2 2 2                     2 2   2   2     2       2 2 2               15 4 4   15 15 15 15   15 15   15 15           1      
// console.log("Loading DataList.js");
 
var AudioVideos = require("./../audio_video/AudioVideos").AudioVideos;
var FieldDBObject = require("./../FieldDBObject").FieldDBObject;
var DocumentCollection = require("./../datum/DocumentCollection").DocumentCollection;
var Comments = require("./../comment/Comments").Comments;
var ContextualizableObject = require("./../locales/ContextualizableObject").ContextualizableObject;
var Q = require("q");
 
// console.log("Requireing FieldDBObject from datalist library ", FieldDBObject);
 
/**
 * @class The Data List widget is used for import search, to prepare handouts and to share data on the web.
 *  @name  DataList
 *
 * @description The Data List widget is used for import search, to prepare handouts and to share data on the web.
 *
 * @property {String} title The title of the Data List.
 * @property {String} description The description of the Data List.
 * @property {Array<String>} datumIds Deprecated: An ordered list of the datum IDs of the
 *   Datums in the Data List.
 * @property {Array<String>} docIds An ordered list of the doc IDs of the
 *   Datums in the Data List.
 * @property {Array<String>} docs An ordered collection of the doc IDs of the
 *   Datums in the Data List (not serialized in the DataList)
 *
 * @extends FieldDBObject
 * @constructs
 */
var DataList = function DataList(options) {
  if (!this._fieldDBtype) {
    this._fieldDBtype = "DataList";
  }
  this.debug("Constructing DataList ", options);
  if (options && options.comments) {
    // this.debug("DataList comments", options.comments);
    // this.debug("DataList comments", options.comments);
  }
  FieldDBObject.apply(this, arguments);
  this.debug("   Constructed datalist ", this);
};
 
// console.log("DataList constructor", DataList);
 
DataList.prototype = Object.create(FieldDBObject.prototype, /** @lends DataList.prototype */ {
  constructor: {
    value: DataList
  },
 
  api: {
    get: function() {
      return this._api || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("api", value);
    }
  },
 
  defaults: {
    get: function() {
      return {
        title: "Untitled Data List",
        description: "",
        datumIds: FieldDBObject.DEFAULT_ARRAY,
        docs: FieldDBObject.DEFAULT_COLLECTION
      };
    }
  },
 
  // Internal models: used by the parse function
  INTERNAL_MODELS: {
    value: {
      comments: Comments,
      docs: DocumentCollection,
      title: ContextualizableObject,
      description: ContextualizableObject,
      audioVideo: AudioVideos
        // item: FieldDBObject
    }
  },
 
  title: {
    get: function() {
      return this._title || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("title", value);
    }
  },
 
  description: {
    get: function() {
      return this._description || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("description", value);
    }
  },
 
  audioVideo: {
    get: function() {
      return this._audioVideo || FieldDBObject.DEFAULT_ARRAY;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("audioVideo", value);
    }
  },
 
 
  docs: {
    get: function() {
      // if (this._docs && this._docs.primaryKey !== this.primaryKey) {
      //   this._docs.primaryKey = this.primaryKey;
      // }
      return this._docs;
    },
    set: function(value) {
      this.debug("creating the " + this.id + " datalist's docs");
      var previousPrimaryKey;
      if (this._docs) {
        previousPrimaryKey = this._docs.primaryKey;
      }
      this.ensureSetViaAppropriateType("docs", value);
 
      Eif (this._docs) {
        delete this._docIds;
        Iif (previousPrimaryKey && previousPrimaryKey !== this._docs.primaryKey) {
          this._docs.primaryKey = previousPrimaryKey;
        }
      }
    }
  },
 
  add: {
    value: function(value) {
      if (value && Object.prototype.toString.call(value) === "[object Array]") {
        var self = this;
        for (var itemIndex in value) {
          value[itemIndex] = self.add(value[itemIndex]);
        }
        return value;
      }
 
      if (!this.docs) {
        this.debug("creating the datalist docs ", value);
        this.docs = [];
      } else {
        this.debug("adding to existing datalist docs ", value);
      }
      //Item of the datalist trumps the collections' item type
      if (this.INTERNAL_MODELS && this.INTERNAL_MODELS.item && !(value instanceof this.INTERNAL_MODELS.item)) {
        value = new this.INTERNAL_MODELS.item(value);
      } else {
        this.debug("Setting the type of this new item to LanguageDatum since it didnt have a type before, and there is no default item for this datalist.");
        value.fieldDBtype = value.fieldDBtype || "LanguageDatum";
      }
      return this.docs.add(value);
    }
  },
 
  addReallyComplicatedDeprecated: {
    value: function(value) {
      if (!this.docs || this.docs.length === 0) {
        if (Object.prototype.toString.call(value) === "[object Array]") {
          value = {
            collection: value,
            // primaryKey: "hithere"
          };
        } else {
          value = {
            collection: [value]
          };
        }
        value.primaryKey = this.primaryKey;
        this.debug("setting the docs  : ", value);
        this.docs = value;
        // this.docs.primaryKey = this.primaryKey;
        return this.docs._collection[0];
      }
      this.debug("adding to existing data list", value);
      return this.docs.add(value);
    }
  },
 
  push: {
    value: function(value) {
      if (!this.docs) {
        this.debug("creating the datalist docs ", value);
        this.docs = [];
      } else {
        this.debug("adding to existing datalist docs ", value);
      }
      return this.docs.push(value);
    }
  },
 
  unshift: {
    value: function(value) {
      Iif (!this.docs) {
        this.debug("creating the datalist docs ", value);
        this.docs = [];
      } else {
        this.debug("adding to existing datalist docs ", value);
      }
      return this.docs.unshift(value);
    }
  },
 
  pop: {
    value: function() {
      Iif (!this.docs) {
        return;
      }
      return this.docs.pop();
    }
  },
 
  shift: {
    value: function() {
      if (!this.docs) {
        return;
      }
      return this.docs.shift();
    }
  },
 
  populate: {
    value: function(results) {
      var self = this;
 
      Iif (!this.docs) {
        this.debug("creating the datalist docs to populate ", this);
        this.docs = [];
      } else {
        this.debug("populating an existing database ", this);
      }
 
      var guessedType;
      this.save();
 
      results = results.map(function(doc) {
        // prevent recursion a bit
        Eif (self.api !== "datalists") {
          // doc.api = self.api;
        }
        doc.confidential = self.confidential;
        // doc.url = self.url;
        doc = FieldDBObject.convertDocIntoItsType(doc);
        Iif (doc.fieldDBtype && doc.fieldDBtype === "LanguageDatum") {
          guessedType = "LanguageDatum";
        }
        // self.debug("adding doc", doc);
        // self.docs.add(doc); //This overwrites this doc if in the collection
        return doc;
      });
      self.todo("OVERWRITING NEW INFO INTO EXISTING DATALIST, instead save the existing list, then add them and remove the ones that arent supposed ot be there.");
      // self.docs.debugMode = true;
      self.docs = results; //This ensures that the docs list matches what the server thinks.
      // self.docs.merge("self", results); //This overwrites this doc if in the collection
 
      Iif (guessedType === "LanguageDatum") {
        self.showDocPosition = true;
        self.showDocCheckboxes = true;
        self.docsAreReorderable = true;
      }
    }
  },
 
  reindexFromApi: {
    value: function() {
      var self = this,
        deferred = Q.defer();
 
      this.whenReindexedFromApi = deferred.promise;
      if (!this.api) {
        this.debug("Not reindexing this datalist from the database, its not connected to an api.");
        Q.nextTick(function() {
          deferred.reject({
            status: 412,
            userFriendlyErrors: ["This datalist doesn't need to be re-indexed. 29834."]
          });
        });
        return deferred.promise;
      }
 
      if (!this.corpus || typeof this.corpus.fetchCollection !== "function") {
        self.fetching = self.loading = false;
        self.warn("This datalist has no corpus, it doesnt know how to find out which data are in it.");
        Q.nextTick(function() {
          self.docs = self.docs || [];
          deferred.reject({
            status: 412,
            userFriendlyErrors: ["This application has errored. Please notify its developers: Cannot reindex this datalist if the corpus is not specified."]
          });
        });
        return deferred.promise;
      }
 
      // Q.nextTick(function() {
      //   deferred.resolve(self);
      // });
 
      var unableToFetchCurrentDataAffiliatedWithThisDataList = function(err) {
        self.fetching = self.loading = false;
        self.warn(" problem fetching the data list");
        self.debug("err", err);
        self.docs = self.docs || [];
        deferred.reject(err);
        // return self;
      };
 
      this.fetching = this.loading = true;
      var dataListUrl = "/_design/data/_list/as_data_list/by_type?key=\"" + this.api + "\"";
      this.corpus.fetchCollection(dataListUrl).then(function(generatedDatalist) {
          self.fetching = self.loading = false;
          self.debug("Downloaded the auto-genrated data list of datum ordered by creation date in this data list", generatedDatalist);
          Iif (!generatedDatalist) {
            self.bug("There was a problem downloading the list of data in the " + self.title + " data list. Please report this.");
            return;
          }
          generatedDatalist.docIds = generatedDatalist.docIds || generatedDatalist.datumIds;
          Eif (generatedDatalist.docIds && generatedDatalist.docIds.length > 0) {
            // If the data list was empty, assign the docIds which will populate it with placeholders
            Eif (!self.docs) {
              self.docs = [];
            }
 
            self.debug("Iterating through the docids to make sure they are in the list.");
            // If the data list doesn't have this id, add a placeholder
            generatedDatalist.docIds.map(function(docPrimaryKey) {
              self.debug("Looking at " + docPrimaryKey);
              Eif (!self._docs[docPrimaryKey]) {
                self.debug("converting " + docPrimaryKey + " into a placeholder");
                var docPlaceholder = {
                  dbname: self.dbname,
                  loaded: false
                };
                docPlaceholder[self.primaryKey] = docPrimaryKey;
                self.debug("adding " + docPrimaryKey + " into the docs");
                self.add(docPlaceholder);
              }
            });
            // If the generatedDatalist indicates this doc is (no longer) in this session, remove it?
            Iif (self.length !== generatedDatalist.docIds.length) {
              self.todo("Not removing items whcih the user currently has in this session which the server doesnt know about.");
            }
            delete generatedDatalist.docIds;
          }
          delete generatedDatalist.title;
          delete generatedDatalist.description;
          // self.merge("self", generatedDatalist);
          self.render();
 
          deferred.resolve(self);
          // return self;
        }, unableToFetchCurrentDataAffiliatedWithThisDataList)
        .fail(function(error) {
          console.error(error.stack, self);
          deferred.reject(error);
        })
        .done(function() {
          console.log("Done data list reindex if possible", self.docs.length);
        });
 
      return deferred.promise;
    }
  },
 
  length: {
    get: function() {
      Eif (this.docIds) {
        return this.docIds.length;
      }
      return 0;
    },
    set: function(value) {
      this.warn("data list lengths comes from the size of the datumids, it cant be set manually to " + value);
    }
  },
 
  primaryKey: {
    get: function() {
      Eif (this._docs && this._docs.primaryKey) {
        return this._docs.primaryKey;
      }
      this.warn("cant get the primary key ", this._docs);
      return "id";
    },
    set: function(value) {
      if (this.docs && this.docs.primaryKey && this.docs.primaryKey !== value) {
        this.docs.primaryKey = value;
      }
    }
  },
 
  docIds: {
    get: function() {
      var self = this;
      if (this.docs && this.docs.length) {
        this._docIds = [];
        this._docIds = this.docs.map(function(doc) {
          self.debug("geting doc id of this doc ", doc);
          return doc[self.primaryKey];
        });
      }
      return this._docIds || FieldDBObject.DEFAULT_ARRAY;
    },
    set: function(value) {
      if (value === this._docIds) {
        return;
      }
      if (!value || value === []) {
        // delete this._docIds;
        return;
      }
      Iif (typeof value.map !== "function") {
        console.error(" trying to set docIds of datalist to something that isnt an array.", value);
        throw new Error("This is a very odd set of docIds " + value);
      }
      var self = this;
      if (!this._docs || !this._docs.add || typeof this._docs.add !== "function") {
        this.docs = [];
      }
      value.map(function(docPrimaryKey) {
        self.debug("Looking at " + docPrimaryKey);
        Eif (self._docs && !self._docs[docPrimaryKey]) {
          self.debug("converting " + docPrimaryKey + " into a placeholder");
          var docPlaceholder = {
            dbname: self.dbname,
            loaded: false
          };
          docPlaceholder[self.primaryKey] = docPrimaryKey;
          self.debug("adding " + docPrimaryKey + " into the docs");
          self.add(docPlaceholder);
        }
      });
    }
  },
 
  datumIds: {
    get: function() {
      this.warn("datumIds is deprecated, please use docIds instead.");
      return this.docIds;
    },
    set: function(value) {
      this.warn("datumIds is deprecated, please use docIds instead.");
      this.docIds = value;
    }
  },
 
  icon: {
    get: function() {
      return "thumb-tack";
    }
  },
 
  getAllAudioAndVideoFiles: {
    value: function(datumIdsToGetAudioVideo) {
      var deferred = Q.defer(),
        self = this;
 
      Q.nextTick(function() {
 
        Eif (!datumIdsToGetAudioVideo) {
          datumIdsToGetAudioVideo = self.docIds;
        }
        Iif (datumIdsToGetAudioVideo.length === 0) {
          datumIdsToGetAudioVideo = self.docIds;
        }
        var audioVideoFiles = [];
        self.debug("DATA LIST datumIdsToGetAudioVideo " + JSON.stringify(datumIdsToGetAudioVideo));
        datumIdsToGetAudioVideo.map(function(id) {
          var doc = self.docs[id];
          Iif (!doc) {
            return;
          }
          var audioVideo = doc.audioVideo || doc._audioVideo;
          Iif (!audioVideo || typeof audioVideo.map !== "function") {
            return;
          }
          audioVideo.map(function(audioVideoFile) {
            Eif (audioVideoFile && audioVideoFile.URL) {
              audioVideoFiles.push(audioVideoFile.URL);
            }
          });
        });
 
        deferred.resolve(audioVideoFiles);
 
      });
      return deferred.promise;
    }
  },
 
  select: {
    value: function(attributeToTriggerSelection) {
 
      Iif (!this.docs || !this.docs.collection || typeof this.docs.collection.map !== "function") {
        return [];
      }
 
      var selected = [],
        self = this;
 
      Iif (attributeToTriggerSelection && attributeToTriggerSelection === "all") {
        attributeToTriggerSelection = this.primaryKey;
      }
 
      this.docs.collection.map(function(item) {
        Iif (!attributeToTriggerSelection && item.selected) {
          item.selected = true;
          selected.push(item[self.primaryKey]);
          return;
        }
        if (attributeToTriggerSelection && item[attributeToTriggerSelection]) {
          item.selected = true;
          selected.push(item[self.primaryKey]);
          return;
        }
        item.selected = false;
      });
      this.debug("Selected ", selected);
      return selected;
    }
  },
 
  applyFunctionToAllIds: {
    value: function(docIdsToApplyFunction, functionToApply, functionArguments) {
      Iif (!docIdsToApplyFunction) {
        docIdsToApplyFunction = this.docIds;
      }
      Iif (docIdsToApplyFunction.length === 0) {
        docIdsToApplyFunction = this.select();
      }
      Iif (!functionToApply) {
        functionToApply = "latexitDataList";
      }
      Iif (!functionArguments) {
        //        functionArguments = true; //leave it null so that the defualts will apply in the Datum call
      }
 
      var self = this;
      this.debug("DATA LIST docIdsToApplyFunction " + JSON.stringify(docIdsToApplyFunction));
      docIdsToApplyFunction.map(function(id) {
        var doc = self.docs[id];
        Eif (doc) {
          doc[functionToApply].apply(doc, functionArguments);
          return id;
        } else {
          self.warn(" Doc has not been fetched, cant apply the function to it.");
          return id;
        }
      });
    }
  },
 
  save: {
    value: function(optionalUserWhoSaved, saveEvenIfSeemsUnchanged, optionalUrl) {
      this.debug("Customizing save ", optionalUserWhoSaved, saveEvenIfSeemsUnchanged, optionalUrl);
      var saveResult = FieldDBObject.prototype.save.apply(this, [optionalUserWhoSaved, saveEvenIfSeemsUnchanged, optionalUrl]);
      // Save recursive docs if they are DataLists
      var promises = this.docs
        .filter(function(any) {
          return !!any;
        })
        .map(function(doc) {
          Iif (doc instanceof DataList) {
            return doc.save();
          }
        });
      promises.push(saveResult);
      return Q.allSettled(promises).then(function() {
        return saveResult;
      });
    }
  },
 
  toJSON: {
    value: function(includeEvenEmptyAttributes, removeEmptyAttributes, attributesToIgnore) {
      // Force docIds to be set to current docs
      if (this.docs && this.docs.length > 0) {
        this.docIds = null;
        this.docIds = this.docIds;
      }
      attributesToIgnore = attributesToIgnore || [];
      attributesToIgnore.push("_docs");
      this.debug("Customizing toJSON ", includeEvenEmptyAttributes, attributesToIgnore);
      var json = FieldDBObject.prototype.toJSON.apply(this, [includeEvenEmptyAttributes, removeEmptyAttributes, attributesToIgnore]);
      // delete json.docs;
      this.todo("Adding datumIds for backward compatability until prototype can handle docIds");
      json.datumIds = this.docIds;
 
      this.debug(json);
      return json;
    }
  }
 
});
 
exports.DataList = DataList;
 
// console.log("Exported DataList", exports);