<commit_before>/*
 * TreatJS: Sandbox
 * http://proglang.informatik.uni-freiburg.de/treatjs/
 *
 * Copyright (c) 2014-2015, Proglang, University of Freiburg.
 * http://proglang.informatik.uni-freiburg.de/treatjs/
 * All rights reserved.
 *
 * Released under the MIT license
 * http://proglang.informatik.uni-freiburg.de/treatjs/license
 *
 * Author Matthias Keil
 * http://www.informatik.uni-freiburg.de/~keilr/
 */

var Effect = (function() {

  // ___  __  __        _
  //| __|/ _|/ _|___ __| |_
  //| _||  _|  _/ -_) _|  _|
  //|___|_| |_| \___\__|\__|

  function Effect(target) {
    if(!(this instanceof Effect)) return new Effect(target);

    Object.defineProperties(this, {
      "date": {
        value: Date.now()
      },
      "target": {
        value: target
      }
    });
  }
  Effect.prototype = {};
  Effect.prototype.toString = function() {
    return "[[DecentJS/Effect]]";
  }

  // ___             _   ___  __  __        _
  //| _ \___ __ _ __| | | __|/ _|/ _|___ __| |_
  //|   / -_) _` / _` | | _||  _|  _/ -_) _|  _|
  //|_|_\___\__,_\__,_| |___|_| |_| \___\__|\__|

  function Read(target) {
    if(!(this instanceof Read)) return new Read(target);
    else Effect.call(this, target);
  }
  Read.prototype = Object.create(Effect.prototype);
  Read.prototype.toString = function() {
    return "[[DecentJS/ReadEffect]]";
  }

  //__      __   _ _         ___  __  __        _
  //\ \    / / _(_) |_ ___  | __|/ _|/ _|___ __| |_
  // \ \/\/ / '_| |  _/ -_) | _||  _|  _/ -_) _|  _|
  //  \_/\_/|_| |_|\__\___| |___|_| |_| \___\__|\__|

  function Write(target) {
    if(!(this instanceof Write)) return new Write(target);
    else Effect.call(this, target);
  }
  Write.prototype = Object.create(Effect.prototype);
  Write.prototype.toString = function() {
    return "[[DecentJS/WriteEffect]]";
  }

  //  ___      _ _   ___  __  __        _
  // / __|__ _| | | | __|/ _|/ _|___ __| |_
  //| (__/ _` | | | | _||  _|  _/ -_) _|  _|
  // \___\__,_|_|_| |___|_| |_| \___\__|\__|

  function Call(target) {
    if(!(this instanceof Call)) return new Call(target);
    else Effect.call(this, target);
  }
  Call.prototype = Object.create(Effect.prototype);
  Call.prototype.toString = function() {
    return "[[TreatJS/CallEffect]]";
  }

  // ___             _   ___  __  __        _
  //| _ \___ __ _ __| | | __|/ _|/ _|___ __| |_ ___
  //|   / -_) _` / _` | | _||  _|  _/ -_) _|  _(_-<
  //|_|_\___\__,_\__,_| |___|_| |_| \___\__|\__/__/

  /** target, name, receiver -> any
  */
  function Get(target, name) {
    if(!(this instanceof Get)) return new Get(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  Get.prototype = Object.create(Read.prototype);
  Get.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"get [name="+this.name+"]";
  }

  /** target, name -> PropertyDescriptor | undefined
  */
  function GetOwnPropertyDescriptor(target, name) {
    if(!(this instanceof GetOwnPropertyDescriptor)) return new GetOwnPropertyDescriptor(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  GetOwnPropertyDescriptor.prototype = Object.create(Read.prototype);
  GetOwnPropertyDescriptor.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"getOwnPropertyDescriptor [name="+this.name+"]";
  }

  /** target -> [String]
  */
  function OwnKeys(target) {
    if(!(this instanceof OwnKeys)) return new OwnKeys(target);
    else Read.call(this, target);
  }
  OwnKeys.prototype = Object.create(Read.prototype);
  OwnKeys.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"getOwnPropertyNames";
  }

  /** target, name -> boolean
  */
  function Has(target, name) {
    if(!(this instanceof Has)) return new Has(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  Has.prototype = Object.create(Read.prototype);
  Has.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"has [name="+this.name+"]";
  }

  /** target, name -> boolean
  */
  function HasOwn(target, name) {
    if(!(this instanceof HasOwn)) return new HasOwn(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  HasOwn.prototype = Object.create(Read.prototype);
  HasOwn.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"hasOwn [name="+this.name+"]";
  }

  /** target -> [String]
  */
  function Enumerate(target) {
    if(!(this instanceof Enumerate)) return new Enumerate(target);
    else Read.call(this, target);
    // TODO
  }
  Enumerate.prototype = Object.create(Read.prototype);
  Enumerate.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"enumerate";
  }

  /** target -> iterator
  */
  function Iterate(target) {
    if(!(this instanceof Iterate)) return new Iterate(target);
    else Read.call(this, target);
    // TODO
  }
  Iterate.prototype = Object.create(Read.prototype);
  Iterate.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"iterate";
  }

  /** target -> [String]
  */
  function Keys(target) {
    if(!(this instanceof Keys)) return new Keys(target);
    else Read.call(this, target);
    // TODO
  }
  Keys.prototype = Object.create(Read.prototype);
  Keys.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"keys";
  }

  /** target -> boolean
   * (not documented)
   */
  function IsExtensible(target) {
    if(!(this instanceof IsExtensible)) return new IsExtensible(target);
    else Read.call(this, target);
    // TODO
  }
  IsExtensible.prototype = Object.create(Read.prototype);
  IsExtensible.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"isExtensible";
  }

  //  ___      _ _   ___  __  __        _
  // / __|__ _| | | | __|/ _|/ _|___ __| |_ ___
  //| (__/ _` | | | | _||  _|  _/ -_) _|  _(_-<
  // \___\__,_|_|_| |___|_| |_| \___\__|\__/__/

  /** target, thisArg, argsArray -> any
  */
  function Apply(target) {
    if(!(this instanceof Apply)) return new Apply(target);
    else Call.call(this, target);
  }
  Apply.prototype = Object.create(Call.prototype);
  Apply.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"apply";
  }

  /** target, thisArg, argsArray -> obejct
  */
  function Construct(target) {
    if(!(this instanceof Construct)) return new Construct(target);
    else Call.call(this, target);
  }
  Construct.prototype = Object.create(Call.prototype);
  Construct.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"construct";
  }

  //__      __   _ _         ___  __  __        _
  //\ \    / / _(_) |_ ___  | __|/ _|/ _|___ __| |_ ___
  // \ \/\/ / '_| |  _/ -_) | _||  _|  _/ -_) _|  _(_-<
  //  \_/\_/|_| |_|\__\___| |___|_| |_| \___\__|\__/__/

  /** target, name, propertyDescriptor -> any
  */
  function Set(target, name) {
    if(!(this instanceof Set)) return new Set(target, name);
    else Write.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  Set.prototype = Object.create(Write.prototype);
  Set.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"set [name="+this.name+"]";
  }

  /** target, name, propertyDescriptor -> any
  */
  function DefineProperty(target, name) {
    if(!(this instanceof DefineProperty)) return new DefineProperty(target, name);
    else Write.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  DefineProperty.prototype = Object.create(Write.prototype);
  DefineProperty.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"defineProperty [name="+this.name+"]";
  }

  /** target, name -> boolean
  */
  function DeleteProperty(target, name) {
    if(!(this instanceof DeleteProperty)) return new DeleteProperty(target, name);
    else Write.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  DeleteProperty.prototype = Object.create(Write.prototype);
  DeleteProperty.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"deleteProperty [name="+this.name+"]";
  }

  /** target -> boolean
  */
  function Freeze(target) {
    if(!(this instanceof Freeze)) return new Freeze(target);
    else Write.call(this, target);
    // TODO
  }
  Freeze.prototype = Object.create(Write.prototype);
  Freeze.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"freeze";
  }

  /** target -> boolean
  */
  function Seal(target) {
    if(!(this instanceof Seal)) return new Seal(target);
    else Write.call(this, target);
    // TODO
  }
  Seal.prototype = Object.create(Write.prototype);
  Seal.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"seal";
  }

  /** target -> boolean
  */
  function PreventExtensions(target) {
    if(!(this instanceof PreventExtensions)) return new PreventExtensions(target);
    else Write.call(this, target);
    // TODO
  }
  PreventExtensions.prototype = Object.create(Write.prototype);
  PreventExtensions.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"preventExtensions";
  }

  //  ___           __ _ _    _
  // / __|___ _ _  / _| (_)__| |_
  //| (__/ _ \ ' \|  _| | / _|  _|
  // \___\___/_||_|_| |_|_\__|\__|

  function Conflict(sbxA, effectA, sbxB, effectB) {
    if(!(this instanceof Conflict)) return new Conflict(sbxA, effectA, sbxB, effectB);

    if(!(sbxA instanceof Sandbox))
      throw new TypeError("No sandbox object.");
    if(!(sbxB instanceof Sandbox))
      throw new TypeError("No sandbox object.");

    if(!(effectA instanceof Effect))
      throw new TypeError("No effect object.");
    if(!(effectB instanceof Effect))
      throw new TypeError("No effect object.");

    Object.defineProperties(this, {
      "sbxA": {
        value: sbxA
      },
      "sbxB": {
        value: sbxB
      },
      "effectA": {
        value: effectA
      },
      "effectB": {
        value: effectB
      }
    });
  }
  Conflict.prototype = {};
  Conflict.prototype.toString = function() {
    return "Confict: "
      + this.effectA.toString() + "@" + this.sbxA.id
      + " - "
      + this.effectB.toString() + "@" + this.sbxB.id;
  }

  // ___  _  __  __
  //|   \(_)/ _|/ _|___ _ _ ___ _ _  __ ___
  //| |) | |  _|  _/ -_) '_/ -_) ' \/ _/ -_)
  //|___/|_|_| |_| \___|_| \___|_||_\__\___|

  function Difference(sbx, effect) {
    if(!(this instanceof Difference)) return new Difference(sbx, effect);

    if(!(sbx instanceof Sandbox))
      throw new TypeError("No sandbox object.");

    if(!(effect instanceof Effect))
      throw new TypeError("No effect object.");

    Object.defineProperties(this, {
      "sbx": {
        value: sbx
      },
      "effect": {
        value: effect
      }
    });
  }
  Difference.prototype = {};
  Difference.prototype.toString = function() {
    return "Difference: "
      + this.effect.toString() + "@" + this.sbx.id;
  };

  //  ___ _
  // / __| |_  __ _ _ _  __ _ ___ ___
  //| (__| ' \/ _` | ' \/ _` / -_|_-<
  // \___|_||_\__,_|_||_\__, \___/__/
  //                    |___/

  function Change(sbx, effect) {
    if(!(this instanceof Change)) return new Change(sbx, effect);

    if(!(sbx instanceof Sandbox))
      throw new TypeError("No sandbox object.");

    if(!(effect instanceof Effect))
      throw new TypeError("No effect object.");

    Object.defineProperties(this, {
      "sbx": {
        value: sbx
      },
      "effect": {
        value: effect
      }
    });
  }
  Change.prototype = {};
  Change.prototype.toString = function() {
    return "Change: "
      + this.effect.toString() + "@" + this.sbx.id;
  };

  // _____                          _   _
  //|_   _| _ __ _ _ _  ___ __ _ __| |_(_)___ _ _
  //  | || '_/ _` | ' \(_-</ _` / _|  _| / _ \ ' \
  //  |_||_| \__,_|_||_/__/\__,_\__|\__|_\___/_||_|

  function Transaction(effects) {
    if(!(this instanceof Transaction)) return new Transaction(effects);

    Object.defineProperties(this, {
      "effects": {
        value: effects
      }
    });

    // TODO
    // Implement differences/ changes/ conflicts ?
    // Or delete

    // TODO
    // add features
    // set of write effects
    //this.effects=effects;
  }
  Transaction.prototype = {};
  Transaction.prototype.toString = function() {
    return "[[DecentJS/Transaction]]";
  };

  // ___  __  __        _
  //| __|/ _|/ _|___ __| |_ ___
  //| _||  _|  _/ -_) _|  _(_-<
  //|___|_| |_| \___\__|\__/__/

  var Effects = new Package("Effect");

  // Core Prototype
  Package.export("Effect", Effect, Effects);

  // Core Effects
  Package.export("Read", Read, Effects);
  Package.export("Write", Write, Effects);
  Package.export("Call", Call, Effects);

  // Read Effects
  Package.export("Get", Get, Effects);
  Package.export("GetOwnPropertyDescriptor", GetOwnPropertyDescriptor, Effects);
  Package.export("OwnKeys", OwnKeys, Effects);
  Package.export("Has", Has, Effects);
  Package.export("HasOwn", HasOwn, Effects);
  Package.export("Enumerate", Enumerate, Effects);
  Package.export("Iterate", Iterate, Effects);
  Package.export("Keys", Keys, Effects);
  Package.export("Apply", Apply, Effects);
  Package.export("Construct", Construct, Effects);
  Package.export("IsExtensible", IsExtensible, Effects);

  // Write Effects
  Package.export("Set", Set, Effects);
  Package.export("DefineProperty", DefineProperty, Effects);
  Package.export("DeleteProperty", DeleteProperty, Effects);
  Package.export("Freeze", Freeze, Effects);
  Package.export("Seal", Seal, Effects);
  Package.export("PreventExtensions", PreventExtensions, Effects);

  // Core Effects
  Package.export("Conflict", Conflict, Effects);
  Package.export("Difference", Difference, Effects);
  Package.export("Change", Change, Effects);

  // Transaction
  Package.export("Transaction", Transaction, Effects);

  return Effects;

})();
<commit_msg>snapshot<commit_after>/*
 * TreatJS: Sandbox
 * http://proglang.informatik.uni-freiburg.de/treatjs/
 *
 * Copyright (c) 2014-2015, Proglang, University of Freiburg.
 * http://proglang.informatik.uni-freiburg.de/treatjs/
 * All rights reserved.
 *
 * Released under the MIT license
 * http://proglang.informatik.uni-freiburg.de/treatjs/license
 *
 * Author Matthias Keil
 * http://www.informatik.uni-freiburg.de/~keilr/
 */

