<commit_before>self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
<<<<<<< HEAD:public/precache-manifest.adaefb6d29aa9e21662558edfeaa62b1.js
    "revision": "008edb9af9fa8e290b05a04b0eebaf73",
=======
    "revision": "6c084f672cf9a168bcf9ba836f217ee5",
>>>>>>> release-5.14:public/precache-manifest.e048ba5083eaab9efc3e5fe8ceb34af1.js
    "url": "/index.html"
  },
  {
    "revision": "0f5c7d4ebad039a2ab9f",
    "url": "/static/css/2.ea29ef5f.chunk.css"
  },
  {
<<<<<<< HEAD:public/precache-manifest.adaefb6d29aa9e21662558edfeaa62b1.js
    "revision": "faa3dc3f87bd33c4dae3",
=======
    "revision": "879b020c99946aa93081",
>>>>>>> release-5.14:public/precache-manifest.e048ba5083eaab9efc3e5fe8ceb34af1.js
    "url": "/static/css/main.4021f65e.chunk.css"
  },
  {
    "revision": "0f5c7d4ebad039a2ab9f",
    "url": "/static/js/2.de7cae14.chunk.js"
  },
  {
    "revision": "06c9834ea13c3499f3dc",
    "url": "/static/js/3.98f0c0d2.chunk.js"
  },
  {
    "revision": "a0df23e252ff34720bab",
    "url": "/static/js/4.8b43f47a.chunk.js"
  },
  {
<<<<<<< HEAD:public/precache-manifest.adaefb6d29aa9e21662558edfeaa62b1.js
    "revision": "faa3dc3f87bd33c4dae3",
    "url": "/static/js/main.b04db7ed.chunk.js"
=======
    "revision": "879b020c99946aa93081",
    "url": "/static/js/main.da9d6906.chunk.js"
>>>>>>> release-5.14:public/precache-manifest.e048ba5083eaab9efc3e5fe8ceb34af1.js
  },
  {
    "revision": "0d87e1548759fb0c377b",
    "url": "/static/js/runtime~main.457fd582.js"
  },
  {
    "revision": "1f38670a7d7ae21d3c7e2099513f5114",
    "url": "/static/media/billRun-cloud-logo.1f38670a.png"
  },
  {
    "revision": "674f50d287a8c48dc19ba404d20fe713",
    "url": "/static/media/fontawesome-webfont.674f50d2.eot"
  },
  {
    "revision": "912ec66d7572ff821749319396470bde",
    "url": "/static/media/fontawesome-webfont.912ec66d.svg"
  },
  {
    "revision": "af7ae505a9eed503f8b8e6982036873e",
    "url": "/static/media/fontawesome-webfont.af7ae505.woff2"
  },
  {
    "revision": "b06871f281fee6b241d60582ae9369b9",
    "url": "/static/media/fontawesome-webfont.b06871f2.ttf"
  },
  {
    "revision": "fee66e712a8a08eef5805a46892932ad",
    "url": "/static/media/fontawesome-webfont.fee66e71.woff"
  },
  {
    "revision": "1f38670a7d7ae21d3c7e2099513f5114",
    "url": "/static/media/footer-logo.1f38670a.png"
  }
]);<commit_msg>Update precache-manifest.adaefb6d29aa9e21662558edfeaa62b1.js (issue after conflicts resolution)<commit_after>self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "008edb9af9fa8e290b05a04b0eebaf73",
    "url": "/index.html"
  },
  {
    "revision": "0f5c7d4ebad039a2ab9f",
    "url": "/static/css/2.ea29ef5f.chunk.css"
  },
  {
    "revision": "faa3dc3f87bd33c4dae3",
    "url": "/static/css/main.4021f65e.chunk.css"
  },
  {
    "revision": "0f5c7d4ebad039a2ab9f",
    "url": "/static/js/2.de7cae14.chunk.js"
  },
  {
    "revision": "06c9834ea13c3499f3dc",
    "url": "/static/js/3.98f0c0d2.chunk.js"
  },
  {
    "revision": "a0df23e252ff34720bab",
    "url": "/static/js/4.8b43f47a.chunk.js"
  },
  {
    "revision": "faa3dc3f87bd33c4dae3",
    "url": "/static/js/main.b04db7ed.chunk.js"
  },
  {
    "revision": "0d87e1548759fb0c377b",
    "url": "/static/js/runtime~main.457fd582.js"
  },
  {
    "revision": "1f38670a7d7ae21d3c7e2099513f5114",
    "url": "/static/media/billRun-cloud-logo.1f38670a.png"
  },
  {
    "revision": "674f50d287a8c48dc19ba404d20fe713",
    "url": "/static/media/fontawesome-webfont.674f50d2.eot"
  },
  {
    "revision": "912ec66d7572ff821749319396470bde",
    "url": "/static/media/fontawesome-webfont.912ec66d.svg"
  },
  {
    "revision": "af7ae505a9eed503f8b8e6982036873e",
    "url": "/static/media/fontawesome-webfont.af7ae505.woff2"
  },
  {
    "revision": "b06871f281fee6b241d60582ae9369b9",
    "url": "/static/media/fontawesome-webfont.b06871f2.ttf"
  },
  {
    "revision": "fee66e712a8a08eef5805a46892932ad",
    "url": "/static/media/fontawesome-webfont.fee66e71.woff"
  },
  {
    "revision": "1f38670a7d7ae21d3c7e2099513f5114",
    "url": "/static/media/footer-logo.1f38670a.png"
  }
]);
<|endoftext|>


<commit_before>(function() {

    'use strict';

    angular
        .module('openlmis-core')
        .factory('localStorageFactory', factory);

    factory.$inject = ['$localStorage'];
    function factory($localStorage) {

        return LocalStorageFactory;

        function LocalStorageFactory(resourceName) {
            var resource,
                storage = {
                    get: get,
                    getAll: getAll,
                    put: put,
                    clearAll: clearAll
                };

            if (!$localStorage[resourceName]) {
                $localStorage[resourceName] = {};
            }

            resource = $localStorage[resourceName];

            return storage;

            function get(id) {
                return resource[id];
            }

            function getAll() {
                var items = [];
                angular.forEach(resource, function(item) {
                    items.push(item);
                });
                return items;
            }

            function put(item) {
                var index;
                if(!item.id) index = generateIndex();
                else index = item.id;
                resource[index] = item;
                return index;
            }

            function clearAll() {
                $localStorage[resourceName] = {};
                resource = {};
            }

            function generateIndex() {
                var index;
                do {
                    index = Math.random();
                }
                while(resource[index]);
                return index;
            }
        }
    }
})();
<commit_msg>OLMIS-1338: moved initialize localStorage to begining of function<commit_after>(function() {

    'use strict';

    angular
        .module('openlmis-core')
        .factory('localStorageFactory', factory);

    factory.$inject = ['$localStorage'];
    function factory($localStorage) {

        return LocalStorageFactory;

        function LocalStorageFactory(resourceName) {
            if(!$localStorage[resourceName]) $localStorage[resourceName] = {};
            var resource = $localStorage[resourceName],
                storage = {
                    get: get,
                    getAll: getAll,
                    put: put,
                    clearAll: clearAll
                };

            return storage;

            function get(id) {
                return resource[id];
            }

            function getAll() {
                var items = [];
                angular.forEach(resource, function(item) {
                    items.push(item);
                });
                return items;
            }

            function put(item) {
                var index;
                if(!item.id) index = generateIndex();
                else index = item.id;
                resource[index] = item;
                return index;
            }

            function clearAll() {
                $localStorage[resourceName] = {};
                resource = {};
            }

            function generateIndex() {
                var index;
                do {
                    index = Math.random();
                }
                while(resource[index]);
                return index;
            }
        }
    }
})();
<|endoftext|>


<commit_before>'use strict';

var diffMatchPatch;
/**
 * @param {Function} onload
 */
function loadDiffMatchPatch(onload) {
    console.info('Loading diff_match_patch.js');
    var script = document.createElement('script');
    script.src = 'diff_match_patch.js';
    script.onload = function() {
        diffMatchPatch = new diff_match_patch();
        console.info('diff_match_patch.js loaded');
        onload();
    };
    document.head.appendChild(script);
}

function ResourceMap() {
    this._map = {};
}
ResourceMap.prototype = {
    get: function(key) {
        this.assertKey(key);
        if (!this._map.hasOwnProperty(key)) {
            throw new Error('resourceMap does not have ' + JSON.stringify(key) + ' key.');
        }
        return this._map[key];
    },
    set: function(key, value) {
        this.assertKey(key);
        this._map[key] = value;
    },
    assertKey: function(key) {
        if (!key) {
            throw new Error('key is ' + JSON.stringify(key));
        }
    }
};

var resourceMap;
var lastStylesheetURL = '';
var addedCSS = '';

/**
 * @param {Object} event
 * @nosideeffects
 * @return {boolean}
 */
function isNewlyAdded(event) {
    return event.url.indexOf('inspector://') == 0 || event.type === 'document';
}

chrome.devtools.inspectedWindow.onResourceContentCommitted.addListener(function(event) {

    if (isNewlyAdded(event)) {
        if (lastStylesheetURL) {
            getBackend(lastStylesheetURL);
        } else {
            getLastStylesheetURL(getBackend);
        }
    } else {
        getBackend(event.url);
    }

    function getBackend(url) {
        chrome.extension.sendRequest({method: 'getBackend', url: url}, function(response) {

            if (!response) {
                console.error(url + ' doesn\'t match any rules in the DevTools Autosave options.');
                return;
            }

            event.getContent(function(content) {
                if (diffMatchPatch) {
                    sendToBackgroundPage();
                } else {
                    loadDiffMatchPatch(sendToBackgroundPage);
                }

                function sendToBackgroundPage() {
                    var patch;
                    if (isNewlyAdded(event)) {
                        console.info('New CSS rules added. Appending them to', lastStylesheetURL);
                        var oldAddedCSS = addedCSS;
                        if (content) {
                            addedCSS = '\n' + content + '\n';
                        } else {
                            addedCSS = '';
                        }
                        patch = diffMatchPatch.patch_make(resourceMap.get(lastStylesheetURL) + oldAddedCSS, resourceMap.get(lastStylesheetURL) + addedCSS);
                    } else {
                        patch = diffMatchPatch.patch_make(resourceMap.get(url), content);
                        resourceMap.set(url, content);
                    }

                    if (arePatchesEmpty(patch)) {
                        console.error('Patch for ' + JSON.stringify(url) + ' is empty.');
                        return;
                    }

                    chrome.extension.sendRequest({
                        method: 'send',
                        content: JSON.stringify(patch),
                        url: response.serverURL,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-URL': url,
                            'X-Path': response.savePath,
                            'X-Type': event.type
                        }
                    });
                }
            });
        });
    }
});