var Effect = (function() {

  // ___  __  __        _
  //| __|/ _|/ _|___ __| |_
  //| _||  _|  _/ -_) _|  _|
  //|___|_| |_| \___\__|\__|

  function Effect(target) {
    if(!(this instanceof Effect)) return new Effect(target);

    Object.defineProperties(this, {
      "date": {
        value: Date.now()
      },
      "target": {
        value: target
      }
    });
  }
  Effect.prototype = {};
  Effect.prototype.toString = function() {
    return "[[DecentJS/Effect]]";
  }

  // ___             _   ___  __  __        _
  //| _ \___ __ _ __| | | __|/ _|/ _|___ __| |_
  //|   / -_) _` / _` | | _||  _|  _/ -_) _|  _|
  //|_|_\___\__,_\__,_| |___|_| |_| \___\__|\__|

  function Read(target) {
    if(!(this instanceof Read)) return new Read(target);
    else Effect.call(this, target);
  }
  Read.prototype = Object.create(Effect.prototype);
  Read.prototype.toString = function() {
    return "[[DecentJS/ReadEffect]]";
  }

  //__      __   _ _         ___  __  __        _
  //\ \    / / _(_) |_ ___  | __|/ _|/ _|___ __| |_
  // \ \/\/ / '_| |  _/ -_) | _||  _|  _/ -_) _|  _|
  //  \_/\_/|_| |_|\__\___| |___|_| |_| \___\__|\__|

  function Write(target) {
    if(!(this instanceof Write)) return new Write(target);
    else Effect.call(this, target);
  }
  Write.prototype = Object.create(Effect.prototype);
  Write.prototype.toString = function() {
    return "[[DecentJS/WriteEffect]]";
  }

  //  ___      _ _   ___  __  __        _
  // / __|__ _| | | | __|/ _|/ _|___ __| |_
  //| (__/ _` | | | | _||  _|  _/ -_) _|  _|
  // \___\__,_|_|_| |___|_| |_| \___\__|\__|

  function Call(target) {
    if(!(this instanceof Call)) return new Call(target);
    else Effect.call(this, target);
  }
  Call.prototype = Object.create(Effect.prototype);
  Call.prototype.toString = function() {
    return "[[TreatJS/CallEffect]]";
  }

  // ___             _   ___  __  __        _
  //| _ \___ __ _ __| | | __|/ _|/ _|___ __| |_ ___
  //|   / -_) _` / _` | | _||  _|  _/ -_) _|  _(_-<
  //|_|_\___\__,_\__,_| |___|_| |_| \___\__|\__/__/

  /**
   * An effect for Object.getPrototypeOf.
   */
  function GetPrototypeOf(target) {
    if(!(this instanceof Get)) return new GetPrototypeOf(target);
    else Read.call(this, target);
  }
  GetPrototypeOf.prototype = Object.create(Read.prototype);
  GetPrototypeOf.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"getPrototypeOf";
  }

  /**
   * An effect for Object.isExtensible
   */
  function IsExtensible(target) {
    if(!(this instanceof IsExtensible)) return new IsExtensible(target);
    else Read.call(this, target);
  }
  IsExtensible.prototype = Object.create(Read.prototype);
  IsExtensible.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"isExtensible";
  }

  /**
   * An effect for Object.getOwnPropertyDescriptor.
   */
  function GetOwnPropertyDescriptor(target, name) {
    if(!(this instanceof GetOwnPropertyDescriptor)) return new GetOwnPropertyDescriptor(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  GetOwnPropertyDescriptor.prototype = Object.create(Read.prototype);
  GetOwnPropertyDescriptor.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"getOwnPropertyDescriptor [name="+this.name+"]";
  }

  /**
   * An effect for the in operator.
   */
  function Has(target, name) {
    if(!(this instanceof Has)) return new Has(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  Has.prototype = Object.create(Read.prototype);
  Has.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"has [name="+this.name+"]";
  }

  /**
   * An effect for getting property values.
   */
  function Get(target, name) {
    if(!(this instanceof Get)) return new Get(target, name);
    else Read.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  Get.prototype = Object.create(Read.prototype);
  Get.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"get [name="+this.name+"]";
  }

  /**
   * An effect for for...in statements.
   */
  function Enumerate(target) {
    if(!(this instanceof Enumerate)) return new Enumerate(target);
    else Read.call(this, target);
  }
  Enumerate.prototype = Object.create(Read.prototype);
  Enumerate.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"enumerate";
  }

  /**
   * An effect for Object.getOwnPropertyNames.
   */
  function OwnKeys(target) {
    if(!(this instanceof OwnKeys)) return new OwnKeys(target);
    else Read.call(this, target);
  }
  OwnKeys.prototype = Object.create(Read.prototype);
  OwnKeys.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"ownKeys";
  }

  //  ___      _ _   ___  __  __        _
  // / __|__ _| | | | __|/ _|/ _|___ __| |_ ___
  //| (__/ _` | | | | _||  _|  _/ -_) _|  _(_-<
  // \___\__,_|_|_| |___|_| |_| \___\__|\__/__/

  /**
   * An effect for a function call.
   */
  function Apply(target) {
    if(!(this instanceof Apply)) return new Apply(target);
    else Call.call(this, target);
  }
  Apply.prototype = Object.create(Call.prototype);
  Apply.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"apply";
  }

  /**
   * An effect for the new operator.
   */
  function Construct(target) {
    if(!(this instanceof Construct)) return new Construct(target);
    else Call.call(this, target);
  }
  Construct.prototype = Object.create(Call.prototype);
  Construct.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"construct";
  }

  //__      __   _ _         ___  __  __        _
  //\ \    / / _(_) |_ ___  | __|/ _|/ _|___ __| |_ ___
  // \ \/\/ / '_| |  _/ -_) | _||  _|  _/ -_) _|  _(_-<
  //  \_/\_/|_| |_|\__\___| |___|_| |_| \___\__|\__/__/

  /**
   * An effect for Object.setPrototypeOf.
   */
  function SetPrototypeOf(target) {
    if(!(this instanceof Get)) return new SetPrototypeOf(target);
    else Write.call(this, target);
  }
  SetPrototypeOf.prototype = Object.create(Write.prototype);
  SetPrototypeOf.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"setPrototypeOf";
  }

  /**
   * An effect for Object.preventExtensions.
   */
  function PreventExtensions(target) {
    if(!(this instanceof PreventExtensions)) return new PreventExtensions(target);
    else Write.call(this, target);
  }
  PreventExtensions.prototype = Object.create(Write.prototype);
  PreventExtensions.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"preventExtensions";
  }

  /**
   * An effect for Object.defineProperty.
   */
  function DefineProperty(target, name) {
    if(!(this instanceof DefineProperty)) return new DefineProperty(target, name);
    else Write.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  DefineProperty.prototype = Object.create(Write.prototype);
  DefineProperty.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"defineProperty [name="+this.name+"]";
  }

  /**
   * An effect for setting property values.
   */
  function Set(target, name) {
    if(!(this instanceof Set)) return new Set(target, name);
    else Write.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  Set.prototype = Object.create(Write.prototype);
  Set.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"set [name="+this.name+"]";
  }

  /**
   * An effect for the delete operator.
   */
  function DeleteProperty(target, name) {
    if(!(this instanceof DeleteProperty)) return new DeleteProperty(target, name);
    else Write.call(this, target);

    Object.defineProperties(this, {
      "name": {
        value: name
      }
    });
  }
  DeleteProperty.prototype = Object.create(Write.prototype);
  DeleteProperty.prototype.toString = function() {
    return "(" + this.date + ")"+" "+"deleteProperty [name="+this.name+"]";
  }

  //  ___           __ _ _    _
  // / __|___ _ _  / _| (_)__| |_
  //| (__/ _ \ ' \|  _| | / _|  _|
  // \___\___/_||_|_| |_|_\__|\__|

  function Conflict(sbxA, effectA, sbxB, effectB) {
    if(!(this instanceof Conflict)) return new Conflict(sbxA, effectA, sbxB, effectB);

    if(!(sbxA instanceof Sandbox))
      throw new TypeError("No sandbox object.");
    if(!(sbxB instanceof Sandbox))
      throw new TypeError("No sandbox object.");

    if(!(effectA instanceof Effect))
      throw new TypeError("No effect object.");
    if(!(effectB instanceof Effect))
      throw new TypeError("No effect object.");

    Object.defineProperties(this, {
      "sbxA": {
        value: sbxA
      },
      "sbxB": {
        value: sbxB
      },
      "effectA": {
        value: effectA
      },
      "effectB": {
        value: effectB
      }
    });
  }
  Conflict.prototype = {};
  Conflict.prototype.toString = function() {
    return "Confict: "
      + this.effectA.toString() + "@" + this.sbxA.id
      + " - "
      + this.effectB.toString() + "@" + this.sbxB.id;
  }

  // ___  _  __  __
  //|   \(_)/ _|/ _|___ _ _ ___ _ _  __ ___
  //| |) | |  _|  _/ -_) '_/ -_) ' \/ _/ -_)
  //|___/|_|_| |_| \___|_| \___|_||_\__\___|

  function Difference(sbx, effect) {
    if(!(this instanceof Difference)) return new Difference(sbx, effect);

    if(!(sbx instanceof Sandbox))
      throw new TypeError("No sandbox object.");

    if(!(effect instanceof Effect))
      throw new TypeError("No effect object.");

    Object.defineProperties(this, {
      "sbx": {
        value: sbx
      },
      "effect": {
        value: effect
      }
    });
  }
  Difference.prototype = {};
  Difference.prototype.toString = function() {
    return "Difference: "
      + this.effect.toString() + "@" + this.sbx.id;
  };

  //  ___ _
  // / __| |_  __ _ _ _  __ _ ___ ___
  //| (__| ' \/ _` | ' \/ _` / -_|_-<
  // \___|_||_\__,_|_||_\__, \___/__/
  //                    |___/

  function Change(sbx, effect) {
    if(!(this instanceof Change)) return new Change(sbx, effect);

    if(!(sbx instanceof Sandbox))
      throw new TypeError("No sandbox object.");

    if(!(effect instanceof Effect))
      throw new TypeError("No effect object.");

    Object.defineProperties(this, {
      "sbx": {
        value: sbx
      },
      "effect": {
        value: effect
      }
    });
  }
  Change.prototype = {};
  Change.prototype.toString = function() {
    return "Change: "
      + this.effect.toString() + "@" + this.sbx.id;
  };

  // _____                          _   _
  //|_   _| _ __ _ _ _  ___ __ _ __| |_(_)___ _ _
  //  | || '_/ _` | ' \(_-</ _` / _|  _| / _ \ ' \
  //  |_||_| \__,_|_||_/__/\__,_\__|\__|_\___/_||_|

  function Transaction(effects) {
    if(!(this instanceof Transaction)) return new Transaction(effects);

    Object.defineProperties(this, {
      "effects": {
        value: effects
      }
    });

    // TODO
    // Implement differences/ changes/ conflicts ?
    // Or delete

    // TODO
    // add features
    // set of write effects
    //this.effects=effects;
  }
  Transaction.prototype = {};
  Transaction.prototype.toString = function() {
    return "[[DecentJS/Transaction]]";
  };

  // ___  __  __        _
  //| __|/ _|/ _|___ __| |_ ___
  //| _||  _|  _/ -_) _|  _(_-<
  //|___|_| |_| \___\__|\__/__/

  var Effects = new Package("Effect");

  // Core Effects
  Package.export("Effect", Effect, Effects);
  Package.export("Read", Read, Effects);
  Package.export("Write", Write, Effects);
  Package.export("Call", Call, Effects);

  // Effects
  Package.export("GetPrototypeOf", GetPrototypeOf, Effects);
  Package.export("SetPrototypeOf", SetPrototypeOf, Effects);
  Package.export("IsExtensible", IsExtensible, Effects);
  Package.export("PreventExtensions", PreventExtensions, Effects);
  Package.export("GetOwnPropertyDescriptor", GetOwnPropertyDescriptor, Effects);
  Package.export("DefineProperty", DefineProperty, Effects);
  Package.export("Has", Has, Effects);
  Package.export("Get", Get, Effects);
  Package.export("Set", Set, Effects);
  Package.export("DeleteProperty", DeleteProperty, Effects);
  Package.export("Enumerate", Enumerate, Effects);
  Package.export("OwnKeys", OwnKeys, Effects);
  Package.export("Apply", Apply, Effects);
  Package.export("Construct", Construct, Effects);

  // Core Elements
  Package.export("Conflict", Conflict, Effects);
  Package.export("Difference", Difference, Effects);
  Package.export("Change", Change, Effects);

  // Transaction
  Package.export("Transaction", Transaction, Effects);

  return Effects;

})();
<|endoftext|>