/**
 * @param {Array} patches
 * @nosideeffects
 * @return {Boolean}
 */
function arePatchesEmpty(patches) {
    for (var i = 0, ii = patches.length; i < ii; i++) {
        if (patches[i].diffs.length > 0) {
            return false;
        }
    }
    return true;
}

/**
 * @param {Function} onSuccess
 */
function getLastStylesheetURL(onSuccess) {
    lastStylesheetURL = '';
    chrome.devtools.inspectedWindow.eval('(function() {\n\
    var links = document.head.querySelectorAll("link[rel=stylesheet][href]");\n\
    var last = links[links.length - 1];\n\
    return last && last.href})()', function(href, fail) {
        if (fail || !href) {
            throw new Error('Cannot find link[rel=stylesheet][href] in the head.');
        }
        lastStylesheetURL = href;
        onSuccess(href);
    });
}

/**
 * @param {Resource} resource
 */
function addResource(resource) {
    var url = resource.url;
    if (!url || url === 'about:blank') {
        return;
    }
    switch (resource.type) {
        case 'stylesheet':
        case 'script':
            resource.getContent(function(content) {
                resourceMap.set(url, content);
            });
            console.info(url, 'loaded');
            break;
    }
}

function getAllResources() {
    console.info('Loading all scripts and stylesheets');
    resourceMap = new ResourceMap();
    chrome.devtools.inspectedWindow.getResources(function(resources) {
        resources.forEach(addResource);
    });
}

getAllResources();

chrome.devtools.inspectedWindow.onResourceAdded.addListener(addResource);

chrome.devtools.network.onNavigated.addListener(function() {
    console.info('A page reloaded');
    addedCSS = '';
    getAllResources();
});
<commit_msg>Don’t add all resources twice after on page load<commit_after>'use strict';

var diffMatchPatch;
/**
 * @param {Function} onload
 */
function loadDiffMatchPatch(onload) {
    console.info('Loading diff_match_patch.js');
    var script = document.createElement('script');
    script.src = 'diff_match_patch.js';
    script.onload = function() {
        diffMatchPatch = new diff_match_patch();
        console.info('diff_match_patch.js loaded');
        onload();
    };
    document.head.appendChild(script);
}

function ResourceMap() {
    this._map = {};
}
ResourceMap.prototype = {
    get: function(key) {
        this.assertKey(key);
        if (!this._map.hasOwnProperty(key)) {
            throw new Error('resourceMap does not have ' + JSON.stringify(key) + ' key.');
        }
        return this._map[key];
    },
    set: function(key, value) {
        this.assertKey(key);
        this._map[key] = value;
    },
    assertKey: function(key) {
        if (!key) {
            throw new Error('key is ' + JSON.stringify(key));
        }
    }
};

var resourceMap;
var lastStylesheetURL = '';
var addedCSS = '';

/**
 * @param {Object} event
 * @nosideeffects
 * @return {boolean}
 */
function isNewlyAdded(event) {
    return event.url.indexOf('inspector://') == 0 || event.type === 'document';
}

chrome.devtools.inspectedWindow.onResourceContentCommitted.addListener(function(event) {

    if (isNewlyAdded(event)) {
        if (lastStylesheetURL) {
            getBackend(lastStylesheetURL);
        } else {
            getLastStylesheetURL(getBackend);
        }
    } else {
        getBackend(event.url);
    }

    function getBackend(url) {
        chrome.extension.sendRequest({method: 'getBackend', url: url}, function(response) {

            if (!response) {
                console.error(url + ' doesn\'t match any rules in the DevTools Autosave options.');
                return;
            }

            event.getContent(function(content) {
                if (diffMatchPatch) {
                    sendToBackgroundPage();
                } else {
                    loadDiffMatchPatch(sendToBackgroundPage);
                }

                function sendToBackgroundPage() {
                    var patch;
                    if (isNewlyAdded(event)) {
                        console.info('New CSS rules added. Appending them to', lastStylesheetURL);
                        var oldAddedCSS = addedCSS;
                        if (content) {
                            addedCSS = '\n' + content + '\n';
                        } else {
                            addedCSS = '';
                        }
                        patch = diffMatchPatch.patch_make(resourceMap.get(lastStylesheetURL) + oldAddedCSS, resourceMap.get(lastStylesheetURL) + addedCSS);
                    } else {
                        patch = diffMatchPatch.patch_make(resourceMap.get(url), content);
                        resourceMap.set(url, content);
                    }

                    if (arePatchesEmpty(patch)) {
                        console.error('Patch for ' + JSON.stringify(url) + ' is empty.');
                        return;
                    }

                    chrome.extension.sendRequest({
                        method: 'send',
                        content: JSON.stringify(patch),
                        url: response.serverURL,
                        headers: {
                            'Content-Type': 'application/json',
                            'X-URL': url,
                            'X-Path': response.savePath,
                            'X-Type': event.type
                        }
                    });
                }
            });
        });
    }
});

/**
 * @param {Array} patches
 * @nosideeffects
 * @return {Boolean}
 */
function arePatchesEmpty(patches) {
    for (var i = 0, ii = patches.length; i < ii; i++) {
        if (patches[i].diffs.length > 0) {
            return false;
        }
    }
    return true;
}

/**
 * @param {Function} onSuccess
 */
function getLastStylesheetURL(onSuccess) {
    lastStylesheetURL = '';
    chrome.devtools.inspectedWindow.eval('(function() {\n\
    var links = document.head.querySelectorAll("link[rel=stylesheet][href]");\n\
    var last = links[links.length - 1];\n\
    return last && last.href})()', function(href, fail) {
        if (fail || !href) {
            throw new Error('Cannot find link[rel=stylesheet][href] in the head.');
        }
        lastStylesheetURL = href;
        onSuccess(href);
    });
}

/**
 * @param {Resource} resource
 */
function addResource(resource) {
    var url = resource.url;
    if (!url || url === 'about:blank') {
        return;
    }
    switch (resource.type) {
        case 'stylesheet':
        case 'script':
            resource.getContent(function(content) {
                resourceMap.set(url, content);
            });
            console.info(url, 'loaded');
            break;
    }
}

function getAllResources() {
    console.info('Loading all scripts and stylesheets');
    resourceMap = new ResourceMap();
    chrome.devtools.inspectedWindow.getResources(function(resources) {
        resources.forEach(addResource);
    });
}

getAllResources();

chrome.devtools.inspectedWindow.onResourceAdded.addListener(addResource);

chrome.devtools.network.onNavigated.addListener(function() {
    console.info('A page reloaded');
    addedCSS = '';
});
<|endoftext|>


<commit_before>UI.body.rendered = function() {
  // The global application namespace.
  window.App = window.App || {};

  App.container = $(document);

  App.triggerEvent = function(name, object) {
    App.container.trigger(name, object);
  };

  App.pushKey = function(keycode) {
    var e = $.Event('keydown');
    e.which = e.keyCode = App.key[keycode];
    App.container.trigger(e);
  };

  // Another namespace to hold all the graphics stuff.
  var three = App.three = App.three || {};

  // Initialize rendering engine.
  // WebGLRenderer()  - the fastest and prettiest, but doesn't work on
  // most phones and older browsers.
  // CanvasRenderer() - much wider support, but much slower.
  // SVGRenderer()    - generally terrible in my own experience.
  var renderer = three.renderer = null;
  if (!!window.WebGLRenderingContext) {
    // TODO: this ends up being a false positive on my Galaxy Nexus.
    // Needs a better conditional.
    renderer = new THREE.WebGLRenderer();
  } else {
    renderer = new THREE.CanvasRenderer();
  }

  // // Set the renderer size to the entire available width and height.
  renderer.setSize(
    window.innerWidth,
    window.innerHeight
  );
  $('#game').append(renderer.domElement);

  // Create a new scene.
  var scene = three.scene = new THREE.Scene();

  // Create a new PerspectiveCamera:
  // http://threejs.org/docs/#Reference/Cameras/PerspectiveCamera
  var camera = three.camera = new THREE.PerspectiveCamera(
    45, window.innerWidth / window.innerHeight, 0.01, 1000
  );
  // Align the camera to view our spaceship from roughly isometric perspective.
  camera.position.x = 2;
  camera.position.y = 2;
  camera.position.z = 2;

  camera.rotation.x = -1.0;
  camera.rotation.y = 0.7;
  camera.rotation.z = 0.5;

  // Automagically resize the renderer and update the camera on window resize:
  // http://learningthreejs.com/blog/2011/08/30/window-resize-for-your-demos/
  THREEx.WindowResize(renderer, camera);

  // A vector of functions to execute each time the render loop is executed.
  var onRenderFcts = three.onRenderFcts = [];

  // The main render function.
  onRenderFcts.push(function() {
    renderer.render(scene, camera);
  });

  // The render loop.
  var lastTimeMsec = null;
  requestAnimationFrame(function animate(nowMsec) {
    // Keep looping.
    requestAnimationFrame(animate);

    // Measure time.
    lastTimeMsec = lastTimeMsec || nowMsec - 1000 / 60;
    var deltaMsec = Math.min(200, nowMsec - lastTimeMsec);
    lastTimeMsec = nowMsec;

    // Call each update function.
    onRenderFcts.forEach(function(onRenderFct) {
      onRenderFct(deltaMsec / 1000, nowMsec / 1000);
    });
  });

  // // Camera Controls.
  // var mouse = {
  //   x: 0,
  //   y: 0
  // };
  //
  // document.addEventListener('mousemove', function(event) {
  //   mouse.x = (event.clientX / window.innerWidth) - 0.5;
  //   mouse.y = (event.clientY / window.innerHeight) - 0.5;
  // }, false);
  //
  // onRenderFcts.push(function(delta, now) {
  //   camera.position.x += (mouse.x * 5 - camera.position.x) * (delta * 3);
  //   camera.position.y += (mouse.y * 5 - camera.position.y) * (delta * 3);
  //   camera.lookAt(scene.position);
  // });

  Ships.find().observe({
    added: function(ship) {
      THREEx.SpaceShips.loadSpaceFighter03(function(object3d) {
        var spaceship = App.three.spaceship = object3d;

        spaceship._id = ship._id;
        spaceship.position = ship.position;
        scene.add(App.three.spaceship);

        App.triggerEvent('shipLoaded', ship);

        setInterval(function() {
          var spaceship = _.pick(App.three.spaceship, '_id', 'position');
          Ships.update(spaceship._id, spaceship);
        }, 1000);
      });

      App.triggerEvent('shipAdded', ship);
    }
  });

  updateShip = function(ship) {
    App.three.spaceship.position = ship.position;
    shipStream.emit('updateShip', ship);

    App.triggerEvent('shipChanged', ship);
  };

  shipStream.on('updateShip', function(ship) {
    App.three.spaceship.position = ship.position;

    App.triggerEvent('shipChanged', ship);
  });

  App.container.keydown(function(e) {
    var spaceship = _.pick(App.three.spaceship, '_id', 'position');

    switch(e.keyCode) {
    case App.key.left:
    case App.key.a:
      spaceship.position.x += 0.1;
      break;
    case App.key.right:
    case App.key.d:
      spaceship.position.x -= 0.1;
      break;
    case App.key.up:
    case App.key.w:
      spaceship.position.z += 0.1;
      break;
    case App.key.down:
    case App.key.s:
      spaceship.position.z -= 0.1;
      break;
    }

    updateShip(spaceship);
  });
};
<commit_msg>Reposition camera, make it follow the ship<commit_after>UI.body.rendered = function() {
  // The global application namespace.
  window.App = window.App || {};

  App.container = $(document);

  App.triggerEvent = function(name, object) {
    App.container.trigger(name, object);
  };

  App.pushKey = function(keycode) {
    var e = $.Event('keydown');
    e.which = e.keyCode = App.key[keycode];
    App.container.trigger(e);
  };

  // Another namespace to hold all the graphics stuff.
  var three = App.three = App.three || {};

  // Initialize rendering engine.
  // WebGLRenderer()  - the fastest and prettiest, but doesn't work on
  // most phones and older browsers.
  // CanvasRenderer() - much wider support, but much slower.
  // SVGRenderer()    - generally terrible in my own experience.
  var renderer = three.renderer = null;
  if (!!window.WebGLRenderingContext) {
    // TODO: this ends up being a false positive on my Galaxy Nexus.
    // Needs a better conditional.
    renderer = new THREE.WebGLRenderer();
  } else {
    renderer = new THREE.CanvasRenderer();
  }

  // // Set the renderer size to the entire available width and height.
  renderer.setSize(
    window.innerWidth,
    window.innerHeight
  );
  $('#game').append(renderer.domElement);

  // Create a new scene.
  var scene = three.scene = new THREE.Scene();

  // Create a new PerspectiveCamera:
  // http://threejs.org/docs/#Reference/Cameras/PerspectiveCamera
  var camera = three.camera = new THREE.PerspectiveCamera(
    45, window.innerWidth / window.innerHeight, 0.01, 1000
  );
  camera.position.x = 0;
  camera.position.y = 2.0;
  camera.position.z = -2.5;

  camera.rotation.x = 0.5;
  camera.rotation.y = 3.15;
  camera.rotation.z = 0.0;

  // Automagically resize the renderer and update the camera on window resize:
  // http://learningthreejs.com/blog/2011/08/30/window-resize-for-your-demos/
  THREEx.WindowResize(renderer, camera);

  // A vector of functions to execute each time the render loop is executed.
  var onRenderFcts = three.onRenderFcts = [];

  // The main render function.
  onRenderFcts.push(function() {
    renderer.render(scene, camera);
  });

  // The render loop.
  var lastTimeMsec = null;
  requestAnimationFrame(function animate(nowMsec) {
    // Keep looping.
    requestAnimationFrame(animate);

    // Measure time.
    lastTimeMsec = lastTimeMsec || nowMsec - 1000 / 60;
    var deltaMsec = Math.min(200, nowMsec - lastTimeMsec);
    lastTimeMsec = nowMsec;

    // Call each update function.
    onRenderFcts.forEach(function(onRenderFct) {
      onRenderFct(deltaMsec / 1000, nowMsec / 1000);
    });
  });

  // Camera Controls.
  var mouse = {
    x: 0,
    y: 0
  };

  document.addEventListener('mousemove', function(event) {
    mouse.x = (event.clientX / window.innerWidth) - 0.5;
    mouse.y = (event.clientY / window.innerHeight) - 0.5;
  }, false);

  // onRenderFcts.push(function(delta, now) {
  //   // camera.position.x += (mouse.x * 5 - camera.position.x) * (delta * 3);
  //   // camera.position.y += (mouse.y * 5 - camera.position.y) * (delta * 3);
  //   camera.lookAt(App.three.spaceship.position);
  // });

  Ships.find().observe({
    added: function(ship) {
      THREEx.SpaceShips.loadSpaceFighter03(function(object3d) {
        var spaceship = App.three.spaceship = object3d;

        spaceship._id = ship._id;
        spaceship.position = ship.position;
        scene.add(App.three.spaceship);

        App.triggerEvent('shipLoaded', ship);

        setInterval(function() {
          var spaceship = _.pick(App.three.spaceship, '_id', 'position');
          Ships.update(spaceship._id, spaceship);
        }, 1000);
      });

      App.triggerEvent('shipAdded', ship);
    }
  });

  updateShip = function(ship) {
    App.three.spaceship.position = ship.position;
    shipStream.emit('updateShip', ship);

    App.triggerEvent('shipChanged', ship);
  };

  shipStream.on('updateShip', function(ship) {
    App.three.spaceship.position = ship.position;

    App.triggerEvent('shipChanged', ship);
  });

  App.container.keydown(function(e) {
    var spaceship = _.pick(App.three.spaceship, '_id', 'position');
    var camera = App.three.camera;

    switch(e.keyCode) {
    case App.key.left:
    case App.key.a:
      spaceship.position.x += 0.1;
      camera.position.x += 0.1;
      break;
    case App.key.right:
    case App.key.d:
      spaceship.position.x -= 0.1;
      camera.position.x -= 0.1;
      break;
    case App.key.up:
    case App.key.w:
      spaceship.position.z += 0.1;
      camera.position.z += 0.1;
      break;
    case App.key.down:
    case App.key.s:
      spaceship.position.z -= 0.1;
      camera.position.z -= 0.1;
      break;
    }

    updateShip(spaceship);
  });
};
<|endoftext|>


<commit_before>const { makeServer } = require('../main');
const commander = require('commander');
const path = require('path');
const logger = require('@cardstack/plugin-utils/logger');
const log = logger('server');
const fs = require('fs');

async function runServer(options, seedModels) {
  let {
    sessionsKey,
    port,
    allowDevDependencies
  } = options;
  let app = await makeServer(process.cwd(), sessionsKey, seedModels, {
    allowDevDependencies
  });
  app.listen(port);
  log.info("server listening on %s", port);
}

function commandLineOptions() {
  commander
    .usage('[options] <seed-config-directory>')
    .option('-p --port <port>', 'Server listen port.', 3000)
    .option('-d --allow-dev-dependencies', 'Allow the hub to load devDependencies.', 3000)
    .parse(process.argv);

  if (commander.args.length < 1) {
    commander.outputHelp();
    process.exit(-1);
  }

  commander.seedConfigDirectory = path.resolve(commander.args[0]);

  let base64Key = process.env.CARDSTACK_SESSIONS_KEY;
  let base64KeyPath = process.env.CARDSTACK_SESSIONS_KEY_FILE;
  if (base64Key) {
    commander.sessionsKey = new Buffer(base64Key, 'base64');
  } else if (base64KeyPath) {
    try {
      base64Key = fs.readFileSync(base64KeyPath, 'utf8');
    } catch (e) {
      process.stderr.write(`Could not read the file specified by CARDSTACK_SESSIONS_KEY_FILE (${base64KeyPath}).\n`);
      process.exit(1);
    }
    commander.sessionsKey = new Buffer(base64Key, 'base64');
  } else {
    process.stderr.write("You must provide a CardStack session encryption secret, via the CARDSTACK_SESSIONS_KEY or CARDSTACK_SESSIONS_KEY_FILE environment variables. You can generate one by running @cardstack/hub/bin/generate-key.js\n");
    process.exit(-1);
  }

  return commander;
}

function loadSeedModels(options) {
  try {
    return fs.readdirSync(options.seedConfigDirectory).map(filename => require(path.join(options.seedConfigDirectory, filename))).reduce((a,b) => a.concat(b), []);
  } catch (err) {
    process.stderr.write(`Unable to load models from your seed-config-file (${options.seedConfigFile}), ${err}\n`);
    process.exit(-1);
  }
}

process.on('warning', (warning) => {
  process.stderr.write(warning.stack);
});

let options = commandLineOptions();
let seedModels = loadSeedModels(options);
runServer(options, seedModels);
<commit_msg>defend against stray files in seeds directory<commit_after>const { makeServer } = require('../main');
const commander = require('commander');
const path = require('path');
const logger = require('@cardstack/plugin-utils/logger');
const log = logger('server');
const fs = require('fs');