<commit_before>(function() {
  "use strict";

  App.register('component').enter(function() {
    console.warn("Loaded Vue")
    console.warn(App.vue);

    App.vue.currentPage = new Vue({
      mixins: [App.vue.interfaces.contentFormatters],
      el: "body",
      data: function() {
        return {
          pageLoadedClass: "vue-page-loaded"
        }
      },
      methods: {
        numeral: numeral,
        moment: moment
      }
    })
  }).exit(function() {
    App.vue.currentPage = null;
  });
})();
<commit_msg>Update vue_pages.js<commit_after>(function() {
  "use strict";

  App.register('component').enter(function() {

    // Insert the customizable global interface
    if (App.vue.interfaces.custom === undefined) {
      App.vue.interfaces.custom = {
        methods: {}
      };
    }

    var components = App.vue.extend;

    console.warn("Loaded Vue")
    console.warn(App.vue);

    App.vue.root = new Vue({
      mixins: [App.vue.interfaces.contentFormatters, App.vue.interfaces.custom],
      el: "body",
      components: components,
      data: function() {
        return {
          pageLoadedClass: "vue-page-loaded"
        }
      },
      methods: {
        numeral: numeral,
        moment: moment
      }
    })
  }).exit(function() {
    App.vue.extend = {};
    App.vue.root = null;
  });
})();
<|endoftext|>


<commit_before>module.exports = {
    pages: {
        index: {
            entry: "src/main.js",
            template: "public/index.html",
            filename: "index.html"
        }
    },
    filenameHashing: false,
    css: {
        loaderOptions: {
            postcss: {
                plugins: [require("postcss-preset-env")()]
            }
        }
    },
    chainWebpack: config => {
        config.resolve.alias.set("@inkline/inkline", __dirname).end();

        // config
        //     .plugin("webpack-bundle-analyzer")
        //     .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
        //     .init(Plugin => new Plugin({
        //         analyzerMode: 'static'
        //     }));
    },
    lintOnSave: true,
    pluginOptions: {
        lintStyleOnBuild: true,
        stylelint: {
            fix: false,
            files: ['src/**/*.{css,scss}'],
            syntax: 'scss'
        }
    }
};
<commit_msg>Added back bundle optimization changes.<commit_after>module.exports = {
    pages: {
        index: {
            entry: "src/main.js",
            template: "public/index.html",
            filename: "index.html"
        }
    },
    filenameHashing: false,
    css: {
        loaderOptions: {
            postcss: {
                plugins: [require("postcss-preset-env")()]
            }
        }
    },
    chainWebpack: config => {
        config.optimization.delete("splitChunks");
        config.optimization.removeAvailableModules(false);
        config.optimization.concatenateModules(false);
        config.optimization.providedExports(false);
        config.optimization.usedExports(false);

        config.resolve.alias.set("@inkline/inkline", __dirname).end();

        // config
        //     .plugin("webpack-bundle-analyzer")
        //     .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
        //     .init(Plugin => new Plugin({
        //         analyzerMode: 'static'
        //     }));
    },
    lintOnSave: true,
    pluginOptions: {
        lintStyleOnBuild: true,
        stylelint: {
            fix: false,
            files: ['src/**/*.{css,scss}'],
            syntax: 'scss'
        }
    }
};
<|endoftext|>


<commit_before>/*
 * Please see the included README.md file for license terms and conditions.
 */

// This file is a suggested starting place for your code.
// It is completely optional and not required.
// Note the reference that includes it in the index.html file.

/*jslint browser:true, devel:true, white:true, vars:true */
/*global $:false, intel:false app:false, dev:false, cordova:false */

// This file contains your event handlers, the center of your application.
// NOTE: see app.initEvents() in init-app.js for event handler initialization code.

// function myEventHandler() {
//     "use strict" ;
// // ...event handler code here...
// }

// ...additional event handlers here...

//variaveis globais
var papel;

//id da propriedade
//var idpropriedade = 4;

//ip do servidor
//var ipServidor = "192.168.0.3";
var ipServidor = "10.2.10.200";
//var ipServidor = "localhost";

/*/funcao mudar background aleatorio
function mudarBackground(){
    switch(Math.floor((Math.random() * 5) + 1)){
        case 1:{
            $(".backgroundInicial").css("background-image", 'url("images/background1.jpg")');
        }break;
        case 2:{
            $(".backgroundInicial").css("background-image", 'url("images/background2.jpg")');
        }break;
        case 3:{
            $(".backgroundInicial").css("background-image", 'url("images/background3.jpg")');
        }break;
        case 4:{
            $(".backgroundInicial").css("background-image", 'url("images/background4.jpg")');
        }break;
        case 5:{
            $(".backgroundInicial").css("background-image", 'url("images/background5.jpg")');
        }break;

    }
}*/

//verifica se existe sessao na localStorage
//inicia pela ultima sessao ou abre tela de login
function verificaSession(){

    try{
        if(localStorage.getItem("logSession")){
            verificarDataLogin();
        }else{
            //limpa o localstorage e inicia o app da pagina de login
            localStorage.clear();
            window.activate_page("#mainpage");
        }
    }catch(e){
        window.alert("Erro verificaSession: " + e.message);
        clearGoMainPage();
    }
}

//funcao para verificar a data referente ao ultimo acesso, se estiver mais de 7 dias sem se conectar redireciona para login
function verificarDataLogin(){

    try{
        var data = new Date(),
            dia = data.getDate(),
            mes = data.getMonth() + 1;
        //teste os dias logado com ultimo login armazenado no localStorage
        if((730 * mes) - (730 - (dia*24)) > JSON.parse(localStorage.getItem("logSession")).logTempo){
            //alerta, redireciona para pagina login e limpa a localStorage
            navigator.notification.alert("Por motivos de segurança pedimos que faça o login novamente!",function(){},"Alerta","OK");
            clearGoMainPage();
        //o app foi aberto antes de 7 dias, entao carrega informacoes da localStorage
        }else{
            papel = JSON.parse(localStorage.getItem("logSession")).papel;
            carregaDados();
        }
    }catch(e){
        window.alert("Erro verificarDataLogin: "+ e.message);
        clearGoMainPage();
    }
}

//carrega os dados de cada usuario
function carregaDados(){
    try{
        if(papel === "a"){
            //usuario agricultor
            window.activate_page("#page_3");
            listarPropriedades();
        }else if(papel === "g" || papel === "e" || papel === "d"){
            //usuario gerenciador e entrevistador
            window.activate_page("#page_4");
            listarCultivar();
        }else{
            clearGoMainPage();
        }
    }catch(e){
        window.alert("Erro carregaDados: "+ e.message);
        clearGoMainPage();
    }

}

//lista os cultivares recebidos contidos no localStorage de cada propriedade
function listarCultivarRecebidos(idpropriedade){
    try{

        $("#cultivarRecebido").empty();
        var cultivaresRecebidos = JSON.parse(localStorage.getItem("cultivaresRecebidos"));

        //se nao conter os dados redireciona para acesso no servidor, armazena na localStorage e depois chama novamente o metotodo listarCultivarRecebidos
        if(cultivaresRecebidos === null){
            clearGoMainPage();
        //acessa o localStorge e cria a lista
        }else{
            var i = 0;
            //percore o tamanho do cultivares recebidos e cria um novo item
            $.each(cultivaresRecebidos, function(){
                var a = cultivaresRecebidos[i];
                //teste a propriedade
                if(a.propriedade_idpropriedade === idpropriedade){
                    var item =''+ cultivarRelatado(a.descricaostatus)+'
'+ a.nomecultivar +'

Safra: '+ a.safra +'

Quantidade recebida: '+ a.qtdrecebida +'&nbsp'+ a.grandeza_safra +'

data recebimento: '+a.datareceb+'

Status da colheita: '+a.descricaostatus+'

Status de destinação: '+a.descricaostatus+'
';
                    $("#cultivarRecebido").append(item);
                }
                i++;
            });
        }
    }catch(e){
        window.alert("Erro listarCultivarRecebidos: "+ e.message);
        clearGoMainPage();
    }
}

//servico de busca dos dados no servidor, consome dados de internet e armazena no localStorage
function servArmazenarCulRecebdo(usuario){
    var cultivaresRecebidos = [];
    var propriedades = [];
    var cultivares = [];

    $.post("http://"+window.ipServidor+":8080/Projeto_BioID-war/servico/cultivar/listarrecebidos", usuario, function(dados){
        //armazena no localStorge
        if(dados.sucesso){
            var i = 0;
            $.each(dados.data, function(){
                //armazena os cultivares em um array
                cultivaresRecebidos[i] = {nomecultivar: dados.data[i].nomecultivar, qtdrecebida: dados.data[i].qtdrecebida, safra: dados.data[i].safra, nomepropriedade: dados.data[i].nomepropriedade, grandeza_safra: dados.data[i].grandeza_safra, descricaostatus: dados.data[i].descricaostatus, datareceb: dados.data[i].datareceb};
                //armazena a propriedade em um array
                if(propriedades.length < 1){
                    propriedades[0] = {propriedade_idpropriedade: cultivaresRecebidos[i].propriedade_idpropriedade, nomepropriedade: cultivaresRecebidos[i].nomepropriedade};
                }else if(propriedades[propriedades.length - 1].nomepropriedade != cultivaresRecebidos[i].nomepropriedade){
                    propriedades[propriedades.length] = {propriedade_idpropriedade: cultivaresRecebidos[i].propriedade_idpropriedade, nomepropriedade: cultivaresRecebidos[i].nomepropriedade};
                }
                //salvar imagem
                //imagens[i] = dados.i

                i++;
            });

            //armazena as imagens dos cultivares em um array
            cultivares = dados.cultivares;
        }
    }, "json")
    //Tratamento de erro da requisicao servico RESt login
    .fail(function(){
        navigator.notification.confirm(
            'Sem conexão com o servidor!',
            function() {
                clearGoMainPage();
            },
            'Erro',
            ['OK']
        );
    })
    .done(function(){
        //armazena no localstorage
        localStorage.setItem("cultivaresRecebidos", JSON.stringify(cultivaresRecebidos));
        //armazena propriedades no localstorage
        localStorage.setItem("propriedades", JSON.stringify(propriedades));
        //armazena imagens no localstorage
        localStorage.setItem("cultivares", JSON.stringify(cultivares));
        //chama o metodo que popula o item de propriedades
        listarPropriedades();

    });

}

//funcao que organiza e lista as propriedades
function listarPropriedades(){
    var item;
    $("#itemPropriedades").empty();
    var propriedades = JSON.parse(localStorage.getItem("propriedades"));
    if(propriedades.length > 0){
        var i = 0;
        $.each(propriedades, function(){
            item = '
'+propriedades[i].nomepropriedade+'
';

            $("#itemPropriedades").append(item);

            i++;
        });

        //marca o ultima propriedade como ativa
        $('#propriedade'+ (i-1)).addClass("active");
        //chama a funcao de listar cultivares recebidos
        listarCultivarRecebidos(propriedades[i-1].propriedade_idpropriedade);

    }else{
        $("#cultivarRecebido").empty();

        item = '
Atualizar lista

data recebimento/quantidade
';

        $("#cultivarRecebido").append(item);

        navigator.notification.alert("Nenhum cultivar foi recebido!",function(){},"Alerta","OK");
    }
}
function listarCultivar(){
    $("#cultivarUnidade").empty();

    $.get("http://"+window.ipServidor+":8080/Projeto_BioID-war/servico/cultivar/listar", function(dados){
        var a = dados.data;
        var qnt = a.length;
        for(var i=0; i<qnt; i++){
            var item ='
'+ a[i].nomecultivar +'

500 kilos
';

            $("#cultivarUnidade").append(item);
        }

    }, "json");

}

function cultivarRelatado(teste){
    if(teste === 'relatada'){
        return ' ';

    }else if(teste === 'expirada'){
        return ' ';

    }else{
        return ' ';

    }

}

//limpa a memoria do app e redireciona para tela de login
function clearGoMainPage(){
    window.activate_page("#mainpage");
    localStorage.clear();
}
<commit_msg>modificacao do ip<commit_after>/*
 * Please see the included README.md file for license terms and conditions.
 */

// This file is a suggested starting place for your code.
// It is completely optional and not required.
// Note the reference that includes it in the index.html file.

/*jslint browser:true, devel:true, white:true, vars:true */
/*global $:false, intel:false app:false, dev:false, cordova:false */

// This file contains your event handlers, the center of your application.
// NOTE: see app.initEvents() in init-app.js for event handler initialization code.

// function myEventHandler() {
//     "use strict" ;
// // ...event handler code here...
// }

// ...additional event handlers here...

//variaveis globais
var papel;

//id da propriedade
//var idpropriedade = 4;

//ip do servidor
//var ipServidor = "192.168.0.3";
var ipServidor = "10.2.10.225";
//var ipServidor = "localhost";

/*/funcao mudar background aleatorio
function mudarBackground(){
    switch(Math.floor((Math.random() * 5) + 1)){
        case 1:{
            $(".backgroundInicial").css("background-image", 'url("images/background1.jpg")');
        }break;
        case 2:{
            $(".backgroundInicial").css("background-image", 'url("images/background2.jpg")');
        }break;
        case 3:{
            $(".backgroundInicial").css("background-image", 'url("images/background3.jpg")');
        }break;
        case 4:{
            $(".backgroundInicial").css("background-image", 'url("images/background4.jpg")');
        }break;
        case 5:{
            $(".backgroundInicial").css("background-image", 'url("images/background5.jpg")');
        }break;

    }
}*/

//verifica se existe sessao na localStorage
//inicia pela ultima sessao ou abre tela de login
function verificaSession(){

    try{
        if(localStorage.getItem("logSession")){
            verificarDataLogin();
        }else{
            //limpa o localstorage e inicia o app da pagina de login
            localStorage.clear();
            window.activate_page("#mainpage");
        }
    }catch(e){
        window.alert("Erro verificaSession: " + e.message);
        clearGoMainPage();
    }
}

//funcao para verificar a data referente ao ultimo acesso, se estiver mais de 7 dias sem se conectar redireciona para login
function verificarDataLogin(){

    try{
        var data = new Date(),
            dia = data.getDate(),
            mes = data.getMonth() + 1;
        //teste os dias logado com ultimo login armazenado no localStorage
        if((730 * mes) - (730 - (dia*24)) > JSON.parse(localStorage.getItem("logSession")).logTempo){
            //alerta, redireciona para pagina login e limpa a localStorage
            navigator.notification.alert("Por motivos de segurança pedimos que faça o login novamente!",function(){},"Alerta","OK");
            clearGoMainPage();
        //o app foi aberto antes de 7 dias, entao carrega informacoes da localStorage
        }else{
            papel = JSON.parse(localStorage.getItem("logSession")).papel;
            carregaDados();
        }
    }catch(e){
        window.alert("Erro verificarDataLogin: "+ e.message);
        clearGoMainPage();
    }
}

//carrega os dados de cada usuario
function carregaDados(){
    try{
        if(papel === "a"){
            //usuario agricultor
            window.activate_page("#page_3");
            listarPropriedades();
        }else if(papel === "g" || papel === "e" || papel === "d"){
            //usuario gerenciador e entrevistador
            window.activate_page("#page_4");
            listarCultivar();
        }else{
            clearGoMainPage();
        }
    }catch(e){
        window.alert("Erro carregaDados: "+ e.message);
        clearGoMainPage();
    }

}

//lista os cultivares recebidos contidos no localStorage de cada propriedade
function listarCultivarRecebidos(idpropriedade){
    try{

        $("#cultivarRecebido").empty();
        var cultivaresRecebidos = JSON.parse(localStorage.getItem("cultivaresRecebidos"));

        //se nao conter os dados redireciona para acesso no servidor, armazena na localStorage e depois chama novamente o metotodo listarCultivarRecebidos
        if(cultivaresRecebidos === null){
            clearGoMainPage();
        //acessa o localStorge e cria a lista
        }else{
            var i = 0;
            //percore o tamanho do cultivares recebidos e cria um novo item
            $.each(cultivaresRecebidos, function(){
                var a = cultivaresRecebidos[i];
                //teste a propriedade
                if(a.propriedade_idpropriedade === idpropriedade){
                    var item =''+ prazoRelatar(a.prazo_destinacao)+'
'+ a.nomecultivar +'

Safra: '+ a.safra +'

data recebimento: '+a.datareceb+'

Quantidade recebida: '+ a.qtdrecebida +'&nbsp'+ a.grandeza_safra +'

Quantidade colhida: '+a.qtdcolhida+'

Status da colheita: '+a.prazo_colheita+'

Quantidade destinada: '+a.qtddestinada+'

Status de destinação: '+a.prazo_destinacao+'
';
                    $("#cultivarRecebido").append(item);
                }
                i++;
            });
        }
    }catch(e){
        window.alert("Erro listarCultivarRecebidos: "+ e.message);
        clearGoMainPage();
    }
}

//servico de busca dos dados no servidor, consome dados de internet e armazena no localStorage
function servArmazenarCulRecebdo(usuario){
    var cultivaresRecebidos = [];
    var propriedades = [];
    var cultivares = [];

    $.post("http://"+window.ipServidor+":8080/Projeto_BioID-war/servico/cultivar/listarrecebidos", usuario, function(dados){
        //armazena no localStorge
        if(dados.sucesso){
            var i = 0;
            $.each(dados.data, function(){
                //armazena os cultivares em um array
                cultivaresRecebidos[i] = {nomepropriedade: dados.data[i].nomepropriedade, safra: dados.data[i].safra, nomecultivar: dados.data[i].nomecultivar, datareceb: dados.data[i].datareceb, qtdrecebida: dados.data[i].qtdrecebida, grandeza_safra: dados.data[i].grandeza_safra, qtdcolhida: dados.data[i].qtdcolhida, prazo_colheita: dados.data[i].prazo_colheita, qtddestinada: dados.data[i].qtddestinada, prazo_destinacao: dados.data[i].prazo_destinacao};
                //armazena a propriedade em um array
                if(propriedades.length < 1){
                    propriedades[0] = {propriedade_idpropriedade: cultivaresRecebidos[i].propriedade_idpropriedade, nomepropriedade: cultivaresRecebidos[i].nomepropriedade};
                }else if(propriedades[propriedades.length - 1].nomepropriedade != cultivaresRecebidos[i].nomepropriedade){
                    propriedades[propriedades.length] = {propriedade_idpropriedade: cultivaresRecebidos[i].propriedade_idpropriedade, nomepropriedade: cultivaresRecebidos[i].nomepropriedade};
                }
                //salvar imagem
                //imagens[i] = dados.i

                i++;
            });

            //armazena as imagens dos cultivares em um array
            cultivares = dados.cultivares;
        }
    }, "json")
    //Tratamento de erro da requisicao servico RESt login
    .fail(function(){
        navigator.notification.confirm(
            'Sem conexão com o servidor!',
            function() {
                clearGoMainPage();
            },
            'Erro',
            ['OK']
        );
    })
    .done(function(){
        //armazena no localstorage
        localStorage.setItem("cultivaresRecebidos", JSON.stringify(cultivaresRecebidos));
        //armazena propriedades no localstorage
        localStorage.setItem("propriedades", JSON.stringify(propriedades));
        //armazena imagens no localstorage
        localStorage.setItem("cultivares", JSON.stringify(cultivares));
        //chama o metodo que popula o item de propriedades
        listarPropriedades();

    });

}