async function runServer(options, seedModels) {
  let {
    sessionsKey,
    port,
    allowDevDependencies
  } = options;
  let app = await makeServer(process.cwd(), sessionsKey, seedModels, {
    allowDevDependencies
  });
  app.listen(port);
  log.info("server listening on %s", port);
}

function commandLineOptions() {
  commander
    .usage('[options] <seed-config-directory>')
    .option('-p --port <port>', 'Server listen port.', 3000)
    .option('-d --allow-dev-dependencies', 'Allow the hub to load devDependencies.', 3000)
    .parse(process.argv);

  if (commander.args.length < 1) {
    commander.outputHelp();
    process.exit(-1);
  }

  commander.seedConfigDirectory = path.resolve(commander.args[0]);

  let base64Key = process.env.CARDSTACK_SESSIONS_KEY;
  let base64KeyPath = process.env.CARDSTACK_SESSIONS_KEY_FILE;
  if (base64Key) {
    commander.sessionsKey = new Buffer(base64Key, 'base64');
  } else if (base64KeyPath) {
    try {
      base64Key = fs.readFileSync(base64KeyPath, 'utf8');
    } catch (e) {
      process.stderr.write(`Could not read the file specified by CARDSTACK_SESSIONS_KEY_FILE (${base64KeyPath}).\n`);
      process.exit(1);
    }
    commander.sessionsKey = new Buffer(base64Key, 'base64');
  } else {
    process.stderr.write("You must provide a CardStack session encryption secret, via the CARDSTACK_SESSIONS_KEY or CARDSTACK_SESSIONS_KEY_FILE environment variables. You can generate one by running @cardstack/hub/bin/generate-key.js\n");
    process.exit(-1);
  }

  return commander;
}

function loadSeedModels(options) {
  try {
    return fs.readdirSync(options.seedConfigDirectory).map(filename => {
      if (/\.js$/.test(filename)) {
        return require(path.join(options.seedConfigDirectory, filename));
      } else {
        return [];
      }
    }).reduce((a,b) => a.concat(b), []);
  } catch (err) {
    process.stderr.write(`Unable to load models from your seed-config-file (${options.seedConfigFile}), ${err}\n`);
    process.exit(-1);
  }
}

process.on('warning', (warning) => {
  process.stderr.write(warning.stack);
});

let options = commandLineOptions();
let seedModels = loadSeedModels(options);
runServer(options, seedModels);
<|endoftext|>


<commit_before>/**
    * @ngdoc service
    * @name umbraco.resources.memberTypeResource
    * @description Loads in data for member types
    **/
function memberTypeResource($q, $http, umbRequestHelper) {

    return {

        //return all member types
        getTypes: function () {

            return umbRequestHelper.resourcePromise(
               $http.get(
                   umbRequestHelper.getApiUrl(
                       "memberTypeApiBaseUrl",
                       "GetAllTypes")),
               'Failed to retreive data for member types id');
        }

    };
}
angular.module('umbraco.resources').factory('memberTypeResource', memberTypeResource);<commit_msg>Replaced "retreive" with "retrieve".<commit_after>/**
    * @ngdoc service
    * @name umbraco.resources.memberTypeResource
    * @description Loads in data for member types
    **/
function memberTypeResource($q, $http, umbRequestHelper) {

    return {

        //return all member types
        getTypes: function () {

            return umbRequestHelper.resourcePromise(
               $http.get(
                   umbRequestHelper.getApiUrl(
                       "memberTypeApiBaseUrl",
                       "GetAllTypes")),
               'Failed to retrieve data for member types id');
        }

    };
}
angular.module('umbraco.resources').factory('memberTypeResource', memberTypeResource);
<|endoftext|>


<commit_before>import regeneratorRuntime from "regenerator-runtime/runtime";

import queueable from './index';

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function sleep(fn, ms = 100) {
  return timeout(ms).then(fn).catch(console.error);
}

async function add(n = 0, target = [], latency = 250) {
  await timeout(latency);
  return [...target, n];
}

jest.setTimeout(5000);

let target = [];
let executions = 0;
let counter = 0;
let promises = [];

const doSth = async () => {
  executions++;
  let x = counter;
  counter++;
  await timeout(100);
  target.push(x);
}

test('returns a function', async () => {
  const qadd = queueable(add);
  expect(typeof qadd).toBe('function');
});

test('queues execution of promises', async () => {
  counter = 0;
  executions = 0;
  promises = [];
  target = [];

  const qDoSth = queueable(doSth);

  for (let i = 0; i < 10; i++) {
    promises.push(qDoSth());
  }

  await Promise.all(promises);

  const res = target.join(',');

  // if the execution would not be queued, the result would be
  // 0,0,0,0,0,0,0,0,0,0
  expect(res).toBe('0,1,2,3,4,5,6,7,8,9');
})

test('handles concurrency of promises', async () => {
  counter = 0;
  executions = 0;
  promises = [];
  target = [];

  const qDoSth = queueable(doSth, {  concurrency: 5 });

  for (let i = 0; i < 10; i++) {
    promises.push(qDoSth());
  }

  const t = Date.now();
  await Promise.all(promises);
  const duration = Date.now() - t;

  const res = target.join(',');

  // when running 5 qDoSth in parallel, they resolve within ~100m
  // therefor when we fire 10 calls, they should be done within
  // ~200ms
  expect(duration >= 200).toBe(true);
  expect(duration <= 330).toBe(true);
})

test('can be used as decorator', async () => {
  counter = 0;
  executions = 0;
  promises = [];
  target = [];

  class Demo {
    @queueable
    async d(...params) {
      return doSth(...params);
    }
  }

  const d = new Demo();

  for (let i = 0; i < 10; i++) {
    promises.push(d.d());
  }

  const t = Date.now();
  await Promise.all(promises);
  const duration = Date.now() - t;

  const res = target.join(',');

  expect(res).toBe('0,1,2,3,4,5,6,7,8,9');
})

test('throws when decorator is used with options', async () => {
  expect(() => {
    class Demo {
      @queueable(5)
      async d(...params) {
        return doSth(...params);
      }
    }

    const d = new Demo();
  }).toThrow();
})

test('continues queue even when errors are thrown', async () => {
  let counter = 0;

  function illThrow() {
    counter += 1;
    throw new Error(1);
  }

  const queuedThrower = queueable(illThrow, { concurrency: 1 });

  const amount = 3;

  for (let i = 0; i < amount; i++) {
    try {
      await queuedThrower();
    } catch (err) {
      expect(err).toBeInstanceOf(Error);
    }
  }

  expect(counter).toBe(amount);
})<commit_msg>fix: concurrency test time calculation more predictable<commit_after>import regeneratorRuntime from "regenerator-runtime/runtime";

import queueable from './index';

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function sleep(fn, ms = 100) {
  return timeout(ms).then(fn).catch(console.error);
}

async function add(n = 0, target = [], latency = 250) {
  await timeout(latency);
  return [...target, n];
}

jest.setTimeout(5000);

let target = [];
let executions = 0;
let counter = 0;
let promises = [];

const doSth = async () => {
  executions++;
  let x = counter;
  counter++;
  await timeout(100);
  target.push(x);
}

test('returns a function', async () => {
  const qadd = queueable(add);
  expect(typeof qadd).toBe('function');
});

test('queues execution of promises', async () => {
  counter = 0;
  executions = 0;
  promises = [];
  target = [];

  const qDoSth = queueable(doSth);

  for (let i = 0; i < 10; i++) {
    promises.push(qDoSth());
  }

  await Promise.all(promises);

  const res = target.join(',');

  // if the execution would not be queued, the result would be
  // 0,0,0,0,0,0,0,0,0,0
  expect(res).toBe('0,1,2,3,4,5,6,7,8,9');
})

test('handles concurrency of promises', async () => {
  counter = 0;
  executions = 0;
  promises = [];
  target = [];

  const qDoSth = queueable(doSth, {  concurrency: 5 });
  const t = Date.now();

  for (let i = 0; i < 10; i++) {
    promises.push(qDoSth());
  }

  await Promise.all(promises);
  const duration = Date.now() - t;

  const res = target.join(',');

  // when running 5 qDoSth in parallel, they resolve within ~100m
  // therefor when we fire 10 calls, they should be done within
  // ~200ms
  expect(duration >= 200).toBe(true);
  expect(duration <= 330).toBe(true);
})

test('can be used as decorator', async () => {
  counter = 0;
  executions = 0;
  promises = [];
  target = [];

  class Demo {
    @queueable
    async d(...params) {
      return doSth(...params);
    }
  }

  const d = new Demo();

  for (let i = 0; i < 10; i++) {
    promises.push(d.d());
  }

  const t = Date.now();
  await Promise.all(promises);
  const duration = Date.now() - t;

  const res = target.join(',');

  expect(res).toBe('0,1,2,3,4,5,6,7,8,9');
})

test('throws when decorator is used with options', async () => {
  expect(() => {
    class Demo {
      @queueable(5)
      async d(...params) {
        return doSth(...params);
      }
    }

    const d = new Demo();
  }).toThrow();
})

test('continues queue even when errors are thrown', async () => {
  let counter = 0;

  function illThrow() {
    counter += 1;
    throw new Error(1);
  }

  const queuedThrower = queueable(illThrow, { concurrency: 1 });

  const amount = 3;

  for (let i = 0; i < amount; i++) {
    try {
      await queuedThrower();
    } catch (err) {
      expect(err).toBeInstanceOf(Error);
    }
  }

  expect(counter).toBe(amount);
})
<|endoftext|>


<commit_before>function create() {
    return [0, 0, 0, 0];
}

function equals(a,b) {
    return a[0] == b[0] &&
           a[1] == b[1] &&
           a[2] == b[2] &&
           a[3] == b[3];
}

function equals4(a,x,y,z,w){
    return a[0] == x &&
           a[1] == y &&
           a[2] == z &&
           a[3] == w;
}

function set(a,b){
    a[0] = b[0];
    a[1] = b[1];
    a[2] = b[2];
    a[3] = b[3];
    return a;
}
function set4(a,x,y,z,w){
    a[0] = x;
    a[1] = y;
    a[2] = z;
    a[3] = w;
    return a;
}

function copy(a,out){
    if(out !== undefined){
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        return out;
    }
    return a.slice(0);
}

var Vec4 = {
    create: create,
    set: set,
    set4: set4,
    copy: copy,
    equals: equals,
    equals4: equals4
};

module.exports = Vec4;
<commit_msg>Vec4 added fromVec3<commit_after>function create() {
    return [0, 0, 0, 0];
}

function equals(a,b) {
    return a[0] == b[0] &&
           a[1] == b[1] &&
           a[2] == b[2] &&
           a[3] == b[3];
}

function equals4(a,x,y,z,w){
    return a[0] == x &&
           a[1] == y &&
           a[2] == z &&
           a[3] == w;
}

function set(a,b){
    a[0] = b[0];
    a[1] = b[1];
    a[2] = b[2];
    a[3] = b[3];
    return a;
}

function set4(a,x,y,z,w){
    a[0] = x;
    a[1] = y;
    a[2] = z;
    a[3] = w;
    return a;
}

function fromVec3(a,b){
    a[0] = b[0];
    a[1] = b[1];
    a[2] = b[2];
    return a;
}

function copy(a,out){
    if(out !== undefined){
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        return out;
    }
    return a.slice(0);
}

var Vec4 = {
    create: create,
    set: set,
    set4: set4,
    fromVec3 : fromVec3,
    copy: copy,
    equals: equals,
    equals4: equals4
};

module.exports = Vec4;
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

var webpack = require('webpack');
var helpers = require('./helpers');

/**
 * Webpack Plugins
 */
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/**
 * Webpack Constants
 */
const METADATA = {
  title: 'Testing Angular 2 applications with Protractor & CucumberJS',
  baseUrl: '/',
};

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  // Static metadata for index.html
  //
  // See: (custom attribute)
  metadata: METADATA,

  // Cache generated modules and chunks to improve performance for multiple incremental builds.
  // This is enabled by default in watch mode.
  // You can pass false to disable it.
  //
  // See: http://webpack.github.io/docs/configuration.html#cache
  // cache: false,

  // The entry point for the bundle
  // Our Angular.js app
  //
  // See: http://webpack.github.io/docs/configuration.html#entry
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts',

  },

  // Options affecting the resolving of modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#resolve
  resolve: {

    // An array of extensions that should be used to resolve modules.
    //
    // See: http://webpack.github.io/docs/configuration.html#resolve-extensions
    extensions: ['', '.ts', '.js'],

    // Make sure root is src
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: ['node_modules'],

  },

  // Options affecting the normal modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#module
  module: {

    // An array of applied pre and post loaders.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
    preLoaders: [

      // Tslint loader support for *.ts files
      //
      // See: https://github.com/wbuchwalter/tslint-loader
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      // Source map loader support for *.js files
      // Extracts SourceMaps for source files that as added as sourceMappingURL comment.
      //
      // See: https://github.com/webpack/source-map-loader
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material'),
        ]
      },

    ],

    // An array of automatically applied loaders.
    //
    // IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
    // This means they are not resolved relative to the configuration file.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-loaders
    loaders: [

      // Typescript loader support for .ts and Angular 2 async routes via .async.ts
      //
      // See: https://github.com/s-panferov/awesome-typescript-loader
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/],
      },

      // Json loader support for *.json files.
      //
      // See: https://github.com/webpack/json-loader
      {
        test: /\.json$/,
        loader: 'json-loader',
      },

      // Raw loader support for *.css files
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.css$/,
        loader: 'raw-loader',
      },

      // Support for SCSS
      // To string loader support for *.scss files
      // Css loader support for *.scss files
      // Post css loader for *.scss files
      // Sass loader for *.scss files
      // Returns file content as string
      {
        test: /\.scss$/,
        exclude: helpers.root('node_modules'),
        loader: 'to-string!css-loader?-url!postcss-loader!sass-loader'
      },

      // Raw loader support for *.html
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [
          helpers.root('src/index.html'),
        ],
      },

      {
        test: /\.png$/,
        loader: "url-loader?limit=100000",
        exclude: [ helpers.root('node_modules') ]
      },

      {
        test: /\.jpg$/,
        loader: "file-loader",
        exclude: [ helpers.root('node_modules') ]
      },

      {
        test: /\.(woff2?|ttf|eot|svg)$/,
        loader: 'url?limit=10000',
      },

    ],

  },

  postcss: function () {
    return [require('autoprefixer')]
  },

  // Add additional plugins to the compiler.
  //
  // See: http://webpack.github.io/docs/configuration.html#plugins
  plugins: [

    // Plugin: ForkCheckerPlugin
    // Description: Do type checking in a separate process, so webpack don't need to wait.
    //
    // See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
    new ForkCheckerPlugin(),

    // Plugin: OccurenceOrderPlugin
    // Description: Varies the distribution of the ids to get the smallest id length
    // for often used ids.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
    // See: https://github.com/webpack/docs/wiki/optimization#minimize
    new webpack.optimize.OccurenceOrderPlugin(true),

    // Plugin: CommonsChunkPlugin
    // Description: Shares common code between the pages.
    // It identifies common modules and put them into a commons chunk.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    // See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
    new webpack.optimize.CommonsChunkPlugin({
      name: helpers.reverse(['polyfills', 'vendor', 'main']),
      minChunks: Infinity,
    }),

    // Plugin: CopyWebpackPlugin
    // Description: Copy files and directories in webpack.
    //
    // Copies project static assets.
    //
    // See: https://www.npmjs.com/package/copy-webpack-plugin
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets',
    }]),

    // Plugin: HtmlWebpackPlugin
    // Description: Simplifies creation of HTML files to serve your webpack bundles.
    // This is especially useful for webpack bundles that include a hash in the filename
    // which changes every compilation.
    //
    // See: https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: 'none',
    }),

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      _: 'lodash'
    }),

  ],

  // Include polyfills or mocks for various node stuff
  // Description: Node configuration
  //
  // See: https://webpack.github.io/docs/configuration.html#node
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false,
  },

};
<commit_msg>updated webpack config<commit_after>/**
 * @author: @AngularClass
 */

var webpack = require('webpack');
var helpers = require('./helpers');

/**
 * Webpack Plugins
 */
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/**
 * Webpack Constants
 */
const METADATA = {
  title: 'Testing Angular 2 applications with Protractor & CucumberJS',
  baseUrl: '/',
};