//funcao que organiza e lista as propriedades
function listarPropriedades(){
    var item;
    $("#itemPropriedades").empty();
    var propriedades = JSON.parse(localStorage.getItem("propriedades"));
    if(propriedades.length > 0){
        var i = 0;
        $.each(propriedades, function(){
            item = '
'+propriedades[i].nomepropriedade+'
';

            $("#itemPropriedades").append(item);

            i++;
        });

        //marca o ultima propriedade como ativa
        $('#propriedade'+ (i-1)).addClass("active");
        //chama a funcao de listar cultivares recebidos
        listarCultivarRecebidos(propriedades[i-1].propriedade_idpropriedade);

    }else{
        $("#cultivarRecebido").empty();

        item = '
Atualizar lista

data recebimento/quantidade
';

        $("#cultivarRecebido").append(item);

        navigator.notification.alert("Nenhum cultivar foi recebido!",function(){},"Alerta","OK");
    }
}
function listarCultivar(){
    $("#cultivarUnidade").empty();

    $.get("http://"+window.ipServidor+":8080/Projeto_BioID-war/servico/cultivar/listar", function(dados){
        var a = dados.data;
        var qnt = a.length;
        for(var i=0; i<qnt; i++){
            var item ='
'+ a[i].nomecultivar +'

500 kilos
';

            $("#cultivarUnidade").append(item);
        }

    }, "json");

}

function prazoRelatar(teste){
    if(teste === 'relatada'){
        return ' ';

    }else if(teste === 'expirada'){
        return ' ';

    }else{
        return ' ';

    }

}

//limpa a memoria do app e redireciona para tela de login
function clearGoMainPage(){
    window.activate_page("#mainpage");
    localStorage.clear();
}
<|endoftext|>


<commit_before>angular.module('barter')
  .controller('WelcomeController', ['$routeParams', "UserService", "TalentService", function($routeParams, UserService, TalentService ){
    this.tals = [];
    this.persons = [];
    this.selectedCategory = 'Art & Music';

     UserService.query(function(data) {
      this.persons = data;
     }.bind(this));

     TalentService.query(function(data) {
      this.tals = data;
     }.bind(this));

     this.filterFunction = function(array, key){
       for(var i = 0; i < array.length; i++){
         if (array[i].type === key){
           return true
         }
       };
      return false;
     };

     // var rep = function(persons) {
     //  for(var i = 0; i < persons.length; i++){
     //    persons[i].reputation =
     //  }
     // };
     this.myVar = false;
     this.toggle = function() {
        this.myVar = true;
     };
     this.clear = function() {
        this.myVar = false;
     };

}]);
angular.module('barter')
.controller('UsersController', ['$http', '$routeParams', 'UserService', "TalentService", "OfferService", function($http, $routeParams, UserService, TalentService, OfferService){

  this.categories = ["Art & Music", "Sports", "Fitness & Nutrition", "Cooking & Baking", "Computers & Electronics", "Education & Careers", "Home Improvement"];
  this.hours = ["08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00"]
  this.days = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday"]
  this.experiences = ["Novice", "Intermediate", "Expert"];
  this.ratings = [1, 2, 3, 4, 5];

  this.loadUserGraph = function() {
     UserService.get({id: $routeParams.id}, function(data){
       this.user = data;
       this.talent = {user_id: this.user.id}
       this.user.reputation = {user_id: this.user.id};
     }.bind(this));
   }

   this.loadUserGraph();

  this.saveUser = function(user) {
    UserService.update(user);
  };

  this.updateTalent = function(talent) {
    var that = this;
    $http.put('/talents/' + talent.id, talent)
    .success(function(response){
      that.loadUserGraph();
    });
  };

  this.saveRating = function(){
    $http.post('/reputations', this.user.reputation);
    this.loadUserGraph();
  };

  this.saveTalent = function(){
    $http.post('/talents', this.talent);
    this.loadUserGraph();
  };

  this.toggleTalentShown = function(talent) {
    talent.isShown = ! talent.isShown;
  };

  this.loadTalentsForUser = function(user) {
    $http.get('/talents/for_user/' + user.id).
     success(function(data, status, headers, config) {
      this.talents = data;
    });
  };

  this.acceptOffer = function(offer) {
    var that = this;
    offer.status = true;
    $http.put('/offers/' + offer.id, offer)
    .success(function(data, status){
      that.loadUserGraph();
    });
  };

  this.declineOffer = function(offer) {
    var that = this;
    $http.delete('/offers/' + offer.id, offer)
    .success(function(response){
      that.loadUserGraph();
    }).error(function(response){
    });
  };

  function insertOffer(newOffer, user) {
    var slots = user.timeslots;
    slots.forEach(function(slot) {
      if (slot.id === newOffer.timeslot_id) {
        slot.offers.push(newOffer);
      }
    })
  }

  function removeOffer(offer, user) {
    var slots = user.timeslots;
    slots.forEach(function(slot) {
      if (slot.id === offer.timeslot_id) {
        var index = slot.offers.indexOf(offer);
        if (index > -1) {
            slot.offers.splice(index, 1);
        }
      }
    });
  }

  this.deleteTimeslot = function(timeslot) {
    var that = this;
    $http.delete('/timeslots/' + timeslot.id, timeslot)
    .success(function(response){
       that.loadUserGraph();
    });
  }

  this.createTimeslot = function(day, hour) {
    var that = this;
    var dayHour = {
      day: day,
      hour: hour
    };
    console.log(dayHour);
    $http.post('/timeslots', dayHour)
    .success(function(response){
      console.log("in success");
      console.log(response);
       that.loadUserGraph();
    }).error(function(response){
      console.log("in error");
    });
  }

  this.creeTimeslot = function(day) {
    var dayHour = {
      day: this.user.timeslot.day,
      hour: this.user.timeslot.hour
    }
    var that = this;
    $http.post("/timeslots", dayHour)
    .success(function(response){
      console.log("in success!");
      that.loadUserGraph();
    }).error(function(response){
      console.log("in error!");
    });
  }

  this.createOffer = function(timeslot) {
    var that = this;
    $http.post('/offers', timeslot)
    .success(function(response){
      var newOffer = response;
      insertOffer(newOffer, that.user);
    }).error(function(response){
      console.log("not in success but getting there!!!");
    });
  };

  this.isClosed = function(timeslot) {
     for( var i = 0; i < timeslot.offers.length; i++) {
        if (timeslot.offers[i].status === true) {
          return true;
        }
     }
  };

}]);

angular.module('barter').controller('TimeslotsController', ['UserService', function(UserService){

   UserService.get({id:4}, function(jsonResponse) {
     this.user = jsonResponse;
   }.bind(this));
}]);
<commit_msg>edit create offer functionality<commit_after>angular.module('barter')
  .controller('WelcomeController', ['$routeParams', "UserService", "TalentService", function($routeParams, UserService, TalentService ){
    this.tals = [];
    this.persons = [];
    this.selectedCategory = 'Art & Music';

     UserService.query(function(data) {
      this.persons = data;
     }.bind(this));

     TalentService.query(function(data) {
      this.tals = data;
     }.bind(this));

     this.filterFunction = function(array, key){
       for(var i = 0; i < array.length; i++){
         if (array[i].type === key){
           return true
         }
       };
      return false;
     };

     // var rep = function(persons) {
     //  for(var i = 0; i < persons.length; i++){
     //    persons[i].reputation =
     //  }
     // };
     this.myVar = false;
     this.toggle = function() {
        this.myVar = true;
     };
     this.clear = function() {
        this.myVar = false;
     };

}]);
angular.module('barter')
.controller('UsersController', ['$http', '$routeParams', 'UserService', "TalentService", "OfferService", function($http, $routeParams, UserService, TalentService, OfferService){

  this.categories = ["Art & Music", "Sports", "Fitness & Nutrition", "Cooking & Baking", "Computers & Electronics", "Education & Careers", "Home Improvement"];
  this.hours = ["08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00"]
  this.days = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday"]
  this.experiences = ["Novice", "Intermediate", "Expert"];
  this.ratings = [1, 2, 3, 4, 5];

  this.loadUserGraph = function() {
     UserService.get({id: $routeParams.id}, function(data){
       this.user = data;
       this.talent = {user_id: this.user.id}
       this.user.reputation = {user_id: this.user.id};
     }.bind(this));
   }

   this.loadUserGraph();

  this.saveUser = function(user) {
    UserService.update(user);
  };

  this.updateTalent = function(talent) {
    var that = this;
    $http.put('/talents/' + talent.id, talent)
    .success(function(response){
      that.loadUserGraph();
    });
  };

  this.saveRating = function(){
    $http.post('/reputations', this.user.reputation);
    this.loadUserGraph();
  };

  this.saveTalent = function(){
    $http.post('/talents', this.talent);
    this.loadUserGraph();
  };

  this.toggleTalentShown = function(talent) {
    talent.isShown = ! talent.isShown;
  };

  this.loadTalentsForUser = function(user) {
    $http.get('/talents/for_user/' + user.id).
     success(function(data, status, headers, config) {
      this.talents = data;
    });
  };

  this.acceptOffer = function(offer) {
    var that = this;
    offer.status = true;
    $http.put('/offers/' + offer.id, offer)
    .success(function(data, status){
      that.loadUserGraph();
    });
  };

  this.declineOffer = function(offer) {
    var that = this;
    $http.delete('/offers/' + offer.id, offer)
    .success(function(response){
      that.loadUserGraph();
    }).error(function(response){
    });
  };

  function insertOffer(newOffer, user) {
    var slots = user.timeslots;
    slots.forEach(function(slot) {
      if (slot.id === newOffer.timeslot_id) {
        slot.offers.push(newOffer);
      }
    })
  }

  function removeOffer(offer, user) {
    var slots = user.timeslots;
    slots.forEach(function(slot) {
      if (slot.id === offer.timeslot_id) {
        var index = slot.offers.indexOf(offer);
        if (index > -1) {
            slot.offers.splice(index, 1);
        }
      }
    });
  }

  this.deleteTimeslot = function(timeslot) {
    var that = this;
    $http.delete('/timeslots/' + timeslot.id, timeslot)
    .success(function(response){
       that.loadUserGraph();
    });
  }

  this.createTimeslot = function(day, hour) {
    var that = this;
    var dayHour = {
      day: day,
      hour: hour
    };
    console.log(dayHour);
    $http.post('/timeslots', dayHour)
    .success(function(response){
      console.log("in success");
      console.log(response);
       that.loadUserGraph();
    }).error(function(response){
      console.log("in error");
    });
  }

  this.creeTimeslot = function(day) {
    var dayHour = {
      day: this.user.timeslot.day,
      hour: this.user.timeslot.hour
    }
    var that = this;
    $http.post("/timeslots", dayHour)
    .success(function(response){
      console.log("in success!");
      that.loadUserGraph();
    }).error(function(response){
      console.log("in error!");
    });
  }

  this.createOffer = function(timeslot) {
    var that = this;
    $http.post('/offers', timeslot)
    .success(function(response){
      var newOffer = response;
      insertOffer(newOffer, that.user);
      that.loadUserGraph();
    }).error(function(response){
      console.log("not in success but getting there!!!");
    });
  };

  this.isClosed = function(timeslot) {
     for( var i = 0; i < timeslot.offers.length; i++) {
        if (timeslot.offers[i].status === true) {
          return true;
        }
     }
  };

}]);

angular.module('barter').controller('TimeslotsController', ['UserService', function(UserService){

   UserService.get({id:4}, function(jsonResponse) {
     this.user = jsonResponse;
   }.bind(this));
}]);
<|endoftext|>


<commit_before>(function(){
  'use strict';

  angular.module('cla.controllers')
    .controller('DiagnosisCtrl',
      ['$scope', 'Category', 'postal', 'eligibility_check',
        function($scope, Category, postal, eligibility_check) {
          // updates the state of case.diagnosis_state after each save
          function saveCallback(data) {
            $scope.case.diagnosis_state = data.state;

            if (!$scope.diagnosis.isInScopeUnknown()) {
              // refreshing the logs
              postal.publish({
                channel : 'models',
                topic   : 'Log.refresh'
              });
            }
          }

          // creates a new diagnosis
          $scope.createDiagnosis = function () {
            if (!$scope.case.diagnosis) {
              // creates the diagnosis object if it doesn't exist
              $scope.diagnosis.$save({
                'case_reference': $scope.case.reference
              }, function(data) {
                $scope.case.diagnosis = data.reference;
              });
            }
          };

          $scope.moveDown = function() {
            $scope.diagnosis.$move_down({
              'case_reference': $scope.case.reference
            }, saveCallback);

            // Mutation observer used to detect when form element has been changed
            // Due to new question (elements) being added and old question (elements) being removed
            var form = document.querySelector('form[name="diagnosis-form"]')

            // Element is placed 100px under the form buttons using CSS
            // To ensure user doesn't have to scroll to find the button
            var anchorScroll = document.getElementById('anchor-scroll');

            var config = {
              childList: true
            };

            var callback = function(mutationsList, observer) {
              observer.disconnect();
              anchorScroll.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
              return;
            };

            var observer = new MutationObserver(callback);

            observer.observe(form, config);
          };

          $scope.moveUp = function() {
            $scope.diagnosis.$move_up({
              'case_reference': $scope.case.reference
            }, saveCallback);
          };

          $scope.delete = function() {
            $scope.diagnosis.$delete({'case_reference': $scope.case.reference}, function() {
              $scope.case.diagnosis = null;
              eligibility_check.has_passported_proceedings_letter = false
              eligibility_check.$update($scope.case.reference)

              // refreshing the logs
              postal.publish({
                channel : 'models',
                topic   : 'Log.refresh'
              });
            });

            // Scroll to the top of the screen in case button is hidden from previous scrolling
            scrollTo(0,0);
          };

          // if choices.length === 1 => check it by default
          $scope.$watch('diagnosis.choices', function(newVal) {
            if (newVal && newVal.length === 1) {
              $scope.diagnosis.current_node_id = newVal[0].id;
            }
          });

          $scope.$watch('diagnosis.category', function(newVal) {
            if (!newVal) {
              $scope.category = null;
            } else {
              Category.get({code: $scope.diagnosis.category}).$promise.then(function(data) {
                $scope.category = data;
              });
            }
          });
        }
      ]
    );
})();
<commit_msg>Add more description to make it easier to track code<commit_after>(function(){
  'use strict';

  angular.module('cla.controllers')
    .controller('DiagnosisCtrl',
      ['$scope', 'Category', 'postal', 'eligibility_check',
        function($scope, Category, postal, eligibility_check) {
          // updates the state of case.diagnosis_state after each save
          function saveCallback(data) {
            $scope.case.diagnosis_state = data.state;

            if (!$scope.diagnosis.isInScopeUnknown()) {
              // refreshing the logs
              postal.publish({
                channel : 'models',
                topic   : 'Log.refresh'
              });
            }
          }

          // creates a new diagnosis
          $scope.createDiagnosis = function () {
            if (!$scope.case.diagnosis) {
              // creates the diagnosis object if it doesn't exist
              $scope.diagnosis.$save({
                'case_reference': $scope.case.reference
              }, function(data) {
                $scope.case.diagnosis = data.reference;
              });
            }
          };

          $scope.moveDown = function() {
            $scope.diagnosis.$move_down({
              'case_reference': $scope.case.reference
            }, saveCallback);

            // Mutation observer used to detect when form element has been changed
            // Due to new question (elements) being added and old question (elements) being removed
            var form = document.querySelector('form[name="diagnosis-form"]')

            // Element is placed 100px under the form buttons using CSS in _case.scss
            // To ensure user doesn't have to scroll to find the button
            var anchorScroll = document.getElementById('anchor-scroll');

            var config = {
              childList: true
            };

            var callback = function(mutationsList, observer) {
              observer.disconnect();
              anchorScroll.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
              return;
            };

            var observer = new MutationObserver(callback);

            observer.observe(form, config);
          };

          $scope.moveUp = function() {
            $scope.diagnosis.$move_up({
              'case_reference': $scope.case.reference
            }, saveCallback);
          };

          $scope.delete = function() {
            $scope.diagnosis.$delete({'case_reference': $scope.case.reference}, function() {
              $scope.case.diagnosis = null;
              eligibility_check.has_passported_proceedings_letter = false
              eligibility_check.$update($scope.case.reference)

              // refreshing the logs
              postal.publish({
                channel : 'models',
                topic   : 'Log.refresh'
              });
            });

            // Scroll to the top of the screen in case button is hidden from previous scrolling
            scrollTo(0,0);
          };

          // if choices.length === 1 => check it by default
          $scope.$watch('diagnosis.choices', function(newVal) {
            if (newVal && newVal.length === 1) {
              $scope.diagnosis.current_node_id = newVal[0].id;
            }
          });

          $scope.$watch('diagnosis.category', function(newVal) {
            if (!newVal) {
              $scope.category = null;
            } else {
              Category.get({code: $scope.diagnosis.category}).$promise.then(function(data) {
                $scope.category = data;
              });
            }
          });
        }
      ]
    );
})();
<|endoftext|>


<commit_before>/* globals aplazame */

var _ = require('../src/utils');

_.template.lookup();

var form = document.querySelector('form[data-submit="updateValues"]'),
    results = document.querySelector('.demo-simulator-results'),
    amount = form.querySelector('input[name="amount"]');

amount.value = localStorage.getItem('demo-simulator-amount');

function getCents(value) {
  var values = value.split(/[,.]/);
  return '' + ( Number( values[0] ? 100*values[0] : 0 ) + Number( values[1] || 0 ) );
}

_.listen(form, 'submit', function (e) {
  console.log('gogogo!');
  e.preventDefault();

  localStorage.setItem('demo-simulator-amount', amount.value);

  var currentAmount = getCents( amount.value );

  results.innerHTML = '
cargando...
';

  aplazame.simulator(currentAmount, function (choices) {
    console.log('simulator', currentAmount, choices);
    results.innerHTML = _.template('results', {
      getAmount: _.getAmount,
      choices: choices,
      months: function (m) {
        return m > 1 ? 'meses' : 'mes';
      }
    });
  });
});
<commit_msg>fixed simulator<commit_after>/* globals aplazame */

var _ = require('../src/tools/tools');

_.template.lookup();

var form = document.querySelector('form[data-submit="updateValues"]'),
    results = document.querySelector('.demo-simulator-results'),
    amount = form.querySelector('input[name="amount"]');

amount.value = localStorage.getItem('demo-simulator-amount');

function getCents(value) {
  var values = value.split(/[,.]/);
  return '' + ( Number( values[0] ? 100*values[0] : 0 ) + Number( values[1] || 0 ) );
}

_.listen(form, 'submit', function (e) {
  console.log('gogogo!');
  e.preventDefault();

  localStorage.setItem('demo-simulator-amount', amount.value);

  var currentAmount = getCents( amount.value );

  results.innerHTML = '
cargando...
';

  aplazame.simulator(currentAmount, function (choices) {
    console.log('simulator', currentAmount, choices);
    results.innerHTML = _.template('results', {
      getAmount: _.getAmount,
      choices: choices,
      months: function (m) {
        return m > 1 ? 'meses' : 'mes';
      }
    });
  });
});
<|endoftext|>


<commit_before>angular
    .module('app.core')
    .constant('BASE_URL', 'http://127.0.0.1:8000/api')
    .factory('trialService', trialService);

trialService.$inject = ['$resource', 'BASE_URL', '$log', 'pickSingleObjFilter', 'strReplaceFilter', 'pickMultiObjFilter', '$timeout'];