/**
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = {

  // Static metadata for index.html
  //
  // See: (custom attribute)
  metadata: METADATA,

  // Cache generated modules and chunks to improve performance for multiple incremental builds.
  // This is enabled by default in watch mode.
  // You can pass false to disable it.
  //
  // See: http://webpack.github.io/docs/configuration.html#cache
  // cache: false,

  // The entry point for the bundle
  // Our Angular.js app
  //
  // See: http://webpack.github.io/docs/configuration.html#entry
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'main': './src/main.browser.ts',

  },

  // Options affecting the resolving of modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#resolve
  resolve: {

    // An array of extensions that should be used to resolve modules.
    //
    // See: http://webpack.github.io/docs/configuration.html#resolve-extensions
    extensions: ['', '.ts', '.js'],

    // Make sure root is src
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: ['node_modules'],

  },

  // Options affecting the normal modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#module
  module: {

    // An array of applied pre and post loaders.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
    preLoaders: [

      // Tslint loader support for *.ts files
      //
      // See: https://github.com/wbuchwalter/tslint-loader
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      // Source map loader support for *.js files
      // Extracts SourceMaps for source files that as added as sourceMappingURL comment.
      //
      // See: https://github.com/webpack/source-map-loader
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material'),
        ]
      },

    ],

    // An array of automatically applied loaders.
    //
    // IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
    // This means they are not resolved relative to the configuration file.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-loaders
    loaders: [

      // Typescript loader support for .ts and Angular 2 async routes via .async.ts
      //
      // See: https://github.com/s-panferov/awesome-typescript-loader
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/],
      },

      // Json loader support for *.json files.
      //
      // See: https://github.com/webpack/json-loader
      {
        test: /\.json$/,
        loader: 'json-loader',
      },

      // Raw loader support for *.css files
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.css$/,
        loader: 'raw-loader',
      },

      // Support for SCSS
      // To string loader support for *.scss files
      // Css loader support for *.scss files
      // Post css loader for *.scss files
      // Sass loader for *.scss files
      // Returns file content as string
      {
        test: /\.scss$/,
        exclude: helpers.root('node_modules'),
        loader: 'to-string!css-loader?-url!postcss-loader!sass-loader'
      },

      // Raw loader support for *.html
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [
          helpers.root('src/index.html'),
        ],
      },

      {
        test: /\.png$/,
        loader: "url-loader?limit=100000",
        exclude: [ helpers.root('node_modules') ]
      },

      {
        test: /\.jpg$/,
        loader: "file-loader",
        exclude: [ helpers.root('node_modules') ]
      },

      {
        test: /\.(woff2?|ttf|eot|svg)$/,
        loader: 'url?limit=10000',
      },

    ],

  },

  postcss: function () {
    return [require('autoprefixer')]
  },

  // Add additional plugins to the compiler.
  //
  // See: http://webpack.github.io/docs/configuration.html#plugins
  plugins: [

    // Plugin: ForkCheckerPlugin
    // Description: Do type checking in a separate process, so webpack don't need to wait.
    //
    // See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
    new ForkCheckerPlugin(),

    // Plugin: OccurenceOrderPlugin
    // Description: Varies the distribution of the ids to get the smallest id length
    // for often used ids.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
    // See: https://github.com/webpack/docs/wiki/optimization#minimize
    new webpack.optimize.OccurenceOrderPlugin(true),

    // Plugin: CommonsChunkPlugin
    // Description: Shares common code between the pages.
    // It identifies common modules and put them into a commons chunk.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    // See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
    new webpack.optimize.CommonsChunkPlugin({
      name: helpers.reverse(['polyfills', 'vendor', 'main']),
      minChunks: Infinity,
    }),

    // Plugin: CopyWebpackPlugin
    // Description: Copy files and directories in webpack.
    //
    // Copies project static assets.
    //
    // See: https://www.npmjs.com/package/copy-webpack-plugin
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets',
    }]),

    // Plugin: HtmlWebpackPlugin
    // Description: Simplifies creation of HTML files to serve your webpack bundles.
    // This is especially useful for webpack bundles that include a hash in the filename
    // which changes every compilation.
    //
    // See: https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: helpers.packageSort(['polyfills', 'vendor', 'main'])
    }),

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      _: 'lodash'
    }),

  ],

  // Include polyfills or mocks for various node stuff
  // Description: Node configuration
  //
  // See: https://webpack.github.io/docs/configuration.html#node
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false,
  },

};
<|endoftext|>


<commit_before>// Parses "optimization_paramters" and 2-column sheets
// from GRNmap input or output workbook

var TWO_COL_SHEET_NAMES = [
    "production_rates",
    "degradation_rates",
    "threshold_b",
    "optimized_production_rates",
    "optimized_threshold_b"];

var parseMetaDataSheet = function (sheet) {
    var meta = {};
    sheet.data.forEach(function (element, index) {
        if (index !== 0) {
            var value = element.slice(1);
            // Extract element from array if array contains only 1 value
            meta[element[0]] = value.length > 1 ? value : value[0];
        }
    });
    return meta;
};

var parseTwoColumnSheet = function (sheet) {
    var data = {};
    sheet.data.forEach(function (element, index) {
        if (index !== 0) {
            data[element[0]] = element[1];
        }
    });
    return data;
};

module.exports = function (workbook) {
    var output = {
        meta: {},
        test: {} // 2-column data
    };
    workbook.forEach(function (sheet) {
        if (sheet.name === "optimization_parameters") {
            output["meta"] = parseMetaDataSheet(sheet);
        // Parse 2-column sheets
        } else if (TWO_COL_SHEET_NAMES.includes(sheet.name)) {
            output["test"][sheet.name] = parseTwoColumnSheet(sheet);
        }
    });
    return output;
};
<commit_msg>es6 changes<commit_after>// Parses "optimization_paramters" and 2-column sheets
// from GRNmap input or output workbook

const TWO_COL_SHEET_NAMES = [
    "production_rates",
    "degradation_rates",
    "threshold_b",
    "optimized_production_rates",
    "optimized_threshold_b"
];

const parseMetaDataSheet = (sheet) => {
    let meta = {};
    sheet.data.forEach(function (element, index) {
        if (index !== 0) {
            const value = element.slice(1);
            // Extract element from array if array contains only 1 value
            meta.element[0] = value.length > 1 ? value : value[0];
        }
    });
    return meta;
};

const parseTwoColumnSheet = (sheet) => {
    let data = {};
    sheet.data.forEach(function (element, index) {
        if (index !== 0) {
            data[element[0]] = element[1];
        }
    });
    return data;
};

module.exports = function (workbook) {
    let output = {
        meta: {},
        test: {} // 2-column data
    };
    workbook.forEach(function (sheet) {
        if (sheet.name === "optimization_parameters") {
            output.meta = parseMetaDataSheet(sheet);
        // Parse 2-column sheets
        } else if (TWO_COL_SHEET_NAMES.includes(sheet.name)) {
            output["test"][sheet.name] = parseTwoColumnSheet(sheet);
        }
    });
    return output;
};
<|endoftext|>


<commit_before>var SC = new Object();

SC.asyncSubmit = function(form, options) {
    var f = $(form);
    new Ajax.Request(f.action, $H(options).merge({
        asynchronous: true,
        parameters: Form.serialize(f)
    }).toObject())
}

SC.asyncLink = function(anchor, options, indicator) {
    var a = $(anchor)
    Event.observe(a, "click", function(e) {
        Event.stop(e);
        SC.doAsyncLink(anchor, options, indicator)
    })
}

SC.doAsyncLink = function(anchor, options, indicator) {
    var a = $(anchor)
    if (indicator) { $(indicator).reveal() }
    new Ajax.Request(a.href, Object.extend({
        asynchronous: true,
        onComplete: function() {
            if (indicator) { $(indicator).conceal() }
        }
    }, options));
}

SC.SessionExpiredLogic = Class.create( {
    initialize: function(url) {
        this.url = url
        this.content =
            Builder.node('div', {id:'lightbox-content'}, [
                Builder.node('h1', 'Session Timed Out'),
                Builder.node('p', 'Your session has expired.  To continue, please ', [
                        Builder.node('a', {href:this.url}, 'log in again.')
                        ])
                ])
    },
    execute: function() {
        $('lightbox').update(this.content)
        LB.Lightbox.activate()
    }
})

SC.UserActiveChallenge = Class.create( {
    initialize: function(url) {
        this.url = url
        this.content =
            Builder.node('div', {id:'lightbox-content'}, [
                    Builder.node('form', {method:'post', action:this.url, id:'ping'}, [
                            Builder.node('h1', 'Your Session is About to Expire'),
                            Builder.node('p', 'Please confirm that you are still active by clicking the button below.'),
                            Builder.node('input', {type:'submit', value:'Confirm Active', id:'user-active-button'})
                            ])
                    ])
    },
    execute: function() {
        $('lightbox').update(this.content)
        this.add_submit_listener()

        LB.Lightbox.activate()
    },
    add_submit_listener: function() {
        Event.observe('ping', 'submit', function(e) {
            Event.stop(e);
            SC.asyncSubmit('ping', {
                onLoaded: function() {
                    LB.Lightbox.deactivate()
                }
            })
        })
    }
})

SC.SessionTimer = Class.create(PeriodicalExecuter, {
    initialize: function($super, expire_logic, time_in_seconds) {
        $super(this.expire, time_in_seconds)
        this.expire_logic = expire_logic
    },
    reset: function() {
        this.stop()
        this.registerCallback()
    },
    expire: function() {
        this.expire_logic.execute()
        this.stop()
    }
})

SC.HttpSessionExpirationManager = Class.create({
    initialize: function(session_warning_in_seconds, session_timeout_in_seconds, session_alive_url, login_url) {
        this.timers = []

        if (session_warning_in_seconds > 0) {
            this.userChallengeTimer =
               new SC.SessionTimer(new SC.UserActiveChallenge(session_alive_url), session_warning_in_seconds)

            this.timers.push(this.userChallengeTimer)
        }

        if (session_timeout_in_seconds > 0) {
            this.httpSessionTimer =
                new SC.SessionTimer(new SC.SessionExpiredLogic(login_url), session_timeout_in_seconds)

            this.timers.push(this.httpSessionTimer)
        }

        Ajax.Responders.register({
            timers:this.timers,
            onComplete: function() {
                this.timers.each(function(timer) {
                    timer.reset()
                })
            }
        })
    }
})

////// COOKIES

/** Main fns based on http://www.quirksmode.org/js/cookies.html */
var Cookies = {
    add: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    get: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    },

    clear: function(name) {
        Cookies.add(name, "", -1);
    },

    set: function(name, value, days) {
        Cookies.clear(name)
        Cookies.add(name, value, days)
    }
}

////// PROTOTYPE EXTENSIONS

Element.addMethods( {
    // Like prototype's hide(), but uses the visibility CSS prop instead of display
    conceal: function() {
        for (var i = 0; i < arguments.length; i++) {
          var element = $(arguments[i]);
          element.style.visibility = 'hidden';
        }
    },

    // Like prototype's show(), but uses the visibility CSS prop instead of display
    reveal: function() {
        for (var i = 0; i < arguments.length; i++) {
          var element = $(arguments[i]);
          element.style.visibility = 'visible';
        }
    }
} );

// Extend Prototype Form object to have toggle checkboxes method
Form.Methods.checkCheckboxes = function(form, checkboxName) {
    Form.Methods.setCheckboxesChecked(form, checkboxName, true)
}
Form.Methods.uncheckCheckboxes = function(form, checkboxName) {
    Form.Methods.setCheckboxesChecked(form, checkboxName, false)
}
//Form.Methods.setCheckboxesChecked = function(form, checkboxName, isChecked) {
//    var events = $(form).getInputs('checkbox',checkboxName)
//    events.each(function(event) {
//        event.checked = isChecked;
//    })
//    return form
//}
Form.Methods.setCheckboxesChecked = function(form, checkboxName, isChecked) {
    var events = $$("#" + form.id + " input." + checkboxName)
    events.each(function(event) {
        event.checked = isChecked;
    })
    return form
}

Element.addMethods();

////// DOM EXTENSIONS

// Adds an IE-like click() fn for other browsers
if (!document.all && HTMLElement && !HTMLElement.prototype.click) {
    HTMLElement.prototype.click = function() {
        var evt = this.ownerDocument.createEvent('MouseEvents');
        // evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
        evt.initEvent("click", true, true);
        this.dispatchEvent(evt);
    }
}

////// SSO

Event.observe(window, "load", function() {
    $$("a.sso").each(function(a) {
        Event.observe(a, "click", function(e) {
            Event.stop(e)
            var ssoForm = $('sso-form')
            ssoForm.action = a.href
            ssoForm.submit()
        })
    })
})

function registerHeaderCollapse() {
    $$(".collapsible").each(function(section) {
        var header = section.getElementsByTagName("H2")[0]
        header.innerHTML += " +"
        header.title = "Click to reveal"
        Event.observe(header, 'click', function() {
            var content = section.getElementsByClassName("content")[0]
            var icon = section.getElementsByClassName("collapse-icon")[0]
            if (content.visible()) {
                SC.slideAndHide(content, {
                    afterFinish: function() {
                        header.title = "Click to reveal form"
                        Element.update(icon, '+')
                    }
                });
            } else {
                SC.slideAndShow(content, {
                    afterFinish: function() {
                        header.title = "Click to conceal form"
                        Element.update(icon, '-')
                    }
                });
            }
        })
    })
}<commit_msg>Small fix to make sure multiple observers don't get registered for "Confirm Active" submit action.<commit_after>var SC = new Object();