function trialService($resource, BASE_URL, $log, pickSingleObjFilter, strReplaceFilter, pickMultiObjFilter, $timeout) {
    var ids = [];
    return {
        'search': search,
        'get': get,
        'searchAllPages': searchAllPages,
        'searchId': searchId,
        'filterSingleObj': filterSingleObj,
        'strToKey': strToKey,
        'getNestedTrials': getNestedTrials,
        'filterMultiObj': filterMultiObj,
        'groupObjBy': groupObjBy,
        'getSearchedTrials': getSearchedTrials,
        'insertToArray': insertToArray,
        'applyArray': applyArray,
        'removeProperty': removeProperty,
        'calculateTotalPages': calculateTotalPages

    };

    function makeRequest(url, params) {
        var requestUrl = BASE_URL + '/' + url;

        return $resource(requestUrl, {}, {
            query: {
                'method': 'GET',
                'params': params,
                'headers': {
                    'Content-Type': 'application/json'
                },
                'interceptor' : {
                    'responseError' : dataServiceError
                },
                'cache': true
            },
            get: {
                'method': 'GET',
                'params': params,
                'headers': {
                    'Content-Type': 'application/json'
                },
                'interceptor' : {
                    'responseError' : dataServiceError
                },
                'cache': true
            }
        });
    }

    function search(apiNode, query){
        // Search one or more records per page
        return makeRequest(apiNode, query).query().$promise.
        then(function(data){
            return data;
        });
    }

    function get(apiNode, query) {
        // Get one record per page
        var id = Object.keys(query)[0];
        return makeRequest(apiNode + ':' + id, query).get().$promise;
    }

    function searchAllPages(apiNode, query, list) {
        // Search one or more records in all pages
        return makeRequest(apiNode, query).query().$promise.then(function(data){
            list = list.concat(data.results);
            if (data.next) {
                query.offset += query.limit;
                return searchAllPages(apiNode, query, list);
            }
            return list;
        });
    }

    function searchId(apiNode, query, key, obj) {
        // Get record id
        return makeRequest(apiNode, query).query().$promise.then(function(data){
            angular.forEach(data.results, function(arrObj){
                var lookup = 'id__in';
                var id = arrObj[key];
                if (lookup in obj){
                    if (ids.indexOf(id) === -1){
                        obj[lookup] += ',' + id;
                        ids.push(id);
                    }
                } else {
                    obj[lookup] = id;
                    ids.push(id);
                }
            });
            if (data.next) {
                query.offset += query.limit;
                return searchId(apiNode, query, key, obj);
            }
            return obj;
        });
    }

    function filterSingleObj(data, filterProp, replaceValue){
        return pickSingleObjFilter(data, filterProp, replaceValue);
    }

    function strToKey(keyOptions, str) {
        // Convert string to key by replacing space with an underscore
        var newKey = false;
        if (keyOptions) {
            str = typeof str !== undefined || str !== null ? str : false;
            angular.forEach(keyOptions, function(opt){
                if (str === opt){
                    newKey = strReplaceFilter(str, ' ', '_').toLowerCase();
                }
            });
        }
        return newKey;
    }

    function getNestedTrials(data, replaceKey, keyOptions){
        var newKey = false;
        var outObjArr = [];
        var nestedObj = false;
        replaceKey = typeof replaceKey !== undefined || replaceKey !== null ? replaceKey : false;
        keyOptions = typeof keyOptions !== undefined || keyOptions !== null ? keyOptions : false;
        angular.forEach(data, function(obj) {
            var outObj = {};
            angular.forEach(obj, function (value, key) {
                if (typeof value === 'object') {
                    nestedObj = value;
                } else {
                    var strKey = strToKey(keyOptions, value);
                    newKey = strKey ? strKey : newKey;
                    key = newKey && (key === replaceKey) ? newKey : key;
                    outObj[key] = value;
                }
            });
            outObjArr = outObjArr.concat(outObj);
        });
        return {
            outObjArr: outObjArr,
            nestedObj: nestedObj
        };
    }

    function filterMultiObj(data, filterProp, replaceValue) {
        return pickMultiObjFilter(data, filterProp, replaceValue);
    }

    function groupObjBy(data, mergeProp){
        // Merge similar objects into one
        var outObjArr = [];
        angular.forEach(data, function(obj){
            var existing = outObjArr.filter(function(outObj){
                var objComp = '';
                if (angular.isArray(mergeProp) && mergeProp.length) {
                    angular.forEach(mergeProp, function (prop, index) {
                        objComp += ('"' + obj[prop] + '"==="' + outObj[prop] + '"');
                        if (mergeProp.length > 1 && (index + 1) < mergeProp.length){
                            objComp += (' && ');
                        }
                    });
                }
                if (eval(objComp)) return true;
            });
            existing.length ? angular.merge(outObjArr[outObjArr.indexOf(existing[0])], obj) : outObjArr = outObjArr.concat(obj);
        });
        return outObjArr;
    }

    function getSearchedTrials (results, searchObj, keyOptions) {
        var outObj = [];
        keyOptions = typeof keyOptions !== undefined || keyOptions !== null ? keyOptions : false;
        angular.forEach(results, function (resultsObj){
            var objMatch = [];
            angular.forEach(searchObj, function (srcValue, srcKey){
                if (angular.isArray(srcValue)){
                    var inObjMatch = [];
                    angular.forEach(srcValue, function (subSrcValue) {
                        var strKey = strToKey(keyOptions, subSrcValue[srcKey]);
                        if (strKey) {
                            resultsObj.hasOwnProperty(strKey) ? inObjMatch.push(true) : inObjMatch.push(false);
                        }else{
                            subSrcValue[srcKey] === resultsObj[srcKey] ? inObjMatch.push(true) : inObjMatch.push(false);
                        }
                    });
                    (inObjMatch.indexOf(true) !== -1 || srcValue.length === 0) ? objMatch.push(true) : objMatch.push(false);
                }else if (typeof srcValue === 'object'){
                    srcValue[srcKey] === resultsObj[srcKey] ? objMatch.push(true) : objMatch.push(false);
                }
            });
            if (objMatch.indexOf(false) === -1) outObj = outObj.concat(resultsObj);
        });
        return outObj;
    }

    function insertToArray (input, nextElement, newElement) {
        var itemInserted = false;
        Array.prototype.insert = function (index) {
            this.splice.apply(this, [index, 0].concat(this.slice.call(arguments, 1)));
        };
        angular.forEach(input, function (obj, index) {
            if (!itemInserted){
                angular.forEach(obj, function (value, key) {
                    if (key === nextElement && !itemInserted){
                        input.insert(index, newElement);
                        itemInserted = true;
                    }
                });
            }
        });
        return input;
    }

    function applyArray (container, key) {
        $timeout(function() {
            var arrayCopy = container[key];
            container[key] = [];
            container.$apply();
            container[key] = arrayCopy;
            container.$apply();
        }, 0);
    }

    function removeProperty (obj, propValue){
        angular.forEach(obj, function(value, key){
            if (!angular.isArray(value) && value[key].startsWith(propValue)){
                delete obj[key];
            }
        });
        return obj;
    }

    function calculateTotalPages (pageSize, totalItems) {
        var totalPages = pageSize < 1 ? 1 : Math.ceil(totalItems / pageSize);
        return Math.max(totalPages || 0, 1);
    }

    function dataServiceError(errorResponse) {
        $log.error('XHR Failed for ShowService');
        $log.error(errorResponse);
        return errorResponse;
    }
}
<commit_msg>Added id querying functionality<commit_after>angular
    .module('app.core')
    .constant('BASE_URL', 'http://127.0.0.1:8000/api')
    .factory('trialService', trialService);

trialService.$inject = ['$resource', 'BASE_URL', '$log', 'pickSingleObjFilter', 'strReplaceFilter', 'pickMultiObjFilter', '$timeout'];

function trialService($resource, BASE_URL, $log, pickSingleObjFilter, strReplaceFilter, pickMultiObjFilter, $timeout) {
    var ids = [];
    return {
        'search': search,
        'get': get,
        'searchAllPages': searchAllPages,
        'searchId': searchId,
        'filterSingleObj': filterSingleObj,
        'strToKey': strToKey,
        'getNestedTrials': getNestedTrials,
        'filterMultiObj': filterMultiObj,
        'groupObjBy': groupObjBy,
        'getSearchedTrials': getSearchedTrials,
        'insertToArray': insertToArray,
        'applyArray': applyArray,
        'removeProperty': removeProperty,
        'calculateTotalPages': calculateTotalPages

    };

    function makeRequest(url, params) {
        var requestUrl = BASE_URL + '/' + url;

        return $resource(requestUrl, {}, {
            query: {
                'method': 'GET',
                'params': params,
                'headers': {
                    'Content-Type': 'application/json'
                },
                'interceptor' : {
                    'responseError' : dataServiceError
                },
                'cache': true
            },
            get: {
                'method': 'GET',
                'params': params,
                'headers': {
                    'Content-Type': 'application/json'
                },
                'interceptor' : {
                    'responseError' : dataServiceError
                },
                'cache': true
            }
        });
    }

    function search(apiNode, query){
        // Search one or more records per page
        return makeRequest(apiNode, query).query().$promise.
        then(function(data){
            return data;
        });
    }

    function get(apiNode, query) {
        // Get one record per page
        var id = Object.keys(query)[0];
        return makeRequest(apiNode + ':' + id, query).get().$promise;
    }

    function searchAllPages(apiNode, query, list) {
        // Search one or more records in all pages
        return makeRequest(apiNode, query).query().$promise.then(function(data){
            list = list.concat(data.results);
            if (data.next) {
                query.offset += query.limit;
                return searchAllPages(apiNode, query, list);
            }
            return list;
        });
    }

    function searchId(apiNode, query, key, obj) {
        // Get record id
        return makeRequest(apiNode, query).query().$promise.then(function(data){
            angular.forEach(data.results, function(arrObj){
                var lookup = 'id__in';
                var id = arrObj[key];
                if (lookup in obj){
                    if (ids.indexOf(id) === -1){
                        obj[lookup] += ',' + id;
                        ids.push(id);
                    }
                } else {
                    obj[lookup] = id;
                    ids.push(id);
                }
            });
            if (data.next) {
                query.offset += query.limit;
                return searchId(apiNode, query, key, obj);
            }
            ids = [];
            return obj;
        });
    }

    function filterSingleObj(data, filterProp, replaceValue){
        return pickSingleObjFilter(data, filterProp, replaceValue);
    }

    function strToKey(keyOptions, str) {
        // Convert string to key by replacing space with an underscore
        var newKey = false;
        if (keyOptions) {
            str = typeof str !== undefined || str !== null ? str : false;
            angular.forEach(keyOptions, function(opt){
                if (str === opt){
                    newKey = strReplaceFilter(str, ' ', '_').toLowerCase();
                }
            });
        }
        return newKey;
    }

    function getNestedTrials(data, replaceKey, keyOptions){
        var newKey = false;
        var outObjArr = [];
        var nestedObj = false;
        replaceKey = typeof replaceKey !== undefined || replaceKey !== null ? replaceKey : false;
        keyOptions = typeof keyOptions !== undefined || keyOptions !== null ? keyOptions : false;
        angular.forEach(data, function(obj) {
            var outObj = {};
            angular.forEach(obj, function (value, key) {
                if (typeof value === 'object') {
                    nestedObj = value;
                } else {
                    var strKey = strToKey(keyOptions, value);
                    newKey = strKey ? strKey : newKey;
                    key = newKey && (key === replaceKey) ? newKey : key;
                    outObj[key] = value;
                }
            });
            outObjArr = outObjArr.concat(outObj);
        });
        return {
            outObjArr: outObjArr,
            nestedObj: nestedObj
        };
    }

    function filterMultiObj(data, filterProp, replaceValue) {
        return pickMultiObjFilter(data, filterProp, replaceValue);
    }

    function groupObjBy(data, mergeProp){
        // Merge similar objects into one
        var outObjArr = [];
        angular.forEach(data, function(obj){
            var existing = outObjArr.filter(function(outObj){
                var objComp = '';
                if (angular.isArray(mergeProp) && mergeProp.length) {
                    angular.forEach(mergeProp, function (prop, index) {
                        objComp += ('"' + obj[prop] + '"==="' + outObj[prop] + '"');
                        if (mergeProp.length > 1 && (index + 1) < mergeProp.length){
                            objComp += (' && ');
                        }
                    });
                }
                if (eval(objComp)) return true;
            });
            existing.length ? angular.merge(outObjArr[outObjArr.indexOf(existing[0])], obj) : outObjArr = outObjArr.concat(obj);
        });
        return outObjArr;
    }

    function getSearchedTrials (results, searchObj, keyOptions) {
        var outObj = [];
        keyOptions = typeof keyOptions !== undefined || keyOptions !== null ? keyOptions : false;
        angular.forEach(results, function (resultsObj){
            var objMatch = [];
            angular.forEach(searchObj, function (srcValue, srcKey){
                if (angular.isArray(srcValue)){
                    var inObjMatch = [];
                    angular.forEach(srcValue, function (subSrcValue) {
                        var strKey = strToKey(keyOptions, subSrcValue[srcKey]);
                        if (strKey) {
                            resultsObj.hasOwnProperty(strKey) ? inObjMatch.push(true) : inObjMatch.push(false);
                        }else{
                            subSrcValue[srcKey] === resultsObj[srcKey] ? inObjMatch.push(true) : inObjMatch.push(false);
                        }
                    });
                    (inObjMatch.indexOf(true) !== -1 || srcValue.length === 0) ? objMatch.push(true) : objMatch.push(false);
                }else if (typeof srcValue === 'object'){
                    srcValue[srcKey] === resultsObj[srcKey] ? objMatch.push(true) : objMatch.push(false);
                }
            });
            if (objMatch.indexOf(false) === -1) outObj = outObj.concat(resultsObj);
        });
        return outObj;
    }

    function insertToArray (input, nextElement, newElement) {
        var itemInserted = false;
        Array.prototype.insert = function (index) {
            this.splice.apply(this, [index, 0].concat(this.slice.call(arguments, 1)));
        };
        angular.forEach(input, function (obj, index) {
            if (!itemInserted){
                angular.forEach(obj, function (value, key) {
                    if (key === nextElement && !itemInserted){
                        input.insert(index, newElement);
                        itemInserted = true;
                    }
                });
            }
        });
        return input;
    }

    function applyArray (container, key) {
        $timeout(function() {
            var arrayCopy = container[key];
            container[key] = [];
            container.$apply();
            container[key] = arrayCopy;
            container.$apply();
        }, 0);
    }

    function removeProperty (obj, propValue){
        angular.forEach(obj, function(value, key){
            if (!angular.isArray(value) && value[key].startsWith(propValue)){
                delete obj[key];
            }
        });
        return obj;
    }

    function calculateTotalPages (pageSize, totalItems) {
        var totalPages = pageSize < 1 ? 1 : Math.ceil(totalItems / pageSize);
        return Math.max(totalPages || 0, 1);
    }

    function dataServiceError(errorResponse) {
        $log.error('XHR Failed for ShowService');
        $log.error(errorResponse);
        return errorResponse;
    }
}
<|endoftext|>


<commit_before>const config = require('../config.js')
const storage = require('../util/storage.js')
const TEST_OPTIONS = { split: { prepend: '```md\n', append: '```' } }
const log = require('../util/logger.js')
const debugFeeds = require('../util/debugFeeds.js').list
const translate = require('../rss/translator/translate.js')
const deletedFeeds = storage.deletedFeeds

class ArticleMessage {
  constructor (article, isTestMessage, skipFilters) {
    if (!article._delivery) throw new Error('article._delivery property missing')
    if (!article._delivery.rssName) throw new Error('article._delivery.rssName property missing')
    if (!article._delivery.source) throw new Error('article._delivery.source property missing')
    if (!article._delivery.channelId) throw new Error('article._delivery.channelId property missing')
    if (!article._delivery.dateSettings) throw new Error('article._delivery.dateSettings property missing')
    this.article = article
    this.isTestMessage = isTestMessage
    this.skipFilters = skipFilters || isTestMessage
    this.channelId = article.discordChannelId
    this.channel = storage.bot.channels.get(article._delivery.channelId)
    if (!this.channel) return
    this.webhook = undefined
    this.sendFailed = 1
    this.rssName = article._delivery.rssName
    this.source = article._delivery.source
    this.toggleRoleMentions = typeof this.source.toggleRoleMentions === 'boolean' ? this.source.toggleRoleMentions : config.feeds.toggleRoleMentions
    this.split = this.source.splitMessage // The split options if the message exceeds the character limit. If undefined, do not split, otherwise it is an object with keys char, prepend, append
    this._translate()
  }

  async _resolveChannel () {
    if (typeof this.source.webhook !== 'object' || !this.channel.guild.me.permissionsIn(this.channel).has('MANAGE_WEBHOOKS')) return
    try {
      const hooks = await this.channel.fetchWebhooks()
      const hook = hooks.get(this.source.webhook.id)
      if (!hook) return
      const guildId = this.channel.guild.id
      const guildName = this.channel.guild.name
      this.webhook = hook
      this.webhook.guild = { id: guildId, name: guildName }
      let name = this.source.webhook.name ? this.parsedArticle.convertKeywords(this.source.webhook.name) : undefined
      if (name && name.length > 32) name = name.slice(0, 29) + '...'
      if (name && name.length < 2) name = undefined
      this.webhook.name = name
      this.webhook.avatar = this.source.webhook.avatar ? this.parsedArticle.convertImgs(this.source.webhook.avatar) : undefined
      return
    } catch (err) {
      log.general.warning(`Cannot fetch webhooks for ArticleMessage webhook initialization to send message`, this.channel, err, true)
    }
  }

  _translate (ignoreLimits) {
    const results = translate(this.article._delivery.source, this.article, this.isTestMessage, ignoreLimits, this.article._delivery.dateSettings)
    this.parsedArticle = results.parsedArticle
    this.subscriptionIds = this.parsedArticle.subscriptionIds
    this.passedFilters = results.passedFilters
    this.testDetails = results.testDetails
    this.embeds = results.embeds
    this.text = results.text
  }

  async send () {
    if (!this.source) throw new Error('Missing feed source')
    if (!this.channel) throw new Error('Missing feed channel')
    await this._resolveChannel()
    if (!this.skipFilters && !this.passedFilters) {
      if (config.log.unfiltered === true) log.general.info(`'${this.article.link ? this.article.link : this.article.title}' did not pass filters and was not sent`, this.channel)
      return
    }
    if (deletedFeeds.includes(this.rssName)) throw new Error(`${this.rssName} for channel ${this.channel.id} was deleted during cycle`)

    // Set up the send options
    const textContent = this.isTestMessage ? this.testDetails : this.text.length > 1950 && !this.split ? `Error: Feed Article could not be sent for ${this.article.link} due to a single message's character count >1950.` : this.text.length === 0 && !this.embeds ? `Unable to send empty message for feed article <${this.article.link}>.` : this.text
    const options = this.isTestMessage ? TEST_OPTIONS : {}
    if (this.webhook) {
      options.username = this.webhook.name
      options.avatarURL = this.webhook.avatar
    }
    if (!this.isTestMessage && this.embeds) {
      if (this.webhook) options.embeds = this.embeds
      else options.embed = this.embeds[0]
    }
    if (!this.isTestMessage) options.split = this.split

    // Send the message, and repeat attempt if failed
    const medium = this.webhook ? this.webhook : this.channel
    try {
      const m = await medium.send(textContent, options)
      if (this.isTestMessage) {
        this.isTestMessage = false
        return this.send()
      } else return m
    } catch (err) {
      if (this.split && err.message.includes('2000 or fewer in length')) {
        delete this.split
        this._translate(false)
        return this.send()
      }
      if (this.split && err.message.includes('no split characters')) {
        this._translate(false) // Retranslate with the character limits for individual placeholders again
        return this.send()
      }
      if (err.code === 50013 || this.sendFailed++ === 4) { // 50013 = Missing Permissions
        if (debugFeeds.includes(this.rssName)) log.debug.error(`${this.rssName}: Message has been translated but could not be sent (TITLE: ${this.article.title})`, err)
        throw err
      }
      return this.send()
    }
  }
}

module.exports = ArticleMessage
<commit_msg>Fixed role mention toggling not working<commit_after>const config = require('../config.js')
const storage = require('../util/storage.js')
const TEST_OPTIONS = { split: { prepend: '```md\n', append: '```' } }
const log = require('../util/logger.js')
const debugFeeds = require('../util/debugFeeds.js').list
const translate = require('../rss/translator/translate.js')
const deletedFeeds = storage.deletedFeeds

class ArticleMessage {
  constructor (article, isTestMessage, skipFilters) {
    if (!article._delivery) throw new Error('article._delivery property missing')
    if (!article._delivery.rssName) throw new Error('article._delivery.rssName property missing')
    if (!article._delivery.source) throw new Error('article._delivery.source property missing')
    if (!article._delivery.channelId) throw new Error('article._delivery.channelId property missing')
    if (!article._delivery.dateSettings) throw new Error('article._delivery.dateSettings property missing')
    this.article = article
    this.isTestMessage = isTestMessage
    this.skipFilters = skipFilters || isTestMessage
    this.channelId = article._delivery.channelId
    this.channel = storage.bot.channels.get(article._delivery.channelId)
    if (!this.channel) return
    this.webhook = undefined
    this.sendFailed = 1
    this.rssName = article._delivery.rssName
    this.source = article._delivery.source
    this.toggleRoleMentions = typeof this.source.toggleRoleMentions === 'boolean' ? this.source.toggleRoleMentions : config.feeds.toggleRoleMentions
    this.split = this.source.splitMessage // The split options if the message exceeds the character limit. If undefined, do not split, otherwise it is an object with keys char, prepend, append
    this._translate()
  }

  async _resolveChannel () {
    if (typeof this.source.webhook !== 'object' || !this.channel.guild.me.permissionsIn(this.channel).has('MANAGE_WEBHOOKS')) return
    try {
      const hooks = await this.channel.fetchWebhooks()
      const hook = hooks.get(this.source.webhook.id)
      if (!hook) return
      const guildId = this.channel.guild.id
      const guildName = this.channel.guild.name
      this.webhook = hook
      this.webhook.guild = { id: guildId, name: guildName }
      let name = this.source.webhook.name ? this.parsedArticle.convertKeywords(this.source.webhook.name) : undefined
      if (name && name.length > 32) name = name.slice(0, 29) + '...'
      if (name && name.length < 2) name = undefined
      this.webhook.name = name
      this.webhook.avatar = this.source.webhook.avatar ? this.parsedArticle.convertImgs(this.source.webhook.avatar) : undefined
      return
    } catch (err) {
      log.general.warning(`Cannot fetch webhooks for ArticleMessage webhook initialization to send message`, this.channel, err, true)
    }
  }

  _translate (ignoreLimits) {
    const results = translate(this.article._delivery.source, this.article, this.isTestMessage, ignoreLimits, this.article._delivery.dateSettings)
    this.parsedArticle = results.parsedArticle
    this.subscriptionIds = this.parsedArticle.subscriptionIds
    this.passedFilters = results.passedFilters
    this.testDetails = results.testDetails
    this.embeds = results.embeds
    this.text = results.text
  }

  async send () {
    if (!this.source) throw new Error('Missing feed source')
    if (!this.channel) throw new Error('Missing feed channel')
    await this._resolveChannel()
    if (!this.skipFilters && !this.passedFilters) {
      if (config.log.unfiltered === true) log.general.info(`'${this.article.link ? this.article.link : this.article.title}' did not pass filters and was not sent`, this.channel)
      return
    }
    if (deletedFeeds.includes(this.rssName)) throw new Error(`${this.rssName} for channel ${this.channel.id} was deleted during cycle`)

    // Set up the send options
    const textContent = this.isTestMessage ? this.testDetails : this.text.length > 1950 && !this.split ? `Error: Feed Article could not be sent for ${this.article.link} due to a single message's character count >1950.` : this.text.length === 0 && !this.embeds ? `Unable to send empty message for feed article <${this.article.link}>.` : this.text
    const options = this.isTestMessage ? TEST_OPTIONS : {}
    if (this.webhook) {
      options.username = this.webhook.name
      options.avatarURL = this.webhook.avatar
    }
    if (!this.isTestMessage && this.embeds) {
      if (this.webhook) options.embeds = this.embeds
      else options.embed = this.embeds[0]
    }
    if (!this.isTestMessage) options.split = this.split

    // Send the message, and repeat attempt if failed
    const medium = this.webhook ? this.webhook : this.channel
    try {
      const m = await medium.send(textContent, options)
      if (this.isTestMessage) {
        this.isTestMessage = false
        return this.send()
      } else return m
    } catch (err) {
      if (this.split && err.message.includes('2000 or fewer in length')) {
        delete this.split
        this._translate(false)
        return this.send()
      }
      if (this.split && err.message.includes('no split characters')) {
        this._translate(false) // Retranslate with the character limits for individual placeholders again
        return this.send()
      }
      if (err.code === 50013 || this.sendFailed++ === 4) { // 50013 = Missing Permissions
        if (debugFeeds.includes(this.rssName)) log.debug.error(`${this.rssName}: Message has been translated but could not be sent (TITLE: ${this.article.title})`, err)
        throw err
      }
      return this.send()
    }
  }
}

module.exports = ArticleMessage
<|endoftext|>