SC.asyncSubmit = function(form, options) {
    var f = $(form);
    new Ajax.Request(f.action, $H(options).merge({
        asynchronous: true,
        parameters: Form.serialize(f)
    }).toObject())
}

SC.asyncLink = function(anchor, options, indicator) {
    var a = $(anchor)
    Event.observe(a, "click", function(e) {
        Event.stop(e);
        SC.doAsyncLink(anchor, options, indicator)
    })
}

SC.doAsyncLink = function(anchor, options, indicator) {
    var a = $(anchor)
    if (indicator) { $(indicator).reveal() }
    new Ajax.Request(a.href, Object.extend({
        asynchronous: true,
        onComplete: function() {
            if (indicator) { $(indicator).conceal() }
        }
    }, options));
}

SC.SessionExpiredLogic = Class.create( {
    initialize: function(url) {
        this.url = url
        this.content =
            Builder.node('div', {id:'lightbox-content'}, [
                Builder.node('h1', 'Session Timed Out'),
                Builder.node('p', 'Your session has expired.  To continue, please ', [
                        Builder.node('a', {href:this.url}, 'log in again.')
                        ])
                ])
    },
    execute: function() {
        $('lightbox').update(this.content)
        LB.Lightbox.activate()
    }
})

SC.UserActiveChallenge = Class.create( {
    initialize: function(url) {
        this.url = url
        this.content =
            Builder.node('div', {id:'lightbox-content'}, [
                    Builder.node('form', {method:'post', action:this.url, id:'ping'}, [
                            Builder.node('h1', 'Your Session is About to Expire'),
                            Builder.node('p', 'Please confirm that you are still active by clicking the button below.'),
                            Builder.node('input', {type:'submit', value:'Confirm Active', id:'user-active-button'})
                            ])
                    ])
    },
    execute: function() {
        $('lightbox').update(this.content)
        this.add_submit_listener()

        LB.Lightbox.activate()
    },
    add_submit_listener: function() {
        Event.stopObserving('ping', 'submit')
        Event.observe('ping', 'submit', function(e) {
            Event.stop(e);
            SC.asyncSubmit('ping', {
                onLoaded: function() {
                    LB.Lightbox.deactivate()
                }
            })
        })
    }
})

SC.SessionTimer = Class.create(PeriodicalExecuter, {
    initialize: function($super, expire_logic, time_in_seconds) {
        $super(this.expire, time_in_seconds)
        this.expire_logic = expire_logic
    },
    reset: function() {
        this.stop()
        this.registerCallback()
    },
    expire: function() {
        this.expire_logic.execute()
        this.stop()
    }
})

SC.HttpSessionExpirationManager = Class.create({
    initialize: function(session_warning_in_seconds, session_timeout_in_seconds, session_alive_url, login_url) {
        this.timers = []

        if (session_warning_in_seconds > 0) {
            this.userChallengeTimer =
               new SC.SessionTimer(new SC.UserActiveChallenge(session_alive_url), session_warning_in_seconds)

            this.timers.push(this.userChallengeTimer)
        }

        if (session_timeout_in_seconds > 0) {
            this.httpSessionTimer =
                new SC.SessionTimer(new SC.SessionExpiredLogic(login_url), session_timeout_in_seconds)

            this.timers.push(this.httpSessionTimer)
        }

        Ajax.Responders.register({
            timers:this.timers,
            onComplete: function() {
                this.timers.each(function(timer) {
                    timer.reset()
                })
            }
        })
    }
})

////// COOKIES

/** Main fns based on http://www.quirksmode.org/js/cookies.html */
var Cookies = {
    add: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    get: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    },

    clear: function(name) {
        Cookies.add(name, "", -1);
    },

    set: function(name, value, days) {
        Cookies.clear(name)
        Cookies.add(name, value, days)
    }
}

////// PROTOTYPE EXTENSIONS

Element.addMethods( {
    // Like prototype's hide(), but uses the visibility CSS prop instead of display
    conceal: function() {
        for (var i = 0; i < arguments.length; i++) {
          var element = $(arguments[i]);
          element.style.visibility = 'hidden';
        }
    },

    // Like prototype's show(), but uses the visibility CSS prop instead of display
    reveal: function() {
        for (var i = 0; i < arguments.length; i++) {
          var element = $(arguments[i]);
          element.style.visibility = 'visible';
        }
    }
} );

// Extend Prototype Form object to have toggle checkboxes method
Form.Methods.checkCheckboxes = function(form, checkboxName) {
    Form.Methods.setCheckboxesChecked(form, checkboxName, true)
}
Form.Methods.uncheckCheckboxes = function(form, checkboxName) {
    Form.Methods.setCheckboxesChecked(form, checkboxName, false)
}
//Form.Methods.setCheckboxesChecked = function(form, checkboxName, isChecked) {
//    var events = $(form).getInputs('checkbox',checkboxName)
//    events.each(function(event) {
//        event.checked = isChecked;
//    })
//    return form
//}
Form.Methods.setCheckboxesChecked = function(form, checkboxName, isChecked) {
    var events = $$("#" + form.id + " input." + checkboxName)
    events.each(function(event) {
        event.checked = isChecked;
    })
    return form
}

Element.addMethods();

////// DOM EXTENSIONS

// Adds an IE-like click() fn for other browsers
if (!document.all && HTMLElement && !HTMLElement.prototype.click) {
    HTMLElement.prototype.click = function() {
        var evt = this.ownerDocument.createEvent('MouseEvents');
        // evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
        evt.initEvent("click", true, true);
        this.dispatchEvent(evt);
    }
}

////// SSO

Event.observe(window, "load", function() {
    $$("a.sso").each(function(a) {
        Event.observe(a, "click", function(e) {
            Event.stop(e)
            var ssoForm = $('sso-form')
            ssoForm.action = a.href
            ssoForm.submit()
        })
    })
})

function registerHeaderCollapse() {
    $$(".collapsible").each(function(section) {
        var header = section.getElementsByTagName("H2")[0]
        header.innerHTML += " +"
        header.title = "Click to reveal"
        Event.observe(header, 'click', function() {
            var content = section.getElementsByClassName("content")[0]
            var icon = section.getElementsByClassName("collapse-icon")[0]
            if (content.visible()) {
                SC.slideAndHide(content, {
                    afterFinish: function() {
                        header.title = "Click to reveal form"
                        Element.update(icon, '+')
                    }
                });
            } else {
                SC.slideAndShow(content, {
                    afterFinish: function() {
                        header.title = "Click to conceal form"
                        Element.update(icon, '-')
                    }
                });
            }
        })
    })
}<|endoftext|>


<commit_before>'use strict'

// Mongodb dependency
const ObjectId = require('mongodb').ObjectId;
require('mongodb-toolkit');
// Internal dependency
const BateeqModels = require('bateeq-models');
const map = BateeqModels.map;
// External dependency
const BaseManager = require('module-toolkit').BaseManager;
const moment = require('moment');

module.exports = class MonthlyStockManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.InventoryMovement);
    }

    // GET START AND END YEAR BASED ON INVENTORY MOVEMENT
    _getFirstInventoryMovement() {
        return this.collection.find().sort({ date: 1 }).limit(1).toArray();
    }

    _getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth) {
        let yearMonths = [];
        for (let i = firstYear; i <= lastYear; i++) {
            let each = this.__pushMonthBasedOnYear(i, firstYear, lastYear, firstMonth, lastMonth);
            yearMonths.push(each);
        }
        yearMonths.sort(function (a, b) { return b.year - a.year });
        return yearMonths;
    }

    __pushMonthBasedOnYear(currentYear, firstYear, lastYear, firstMonth, lastMonth) {
        let currentYearList = { year: currentYear, months: [] };
        if (currentYear === firstYear) {
            if (currentYear === lastYear) {
                for (let j = firstMonth; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = firstMonth; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
        }
        else {
            if (currentYear === lastYear) {
                for (let j = 0; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = 0; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }

        }
        return currentYearList;
    }

    __getMonthName(monthNumber) {
        switch (monthNumber) {
            case 0:
                return { id: 0, name: "Januari" };
            case 1:
                return { id: 1, name: "Februari" };
            case 2:
                return { id: 2, name: "Maret" };
            case 3:
                return { id: 3, name: "April" };
            case 4:
                return { id: 4, name: "Mei" };
            case 5:
                return { id: 5, name: "Juni" };
            case 6:
                return { id: 6, name: "Juli" };
            case 7:
                return { id: 7, name: "Agustus" };
            case 8:
                return { id: 8, name: "September" };
            case 9:
                return { id: 9, name: "Oktober" };
            case 10:
                return { id: 10, name: "November" };
            case 11:
                return { id: 11, name: "Desember" };
        }
    }

    getYearMonthList() {
        let firstIM = this._getFirstInventoryMovement();
        let now = moment();
        return new Promise((resolve, reject) => {
            firstIM
                .then(results => {
                    let firstYear = results[0].date.getFullYear();
                    let firstMonth = results[0].date.getMonth();
                    let lastYear = parseInt(now.format('YYYY'));
                    let lastMonth = parseInt(now.format('MM')) - 1;
                    let yearMonthList = this._getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth);
                    resolve(yearMonthList);
                })
        })
    }
    //

    // GET LOCALE TIME IN JAKARTA
    __getLocaleDateOfMonth(year, month, isStartOf) {
        let locale = isStartOf ? moment().month(month).year(year).startOf('month') : moment().month(month).year(year).endOf('month');
        return locale;
    }

    _setDateOfMonth(month, year) {
        let firstDay = this.__getLocaleDateOfMonth(year, month, true).format();
        let lastDay = this.__getLocaleDateOfMonth(year, month, false).format();
        return {
            firstDay: new Date(firstDay),
            lastDay: new Date(lastDay)
        }
    }
    //

    // GET INVENTORY ON PARTICULAR MONTH -> INVENTORY WITH MOVEMENT (END OF THE MONTH AND BEFORE EARLY OF THE MONTH)
    _getCurrentStocks(day) {
        let currentStocks = [
            { $match: { date: { $lte: day } } },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { storageCode: "$storage.code", itemCode: "$item.code" },
                    storageName: { $first: "$storage.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", ""] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", ""] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    _id: 1,
                    storageName: "$storageName",
                    quantity: "$quantity",
                    hpp: { $multiply: ["$quantity", parseFloat("$hpp")] },
                    sale: { $multiply: ["$quantity", parseFloat("$sale")] }
                }
            },
            {
                $group: {
                    _id: { storageCode: "$_id.storageCode" },
                    storageName: { $first: "$storageName" },
                    quantity: { $sum: "$quantity" },
                    hpp: { $sum: "$hpp" },
                    sale: { $sum: "$sale" }
                }
            }
        ]
        let query = this.collection.aggregate(currentStocks).toArray();
        return query;
    }

    _combineStocks(earliest, latest) {
        let allStocks = [];
        latest.forEach(ls => {
            let stock = {
                code: ls._id.storageCode,
                name: ls.storageName,
                latestQuantity: ls.quantity,
                latestHPP: ls.hpp,
                latestSale: ls.sale
            };
            let found = earliest.find(es => { return es._id.storageCode === ls._id.storageCode });
            if (found !== undefined) {
                stock.earliestQuantity = found.quantity;
                stock.earliestHPP = found.hpp;
                stock.earliestSale = found.sale;
            }
            else {
                stock.earliestQuantity = 0;
                stock.earliestHPP = 0;
                stock.earliestSale = 0;
            }
            allStocks.push(stock);
        })
        return allStocks;
    }

    getOverallStock(month, year) {
        let date = this._setDateOfMonth(month, year);
        let earliestStocksQuery = this._getCurrentStocks(date.firstDay);
        let latestStocksQuery = this._getCurrentStocks(date.lastDay);
        return new Promise((resolve, reject) => {
            return Promise.all([earliestStocksQuery, latestStocksQuery])
                .then(results => {
                    let earliestStocks = results[0];
                    let latestStocks = results[1];
                    let finalStocks = this._combineStocks(earliestStocks, latestStocks);
                    resolve(finalStocks);
                })
        })
    }
    //

    // GET LATEST ITEM WITH PARTICULAR MONTH AND STORAGE CODE
    _getCurrentItems(code, day) {
        let currentItems = [
            {
                $match: {
                    date: { $lte: day },
                    "storage.code": code
                }
            },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { itemCode: "$item.code" },
                    itemName: { $first: "$item.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", ""] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", ""] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    itemCode: "$_id.itemCode",
                    itemName: "$itemName",
                    quantity: "$quantity",
                    totalHPP: { $multiply: ["$quantity", parseFloat("$hpp")] },
                    totalSale: { $multiply: ["$quantity", parseFloat("$sale")] }
                }
            },
            { $match: { quantity: { $ne: 0 } } }
        ]
        let query = this.collection.aggregate(currentItems).toArray();
        return query;
    }

    getStockInStorage(storageCode, month, year) {
        let date = this._setDateOfMonth(month, year);
        let latestItemsQuery = this._getCurrentItems(storageCode, date.lastDay);
        return new Promise((resolve, reject) => {
            return latestItemsQuery
                .then(latestItems => {
                    resolve(latestItems);
                })
        })
    }
    //
}<commit_msg>Remove parseFloat on monthly-stock<commit_after>'use strict'

// Mongodb dependency
const ObjectId = require('mongodb').ObjectId;
require('mongodb-toolkit');
// Internal dependency
const BateeqModels = require('bateeq-models');
const map = BateeqModels.map;
// External dependency
const BaseManager = require('module-toolkit').BaseManager;
const moment = require('moment');

module.exports = class MonthlyStockManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.InventoryMovement);
    }

    // GET START AND END YEAR BASED ON INVENTORY MOVEMENT
    _getFirstInventoryMovement() {
        return this.collection.find().sort({ date: 1 }).limit(1).toArray();
    }

    _getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth) {
        let yearMonths = [];
        for (let i = firstYear; i <= lastYear; i++) {
            let each = this.__pushMonthBasedOnYear(i, firstYear, lastYear, firstMonth, lastMonth);
            yearMonths.push(each);
        }
        yearMonths.sort(function (a, b) { return b.year - a.year });
        return yearMonths;
    }

    __pushMonthBasedOnYear(currentYear, firstYear, lastYear, firstMonth, lastMonth) {
        let currentYearList = { year: currentYear, months: [] };
        if (currentYear === firstYear) {
            if (currentYear === lastYear) {
                for (let j = firstMonth; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = firstMonth; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
        }
        else {
            if (currentYear === lastYear) {
                for (let j = 0; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = 0; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }

        }
        return currentYearList;
    }

    __getMonthName(monthNumber) {
        switch (monthNumber) {
            case 0:
                return { id: 0, name: "Januari" };
            case 1:
                return { id: 1, name: "Februari" };
            case 2:
                return { id: 2, name: "Maret" };
            case 3:
                return { id: 3, name: "April" };
            case 4:
                return { id: 4, name: "Mei" };
            case 5:
                return { id: 5, name: "Juni" };
            case 6:
                return { id: 6, name: "Juli" };
            case 7:
                return { id: 7, name: "Agustus" };
            case 8:
                return { id: 8, name: "September" };
            case 9:
                return { id: 9, name: "Oktober" };
            case 10:
                return { id: 10, name: "November" };
            case 11:
                return { id: 11, name: "Desember" };
        }
    }

    getYearMonthList() {
        let firstIM = this._getFirstInventoryMovement();
        let now = moment();
        return new Promise((resolve, reject) => {
            firstIM
                .then(results => {
                    let firstYear = results[0].date.getFullYear();
                    let firstMonth = results[0].date.getMonth();
                    let lastYear = parseInt(now.format('YYYY'));
                    let lastMonth = parseInt(now.format('MM')) - 1;
                    let yearMonthList = this._getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth);
                    resolve(yearMonthList);
                })
        })
    }
    //

    // GET LOCALE TIME IN JAKARTA
    __getLocaleDateOfMonth(year, month, isStartOf) {
        let locale = isStartOf ? moment().month(month).year(year).startOf('month') : moment().month(month).year(year).endOf('month');
        return locale;
    }

    _setDateOfMonth(month, year) {
        let firstDay = this.__getLocaleDateOfMonth(year, month, true).format();
        let lastDay = this.__getLocaleDateOfMonth(year, month, false).format();
        return {
            firstDay: new Date(firstDay),
            lastDay: new Date(lastDay)
        }
    }
    //

    // GET INVENTORY ON PARTICULAR MONTH -> INVENTORY WITH MOVEMENT (END OF THE MONTH AND BEFORE EARLY OF THE MONTH)
    _getCurrentStocks(day) {
        let currentStocks = [
            { $match: { date: { $lte: day } } },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { storageCode: "$storage.code", itemCode: "$item.code" },
                    storageName: { $first: "$storage.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", 0] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", 0] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    _id: 1,
                    storageName: "$storageName",
                    quantity: "$quantity",
                    hpp: { $multiply: ["$quantity", "$hpp"] },
                    sale: { $multiply: ["$quantity", "$sale"] }
                }
            },
            {
                $group: {
                    _id: { storageCode: "$_id.storageCode" },
                    storageName: { $first: "$storageName" },
                    quantity: { $sum: "$quantity" },
                    hpp: { $sum: "$hpp" },
                    sale: { $sum: "$sale" }
                }
            }
        ]
        let query = this.collection.aggregate(currentStocks).toArray();
        return query;
    }

    _combineStocks(earliest, latest) {
        let allStocks = [];
        latest.forEach(ls => {
            let stock = {
                code: ls._id.storageCode,
                name: ls.storageName,
                latestQuantity: ls.quantity,
                latestHPP: ls.hpp,
                latestSale: ls.sale
            };
            let found = earliest.find(es => { return es._id.storageCode === ls._id.storageCode });
            if (found !== undefined) {
                stock.earliestQuantity = found.quantity;
                stock.earliestHPP = found.hpp;
                stock.earliestSale = found.sale;
            }
            else {
                stock.earliestQuantity = 0;
                stock.earliestHPP = 0;
                stock.earliestSale = 0;
            }
            allStocks.push(stock);
        })
        return allStocks;
    }

    getOverallStock(month, year) {
        let date = this._setDateOfMonth(month, year);
        let earliestStocksQuery = this._getCurrentStocks(date.firstDay);
        let latestStocksQuery = this._getCurrentStocks(date.lastDay);
        return new Promise((resolve, reject) => {
            return Promise.all([earliestStocksQuery, latestStocksQuery])
                .then(results => {
                    let earliestStocks = results[0];
                    let latestStocks = results[1];
                    let finalStocks = this._combineStocks(earliestStocks, latestStocks);
                    resolve(finalStocks);
                })
        })
    }
    //

    // GET LATEST ITEM WITH PARTICULAR MONTH AND STORAGE CODE
    _getCurrentItems(code, day) {
        let currentItems = [
            {
                $match: {
                    date: { $lte: day },
                    "storage.code": code
                }
            },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { itemCode: "$item.code" },
                    itemName: { $first: "$item.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", 0] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", 0] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    itemCode: "$_id.itemCode",
                    itemName: "$itemName",
                    quantity: "$quantity",
                    totalHPP: { $multiply: ["$quantity", "$hpp"] },
                    totalSale: { $multiply: ["$quantity", "$sale"] }
                }
            },
            { $match: { quantity: { $ne: 0 } } }
        ]
        let query = this.collection.aggregate(currentItems).toArray();
        return query;
    }

    getStockInStorage(storageCode, month, year) {
        let date = this._setDateOfMonth(month, year);
        let latestItemsQuery = this._getCurrentItems(storageCode, date.lastDay);
        return new Promise((resolve, reject) => {
            return latestItemsQuery
                .then(latestItems => {
                    resolve(latestItems);
                })
        })
    }
    //
}<|endoftext|>