<commit_before>import { window, document } from 'ssr-window';
import $ from '../../../utils/dom';
import Utils from '../../../utils/utils';

export default function (event) {
  const swiper = this;
  const data = swiper.touchEventsData;
  const { params, touches } = swiper;
  if (swiper.animating && params.preventInteractionOnTransition) {
    return;
  }
  let e = event;
  if (e.originalEvent) e = e.originalEvent;
  data.isTouchEvent = e.type === 'touchstart';
  if (!data.isTouchEvent && 'which' in e && e.which === 3) return;
  if (data.isTouched && data.isMoved) return;
  if (params.noSwiping && $(e.target).closest(params.noSwipingSelector ? params.noSwipingSelector : `.${params.noSwipingClass}`)[0]) {
    swiper.allowClick = true;
    return;
  }
  if (params.swipeHandler) {
    if (!$(e).closest(params.swipeHandler)[0]) return;
  }

  touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
  touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
  const startX = touches.currentX;
  const startY = touches.currentY;

  // Do NOT start if iOS edge swipe is detected. Otherwise iOS app (UIWebView) cannot swipe-to-go-back anymore

  const edgeSwipeDetection = params.edgeSwipeDetection || params.iOSEdgeSwipeDetection;
  const edgeSwipeThreshold = params.edgeSwipeThreshold || params.iOSEdgeSwipeThreshold;
  if (
    edgeSwipeDetection
    && ((startX <= edgeSwipeThreshold)
    || (startX >= window.screen.width - edgeSwipeThreshold))
  ) {
    return;
  }

  Utils.extend(data, {
    isTouched: true,
    isMoved: false,
    allowTouchCallbacks: true,
    isScrolling: undefined,
    startMoving: undefined,
  });

  touches.startX = startX;
  touches.startY = startY;
  data.touchStartTime = Utils.now();
  swiper.allowClick = true;
  swiper.updateSize();
  swiper.swipeDirection = undefined;
  if (params.threshold > 0) data.allowThresholdMove = false;
  if (e.type !== 'touchstart') {
    let preventDefault = true;
    if ($(e.target).is(data.formElements)) preventDefault = false;
    if (
      document.activeElement
      && $(document.activeElement).is(data.formElements)
      && document.activeElement !== e.target
    ) {
      document.activeElement.blur();
    }
    if (preventDefault && swiper.allowTouchMove && swiper.touchStartPreventDefault) {
      e.preventDefault();
    }
  }
  swiper.emit('touchStart', e);
}
<commit_msg>Don't track all mouse buttons<commit_after>import { window, document } from 'ssr-window';
import $ from '../../../utils/dom';
import Utils from '../../../utils/utils';

export default function (event) {
  const swiper = this;
  const data = swiper.touchEventsData;
  const { params, touches } = swiper;
  if (swiper.animating && params.preventInteractionOnTransition) {
    return;
  }
  let e = event;
  if (e.originalEvent) e = e.originalEvent;
  data.isTouchEvent = e.type === 'touchstart';
  if (!data.isTouchEvent && 'which' in e && e.which === 3) return;
  if (!data.isTouchEvent && 'button' in e && e.button > 0) return;
  if (data.isTouched && data.isMoved) return;
  if (params.noSwiping && $(e.target).closest(params.noSwipingSelector ? params.noSwipingSelector : `.${params.noSwipingClass}`)[0]) {
    swiper.allowClick = true;
    return;
  }
  if (params.swipeHandler) {
    if (!$(e).closest(params.swipeHandler)[0]) return;
  }

  touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
  touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
  const startX = touches.currentX;
  const startY = touches.currentY;

  // Do NOT start if iOS edge swipe is detected. Otherwise iOS app (UIWebView) cannot swipe-to-go-back anymore

  const edgeSwipeDetection = params.edgeSwipeDetection || params.iOSEdgeSwipeDetection;
  const edgeSwipeThreshold = params.edgeSwipeThreshold || params.iOSEdgeSwipeThreshold;
  if (
    edgeSwipeDetection
    && ((startX <= edgeSwipeThreshold)
    || (startX >= window.screen.width - edgeSwipeThreshold))
  ) {
    return;
  }

  Utils.extend(data, {
    isTouched: true,
    isMoved: false,
    allowTouchCallbacks: true,
    isScrolling: undefined,
    startMoving: undefined,
  });

  touches.startX = startX;
  touches.startY = startY;
  data.touchStartTime = Utils.now();
  swiper.allowClick = true;
  swiper.updateSize();
  swiper.swipeDirection = undefined;
  if (params.threshold > 0) data.allowThresholdMove = false;
  if (e.type !== 'touchstart') {
    let preventDefault = true;
    if ($(e.target).is(data.formElements)) preventDefault = false;
    if (
      document.activeElement
      && $(document.activeElement).is(data.formElements)
      && document.activeElement !== e.target
    ) {
      document.activeElement.blur();
    }
    if (preventDefault && swiper.allowTouchMove && swiper.touchStartPreventDefault) {
      e.preventDefault();
    }
  }
  swiper.emit('touchStart', e);
}
<|endoftext|>


<commit_before>const reorder = require('../dist/reorder.cjs');

const vows = require('vows'),
  assert = require('assert');
const seedrandom = require('seedrandom');
Math.seedrandom('reorder');

const suite = vows.describe('reorder.graph2mat');

function remove_zeroes(mat) {
  let i, j;
  for (i = mat.length - 1; i >= 0; i--) {
    const row = mat[i];
    if (row.some((a) => a > 0)) {
      //console.log('remove row %d', i);
      break;
    }
    mat.pop();
  }
  for (j = mat[0].length - 1; j >= 0; j--) {
    if (mat.some((row) => row[j] != 0)) {
      //console.log('remove column %d', j);
      break;
    }
    for (i = 0; i < mat.length; i++) mat[i].pop();
  }

  return mat;
}

suite.addBatch({
  graph2mat: {
    simple() {
      const mat = [
        [0, 1, 0],
        [1, 0, 1],
        [0, 1, 0],
      ];
      const graph = reorder.mat2graph(mat);
      assert.equal(graph.nodes().length, 3);
      assert.equal(graph.links().length, 2);
      const m2 = reorder.graph2mat(graph);
      assert.deepEqual(m2, mat);
    },
    lesssimple() {
      const mat = reorder.random_matrix(0.2, 10),
        graph = reorder.mat2graph(mat),
        m2 = reorder.graph2mat(graph);
      assert.deepEqual(m2, mat);
    },
    hard() {
      for (let i = 10; i < 100; i += 20) {
        for (let j = 10; j < 100; j += 20) {
          const mat = remove_zeroes(reorder.random_matrix(0.2, i, j, false)),
            graph = reorder.mat2graph(mat, true),
            m2 = reorder.graph2mat(graph);
          assert.deepEqual(m2, mat);
        }
      }
    },
  },
});

suite.export(module);
<commit_msg>Manual cleanup of graph2mat-test.js<commit_after>const reorder = require('../dist/reorder.cjs');

const vows = require('vows');
const assert = require('assert');
const seedrandom = require('seedrandom');
Math.seedrandom('reorder');

const suite = vows.describe('reorder.graph2mat');

function remove_zeroes(mat) {
  for (let i = mat.length - 1; i >= 0; i--) {
    const row = mat[i];
    if (row.some((a) => a > 0)) {
      //console.log('remove row %d', i);
      break;
    }
    mat.pop();
  }
  for (let j = mat[0].length - 1; j >= 0; j--) {
    if (mat.some((row) => row[j] != 0)) {
      //console.log('remove column %d', j);
      break;
    }
    for (i = 0; i < mat.length; i++) mat[i].pop();
  }

  return mat;
}

suite.addBatch({
  graph2mat: {
    simple() {
      const mat = [
        [0, 1, 0],
        [1, 0, 1],
        [0, 1, 0],
      ];
      const graph = reorder.mat2graph(mat);
      assert.equal(graph.nodes().length, 3);
      assert.equal(graph.links().length, 2);
      const m2 = reorder.graph2mat(graph);
      assert.deepEqual(m2, mat);
    },
    lesssimple() {
      const mat = reorder.random_matrix(0.2, 10);
      const graph = reorder.mat2graph(mat);
      const m2 = reorder.graph2mat(graph);
      assert.deepEqual(m2, mat);
    },
    hard() {
      for (let i = 10; i < 100; i += 20) {
        for (let j = 10; j < 100; j += 20) {
          const mat = remove_zeroes(reorder.random_matrix(0.2, i, j, false));
          const graph = reorder.mat2graph(mat, true);
          const m2 = reorder.graph2mat(graph);
          assert.deepEqual(m2, mat);
        }
      }
    },
  },
});

suite.export(module);
<|endoftext|>


<commit_before>// group-api-test.js
//
// Test group API
//
// Copyright 2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("underscore"),
    http = require("http"),
    urlparse = require("url").parse,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    actutil = require("./lib/activity"),
    pj = httputil.postJSON,
    gj = httputil.getJSON,
    validActivity = actutil.validActivity,
    validActivityObject = actutil.validActivityObject,
    validFeed = actutil.validFeed,
    setupApp = oauthutil.setupApp,
    newCredentials = oauthutil.newCredentials;

var suite = vows.describe("Group API test");

// A batch for testing the read-write access to the API

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            if (app && app.close) {
                app.close();
            }
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we make a new user": {
            topic: function() {
                newCredentials("fafhrd", "lankhmar+1", this.callback);
            },
            "it works": function(err, cred) {
                assert.ifError(err);
                assert.isObject(cred);
            },
            "and they create a group": {
                topic: function(cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/fafhrd/feed",
                        act = {
                            verb: "create",
                            object: {
                                objectType: "group",
                                displayName: "Barbarians",
                                summary: "A safe place for barbarians to share their feelings"
                            }
                        };

                    pj(url, cred, act, function(err, data, resp) {
                        callback(err, data);
                    });
                },
                "it works": function(err, data) {
                    assert.ifError(err);
                    validActivity(data);
                },
                "and we retrieve that group with the REST API": {
                    topic: function(act, cred) {
                        var callback = this.callback,
                            url = act.object.links.self.href;

                        gj(url, cred, function(err, data, resp) {
                            callback(err, data);
                        });
                    },
                    "it works": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                    },
                    "it looks right": function(err, group) {
                        assert.ifError(err);
                        validActivityObject(group);
                    },
                    "it has a members feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "members");
                        assert.isObject(group.members);
                        assert.include(group.members, "url");
                        assert.isString(group.members.url);
                        assert.include(group.members, "totalItems");
                        assert.isNumber(group.members.totalItems);
                        assert.equal(group.members.totalItems, 0);
                    },
                    "it has an inbox feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "links");
                        assert.isObject(group.links);
                        assert.include(group.links, "activity-inbox");
                        assert.isObject(group.links["activity-inbox"]);
                        assert.include(group.links["activity-inbox"], "href");
                        assert.isString(group.links["activity-inbox"].href);
                    },
                    "and we get the members feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.members.url;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    },
                    "and we get the group inbox feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.links["activity-inbox"].href;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    }
                }
            }
        },
        "and we make another group": {
            topic: function() {
                var callback = this.callback,
                    url = "http://localhost:4815/api/user/graymouser/feed",
                    act = {
                        verb: "create",
                        to: [{
                            id: "http://activityschema.org/collection/public",
                            objectType: "collection"
                        }],
                        object: {
                            objectType: "group",
                            displayName: "Magicians",
                            summary: "Let's talk sorcery!"
                        }
                    },
                    cred;

                Step(
                    function() {
                        newCredentials("graymouser", "swords+_+_", this);
                    },
                    function(err, results) {
                        if (err) throw err;
                        cred = results;
                        pj(url, cred, act, this);
                    },
                    function(err, data, resp) {
                        if (err) {
                            callback(err, null, null);
                        } else {
                            callback(null, data, cred);
                        }
                    }
                );
            },
            "it works": function(err, data, cred) {
                assert.ifError(err);
                validActivity(data);
            },
            "and another user tries to join it": {
                topic: function(created, cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/ningauble/feed",
                        act = {
                            verb: "join",
                            object: {
                                id: created.object.id,
                                objectType: created.object.objectType
                            }
                        },
                        newCred;

                    Step(
                        function() {
                            newCredentials("ningauble", "*iiiiiii*", this);
                        },
                        function(err, results) {
                            if (err) throw err;
                            newCred = results;
                            pj(url, newCred, act, this);
                        },
                        function(err, data, resp) {
                            if (err) {
                                callback(err, null, null);
                            } else {
                                callback(null, data, newCred);
                            }
                        }
                    );
                },
                "it works": function(err, data, cred) {
                    assert.ifError(err);
                    validActivity(data);
                },
		"and the creator checks the member feed": {
		    topic: function(joinAct, memberCred, createAct, creatorCred) {
                        var callback = this.callback,
                        url = joinAct.object.members.url,
			cred = creatorCred;

                        gj(url, cred, function(err, data, resp) {
                            callback(err, data, joinAct.actor);
                        });
                    },
                    "it works": function(err, feed, joiner) {
                        assert.ifError(err);
                        validFeed(feed);
                    },
                    "it's got our joined person": function(err, feed, joiner) {
                        assert.ifError(err);
                        assert.equal(feed.totalItems, 1);
                        assert.equal(feed.items.length, 1);
                        validActivityObject(feed.items[0]);
                        assert.equal(feed.items[0].id, joiner.id);
                    },
                    "and the member leaves the group": {
		        topic: function(feed, joiner, joinAct, memberCred, createAct, creatorCred) {
                            var callback = this.callback,
                                url = "http://localhost:4815/api/user/ningauble/feed",
                                cred = memberCred,
                                group = createAct.object,
                                act = {
                                    verb: "leave",
                                    object: {
                                        id: group.id,
                                        objectType: group.objectType
                                    }
                                };

                            Step(
                                function() {
                                    pj(url, cred, act, this);
                                },
                                function(err, data, resp) {
                                    if (err) {
                                        callback(err, null);
                                    } else {
                                        callback(null, data);
                                    }
                                }
                            );
                        },
                        "it works": function(err, data) {
                            assert.ifError(err);
                            validActivity(data);
                        },
                        "and the creator checks the member feed": {
		            topic: function(leaveAct, feed, joiner, joinAct, memberCred, createAct, creatorCred) {

                                var callback = this.callback,
                                    url = createAct.object.members.url,
			            cred = creatorCred;

                                gj(url, cred, function(err, data, resp) {
                                    callback(err, data);
                                });
                            },
                            "it works": function(err, feed) {
                                assert.ifError(err);
                                validFeed(feed);
                            },
                            "it's empty": function(err, feed) {
                                assert.ifError(err);
                                assert.equal(feed.totalItems, 0);
                                assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                            }
                        }
                    }
		}
            }
        },
        "and two users join a group": {
            topic: function() {
                var callback = this.callback,
                    creds,
                    group;

                Step(
                    function() {
                        newCredentials("krovas", "grand*master", this.parallel());
                        newCredentials("fissif", "thief*no1", this.parallel());
                        newCredentials("slevyas", "thief*no2", this.parallel());
                    },
                    function(err, cred1, cred2, cred3) {
                        var url, act;
                        if (err) throw err;
                        creds = {
                            krovas: cred1,
                            fissif: cred2,
                            slevyas: cred3
                        };
                        url = "http://localhost:4815/api/user/krovas/feed";
                        act = {
                            verb: "create",
                            to: [{
                                id: "http://activityschema.org/collection/public",
                                objectType: "collection"
                            }],
                            object: {
                                objectType: "group",
                                displayName: "Thieves' Guild",
                                summary: "For thieves to hang out and help each other steal stuff"
                            }
                        };
                        pj(url, creds.krovas, act, this);
                    },
                    function(err, created) {
                        var url, act;
                        if (err) throw err;
                        group = created.object;
                        url = "http://localhost:4815/api/user/fissif/feed";
                        act = {
                            verb: "join",
                            object: group
                        };
                        pj(url, creds.fissif, act, this.parallel());
                        url = "http://localhost:4815/api/user/slevyas/feed";
                        act = {
                            verb: "join",
                            object: group
                        };
                        pj(url, creds.slevyas, act, this.parallel());
                    },
                    function(err) {
                        if (err) {
                            callback(err, null, null);
                        } else {
                            callback(null, group, creds);
                        }
                    }
                );
            },
            "it works": function(err, group, creds) {
                assert.ifError(err);
                validActivityObject(group);
                assert.isObject(creds);
            }
        }
    }
});

suite["export"](module);
<commit_msg>One user posting to the group<commit_after>// group-api-test.js
//
// Test group API
//
// Copyright 2013, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("underscore"),
    http = require("http"),
    urlparse = require("url").parse,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    actutil = require("./lib/activity"),
    pj = httputil.postJSON,
    gj = httputil.getJSON,
    validActivity = actutil.validActivity,
    validActivityObject = actutil.validActivityObject,
    validFeed = actutil.validFeed,
    setupApp = oauthutil.setupApp,
    newCredentials = oauthutil.newCredentials;

var suite = vows.describe("Group API test");

// A batch for testing the read-write access to the API

suite.addBatch({
    "When we set up the app": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            if (app && app.close) {
                app.close();
            }
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we make a new user": {
            topic: function() {
                newCredentials("fafhrd", "lankhmar+1", this.callback);
            },
            "it works": function(err, cred) {
                assert.ifError(err);
                assert.isObject(cred);
            },
            "and they create a group": {
                topic: function(cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/fafhrd/feed",
                        act = {
                            verb: "create",
                            object: {
                                objectType: "group",
                                displayName: "Barbarians",
                                summary: "A safe place for barbarians to share their feelings"
                            }
                        };

                    pj(url, cred, act, function(err, data, resp) {
                        callback(err, data);
                    });
                },
                "it works": function(err, data) {
                    assert.ifError(err);
                    validActivity(data);
                },
                "and we retrieve that group with the REST API": {
                    topic: function(act, cred) {
                        var callback = this.callback,
                            url = act.object.links.self.href;

                        gj(url, cred, function(err, data, resp) {
                            callback(err, data);
                        });
                    },
                    "it works": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                    },
                    "it looks right": function(err, group) {
                        assert.ifError(err);
                        validActivityObject(group);
                    },
                    "it has a members feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "members");
                        assert.isObject(group.members);
                        assert.include(group.members, "url");
                        assert.isString(group.members.url);
                        assert.include(group.members, "totalItems");
                        assert.isNumber(group.members.totalItems);
                        assert.equal(group.members.totalItems, 0);
                    },
                    "it has an inbox feed": function(err, group) {
                        assert.ifError(err);
                        assert.isObject(group);
                        assert.include(group, "links");
                        assert.isObject(group.links);
                        assert.include(group.links, "activity-inbox");
                        assert.isObject(group.links["activity-inbox"]);
                        assert.include(group.links["activity-inbox"], "href");
                        assert.isString(group.links["activity-inbox"].href);
                    },
                    "and we get the members feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.members.url;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    },
                    "and we get the group inbox feed": {
                        topic: function(group, act, cred) {
                            var callback = this.callback,
                                url = group.links["activity-inbox"].href;

                            gj(url, cred, function(err, data, resp) {
                                callback(err, data);
                            });
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            validFeed(feed);
                        },
                        "it's empty": function(err, feed) {
                            assert.ifError(err);
                            assert.equal(feed.totalItems, 0);
                            assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                        }
                    }
                }
            }
        },
        "and we make another group": {
            topic: function() {
                var callback = this.callback,
                    url = "http://localhost:4815/api/user/graymouser/feed",
                    act = {
                        verb: "create",
                        to: [{
                            id: "http://activityschema.org/collection/public",
                            objectType: "collection"
                        }],
                        object: {
                            objectType: "group",
                            displayName: "Magicians",
                            summary: "Let's talk sorcery!"
                        }
                    },
                    cred;

                Step(
                    function() {
                        newCredentials("graymouser", "swords+_+_", this);
                    },
                    function(err, results) {
                        if (err) throw err;
                        cred = results;
                        pj(url, cred, act, this);
                    },
                    function(err, data, resp) {
                        if (err) {
                            callback(err, null, null);
                        } else {
                            callback(null, data, cred);
                        }
                    }
                );
            },
            "it works": function(err, data, cred) {
                assert.ifError(err);
                validActivity(data);
            },
            "and another user tries to join it": {
                topic: function(created, cred) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/ningauble/feed",
                        act = {
                            verb: "join",
                            object: {
                                id: created.object.id,
                                objectType: created.object.objectType
                            }
                        },
                        newCred;

                    Step(
                        function() {
                            newCredentials("ningauble", "*iiiiiii*", this);
                        },
                        function(err, results) {
                            if (err) throw err;
                            newCred = results;
                            pj(url, newCred, act, this);
                        },
                        function(err, data, resp) {
                            if (err) {
                                callback(err, null, null);
                            } else {
                                callback(null, data, newCred);
                            }
                        }
                    );
                },
                "it works": function(err, data, cred) {
                    assert.ifError(err);
                    validActivity(data);
                },
		"and the creator checks the member feed": {
		    topic: function(joinAct, memberCred, createAct, creatorCred) {
                        var callback = this.callback,
                        url = joinAct.object.members.url,
			cred = creatorCred;

                        gj(url, cred, function(err, data, resp) {
                            callback(err, data, joinAct.actor);
                        });
                    },
                    "it works": function(err, feed, joiner) {
                        assert.ifError(err);
                        validFeed(feed);
                    },
                    "it's got our joined person": function(err, feed, joiner) {
                        assert.ifError(err);
                        assert.equal(feed.totalItems, 1);
                        assert.equal(feed.items.length, 1);
                        validActivityObject(feed.items[0]);
                        assert.equal(feed.items[0].id, joiner.id);
                    },
                    "and the member leaves the group": {
		        topic: function(feed, joiner, joinAct, memberCred, createAct, creatorCred) {
                            var callback = this.callback,
                                url = "http://localhost:4815/api/user/ningauble/feed",
                                cred = memberCred,
                                group = createAct.object,
                                act = {
                                    verb: "leave",
                                    object: {
                                        id: group.id,
                                        objectType: group.objectType
                                    }
                                };

                            Step(
                                function() {
                                    pj(url, cred, act, this);
                                },
                                function(err, data, resp) {
                                    if (err) {
                                        callback(err, null);
                                    } else {
                                        callback(null, data);
                                    }
                                }
                            );
                        },
                        "it works": function(err, data) {
                            assert.ifError(err);
                            validActivity(data);
                        },
                        "and the creator checks the member feed": {
		            topic: function(leaveAct, feed, joiner, joinAct, memberCred, createAct, creatorCred) {

                                var callback = this.callback,
                                    url = createAct.object.members.url,
			            cred = creatorCred;

                                gj(url, cred, function(err, data, resp) {
                                    callback(err, data);
                                });
                            },
                            "it works": function(err, feed) {
                                assert.ifError(err);
                                validFeed(feed);
                            },
                            "it's empty": function(err, feed) {
                                assert.ifError(err);
                                assert.equal(feed.totalItems, 0);
                                assert.isTrue(!_.has(feed, "items") || (_.isArray(feed.items) && feed.items.length === 0));
                            }
                        }
                    }
		}
            }
        },
        "and two users join a group": {
            topic: function() {
                var callback = this.callback,
                    creds,
                    group;

                Step(
                    function() {
                        newCredentials("krovas", "grand*master", this.parallel());
                        newCredentials("fissif", "thief*no1", this.parallel());
                        newCredentials("slevyas", "thief*no2", this.parallel());
                    },
                    function(err, cred1, cred2, cred3) {
                        var url, act;
                        if (err) throw err;
                        creds = {
                            krovas: cred1,
                            fissif: cred2,
                            slevyas: cred3
                        };
                        url = "http://localhost:4815/api/user/krovas/feed";
                        act = {
                            verb: "create",
                            to: [{
                                id: "http://activityschema.org/collection/public",
                                objectType: "collection"
                            }],
                            object: {
                                objectType: "group",
                                displayName: "Thieves' Guild",
                                summary: "For thieves to hang out and help each other steal stuff"
                            }
                        };
                        pj(url, creds.krovas, act, this);
                    },
                    function(err, created) {
                        var url, act;
                        if (err) throw err;
                        group = created.object;
                        url = "http://localhost:4815/api/user/fissif/feed";
                        act = {
                            verb: "join",
                            object: group
                        };
                        pj(url, creds.fissif, act, this.parallel());
                        url = "http://localhost:4815/api/user/slevyas/feed";
                        act = {
                            verb: "join",
                            object: group
                        };
                        pj(url, creds.slevyas, act, this.parallel());
                    },
                    function(err) {
                        if (err) {
                            callback(err, null, null);
                        } else {
                            callback(null, group, creds);
                        }
                    }
                );
            },
            "it works": function(err, group, creds) {
                assert.ifError(err);
                validActivityObject(group);
                assert.isObject(creds);
            },
            "and one member posts to the group": {
                topic: function(group, creds) {
                    var callback = this.callback,
                        url = "http://localhost:4815/api/user/fissif/feed",
                        act = {
                            verb: "post",
                            to: [group],
                            object: {
                                objectType: "note",
                                content: "When is the next big caper, guys?"
                            }
                        };
                    pj(url, creds.fissif, act, function(err, data, resp) {
                        callback(err, data);
                    });
                },
                "it works": function(err, act) {
                    assert.ifError(err);
                    validActivity(act);
                }
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import ReactDOM from 'react-dom'
import Icon from 'react-fa'

import {SpaceCard, NewSpaceCard} from 'gComponents/spaces/cards'

import Container from 'gComponents/utility/container/Container'
import {MembersTab} from './members'
import {FactListContainer} from 'gComponents/facts/list/container.js'

import {httpRequestSelector} from './httpRequestSelector'
import {organizationSpaceSelector} from './organizationSpaceSelector'
import {organizationMemberSelector} from './organizationMemberSelector'

import * as modalActions from 'gModules/modal/actions'
import * as spaceActions from 'gModules/spaces/actions'
import * as organizationActions from 'gModules/organizations/actions'
import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'

import e from 'gEngine/engine'

import './style.css'

const MODEL_TAB = 'models'
const MEMBERS_TAB = 'members'
const FACT_BOOK_TAB = 'facts'

const isValidTabString = tabStr => [MODEL_TAB, MEMBERS_TAB, FACT_BOOK_TAB].includes(tabStr)

function mapStateToProps(state) {
  return {
    me: state.me,
    organizations: state.organizations,
    organizationFacts: state.facts.organizationFacts,
  }
}

@connect(mapStateToProps)
@connect(organizationSpaceSelector)
@connect(organizationMemberSelector)
@connect(httpRequestSelector)
export default class OrganizationShow extends Component{
  displayName: 'OrganizationShow'

  state = {
    openTab: isValidTabString(this.props.tab) ? this.props.tab : MODEL_TAB,
  }

  componentWillMount() {
    this.refreshData()
  }

  refreshData() {
    this.props.dispatch(organizationActions.fetchById(this.props.organizationId))
    this.props.dispatch(spaceActions.fetch({organizationId: this.props.organizationId}))
  }

  changeTab(tab) {
    this.setState({
      openTab: tab,
    })
  }

  _newModel() {
    this.props.dispatch(spaceActions.create(this.props.organizationId))
  }

  destroyMembership(membershipId) {
    this.props.dispatch(userOrganizationMembershipActions.destroy(membershipId))
  }

  onRemove(member) {
    this.confirmRemove(member)
  }

  confirmRemove({email, name, membershipId}) {
    const removeCallback = () => {
      this.destroyMembership(membershipId)
      this.props.dispatch(modalActions.close())
    }

    const message = `Are you sure you want to remove ${name} from this organization?`

    this.props.dispatch(modalActions.openConfirmation({onConfirm: removeCallback, message}))
  }

  render () {
    const {organizationId, organizations, organizationFacts, members, memberships, invitations} = this.props
    const {openTab} = this.state
    const spaces =  _.orderBy(this.props.organizationSpaces.asMutable(), ['updated_at'], ['desc'])
    const organization = organizations.find(u => u.id.toString() === organizationId.toString())
    const facts = _.get(organizationFacts.find(f => f.variable_name === `organization_${organizationId}`), 'children') || []
    const meIsAdmin = !!organization && (organization.admin_id === this.props.me.id)
    const meIsMember = meIsAdmin || !!(members.find(m => m.id === this.props.me.id))

    if (!organization) { return false }
    let tabs = [{name: 'Models', key: MODEL_TAB}, {name: 'Facts', key: FACT_BOOK_TAB}]
    if (__DEV__ || organizationId === 1) { tabs = [...tabs, {name: 'Members', key: MEMBERS_TAB}] }
    const portalUrl = _.get(organization, 'account._links.payment_portal.href')
    if (!!portalUrl) { tabs = [...tabs, {name: 'Billing', key: 'BILLING', href: portalUrl, onMouseUp: this.refreshData.bind(this)}] }

    return (
      <Container>

          <OrganizationHeader organization={organization}/>

          {meIsMember &&
            <OrganizationTabButtons
              tabs={tabs}
              openTab={openTab}
              changeTab={this.changeTab.bind(this)}
            />
          }

            {(openTab === MODEL_TAB || !meIsMember) && spaces &&

                {meIsMember &&
                  <NewSpaceCard onClick={this._newModel.bind(this)}/>
                }
                {_.map(spaces, (s) =>
                    <SpaceCard
                      key={s.id}
                      space={s}
                      showPrivacy={true}
                    />
                )}

            }

            {(openTab === MEMBERS_TAB) && meIsMember && members && organization &&
              <MembersTab
                organizationId={organizationId}
                startOnIndexTab={true}
                members={members}
                memberships={memberships}
                invitations={invitations}
                admin_id={organization.admin_id}
                onRemove={this.onRemove.bind(this)}
                httpRequests={this.props.httpRequests}
                meIsAdmin={meIsAdmin}
              />
            }

            {(openTab === FACT_BOOK_TAB) && meIsMember && !!facts &&
              <FactTab organizationId={organizationId}/>
            }

      </Container>
    )
  }
}

const OrganizationHeader = ({organization}) => (

 {organization.name}

)

const OrganizationTabButtons = ({tabs, openTab, changeTab}) => (

        { tabs.map( e => {
          const className = `item ${(openTab === e.key) ? 'active' : ''}`
          if (!!e.href){
            return (
               {} }
              >
                {e.name}

            )
          } else {
            return (
               {changeTab(e.key)}}> {e.name}
            )
          }
         })}

)

const FactTab = ({organizationId}) => (

 Organizational Facts

 Facts can be used in organization models by referencing them with '#' symbols.

        <FactListContainer organizationId={organizationId} isEditable={true}/>

)

<commit_msg>Whoopsy<commit_after>import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'

import ReactDOM from 'react-dom'
import Icon from 'react-fa'

import {SpaceCard, NewSpaceCard} from 'gComponents/spaces/cards'

import Container from 'gComponents/utility/container/Container'
import {MembersTab} from './members'
import {FactListContainer} from 'gComponents/facts/list/container.js'

import {httpRequestSelector} from './httpRequestSelector'
import {organizationSpaceSelector} from './organizationSpaceSelector'
import {organizationMemberSelector} from './organizationMemberSelector'

import * as modalActions from 'gModules/modal/actions'
import * as spaceActions from 'gModules/spaces/actions'
import * as organizationActions from 'gModules/organizations/actions'
import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'

import e from 'gEngine/engine'

import './style.css'

const MODEL_TAB = 'models'
const MEMBERS_TAB = 'members'
const FACT_BOOK_TAB = 'facts'

const isValidTabString = tabStr => [MODEL_TAB, MEMBERS_TAB, FACT_BOOK_TAB].includes(tabStr)

function mapStateToProps(state) {
  return {
    me: state.me,
    organizations: state.organizations,
    organizationFacts: state.facts.organizationFacts,
  }
}

@connect(mapStateToProps)
@connect(organizationSpaceSelector)
@connect(organizationMemberSelector)
@connect(httpRequestSelector)
export default class OrganizationShow extends Component{
  displayName: 'OrganizationShow'

  state = {
    openTab: isValidTabString(this.props.tab) ? this.props.tab : MODEL_TAB,
  }

  componentWillMount() {
    this.refreshData()
  }

  refreshData() {
    this.props.dispatch(organizationActions.fetchById(this.props.organizationId))
    this.props.dispatch(spaceActions.fetch({organizationId: this.props.organizationId}))
  }

  changeTab(tab) {
    this.setState({
      openTab: tab,
    })
  }

  _newModel() {
    this.props.dispatch(spaceActions.create(this.props.organizationId))
  }

  destroyMembership(membershipId) {
    this.props.dispatch(userOrganizationMembershipActions.destroy(membershipId))
  }

  onRemove(member) {
    this.confirmRemove(member)
  }

  confirmRemove({email, name, membershipId}) {
    const removeCallback = () => {
      this.destroyMembership(membershipId)
      this.props.dispatch(modalActions.close())
    }

    const message = `Are you sure you want to remove ${name} from this organization?`

    this.props.dispatch(modalActions.openConfirmation({onConfirm: removeCallback, message}))
  }

  render () {
    const {organizationId, organizations, organizationFacts, members, memberships, invitations} = this.props
    const {openTab} = this.state
    const spaces =  _.orderBy(this.props.organizationSpaces.asMutable(), ['updated_at'], ['desc'])
    const organization = organizations.find(u => u.id.toString() === organizationId.toString())
    const facts = _.get(organizationFacts.find(f => f.variable_name === `organization_${organizationId}`), 'children') || []
    const meIsAdmin = !!organization && (organization.admin_id === this.props.me.id)
    const meIsMember = meIsAdmin || !!(members.find(m => m.id === this.props.me.id))

    if (!organization) { return false }
    let tabs = [{name: 'Models', key: MODEL_TAB}, {name: 'Members', key: MEMBERS_TAB}]
    if (__DEV__ || organizationId === 1) { tabs = [{name: 'Models', key: MODEL_TAB}, {name: 'Facts', key: FACT_BOOK_TAB}, {name: 'Members', key: MEMBERS_TAB}] }
    const portalUrl = _.get(organization, 'account._links.payment_portal.href')
    if (!!portalUrl) { tabs = [...tabs, {name: 'Billing', key: 'BILLING', href: portalUrl, onMouseUp: this.refreshData.bind(this)}] }

    return (
      <Container>

          <OrganizationHeader organization={organization}/>

          {meIsMember &&
            <OrganizationTabButtons
              tabs={tabs}
              openTab={openTab}
              changeTab={this.changeTab.bind(this)}
            />
          }

            {(openTab === MODEL_TAB || !meIsMember) && spaces &&

                {meIsMember &&
                  <NewSpaceCard onClick={this._newModel.bind(this)}/>
                }
                {_.map(spaces, (s) =>
                    <SpaceCard
                      key={s.id}
                      space={s}
                      showPrivacy={true}
                    />
                )}

            }

            {(openTab === MEMBERS_TAB) && meIsMember && members && organization &&
              <MembersTab
                organizationId={organizationId}
                startOnIndexTab={true}
                members={members}
                memberships={memberships}
                invitations={invitations}
                admin_id={organization.admin_id}
                onRemove={this.onRemove.bind(this)}
                httpRequests={this.props.httpRequests}
                meIsAdmin={meIsAdmin}
              />
            }

            {(openTab === FACT_BOOK_TAB) && meIsMember && !!facts &&
              <FactTab organizationId={organizationId}/>
            }

      </Container>
    )
  }
}

const OrganizationHeader = ({organization}) => (

 {organization.name}

)

const OrganizationTabButtons = ({tabs, openTab, changeTab}) => (

        { tabs.map( e => {
          const className = `item ${(openTab === e.key) ? 'active' : ''}`
          if (!!e.href){
            return (
               {} }
              >
                {e.name}

            )
          } else {
            return (
               {changeTab(e.key)}}> {e.name}
            )
          }
         })}

)

const FactTab = ({organizationId}) => (

 Organizational Facts

 Facts can be used in organization models by referencing them with '#' symbols.

        <FactListContainer organizationId={organizationId} isEditable={true}/>

)

<|endoftext|>


<commit_before>/* eslint-disable */
// based on https://github.com/alicelieutier/smoothScroll

var getTop = function(element) {
    // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset
    if(element.nodeName === 'HTML') return -window.pageYOffset
    return element.getBoundingClientRect().top + window.pageYOffset;
}
// ease in out function thanks to:
// http://blog.greweb.fr/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/
var easeInOutCubic = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }

// calculate the scroll position we should be in
// given the start and end point of the scroll
// the time elapsed from the beginning of the scroll
// and the total duration of the scroll (default 500ms)
var position = function(start, end, elapsed, duration) {
    if (elapsed > duration) return end;
    return start + (end - start) * easeInOutCubic(elapsed / duration); // <-- you can change the easing funtion there
    // return start + (end - start) * (elapsed / duration); // <-- this would give a linear scroll
}

// we use requestAnimationFrame to be called by the browser before every repaint
// if the first argument is an element then scroll to the top of this element
// if the first argument is numeric then scroll to this location
// if the callback exist, it is called when the scrolling is finished
// if context is set then scroll that element, else scroll window
var smoothScroll = function(el, duration, callback, context){
    duration = duration || 500;
    context = context || window;
    var start = window.pageYOffset;

    if (typeof el === 'number') {
      var end = parseInt(el);
    } else {
      var end = getTop(el);
    }

    var clock = Date.now();
    var requestAnimationFrame = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
        function(fn){window.setTimeout(fn, 15);};

    var step = function(){
        var elapsed = Date.now() - clock;
        if (context !== window) {
        	context.scrollTop = position(start, end, elapsed, duration);
        }
        else {
        	window.scroll(0, position(start, end, elapsed, duration));
        }

        if (elapsed > duration) {
            if (typeof callback === 'function') {
                callback(el);
            }
        } else {
            requestAnimationFrame(step);
        }
    }
    step();
}

export default smoothScroll;
<commit_msg>refactoring<commit_after>// based on https://github.com/alicelieutier/smoothScroll

const getTop = (element) => {
  // return value of html.getBoundingClientRect().top ... IE : 0, other browsers : -pageYOffset
  if (element.nodeName === 'HTML') return -window.pageYOffset;
  return element.getBoundingClientRect().top + window.pageYOffset;
};

// ease in out function thanks to:
// http://blog.greweb.fr/2012/02/bezier-curve-based-easing-functions-from-concept-to-implementation/
const easeInOutCubic = (t) => (
  t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
);

// calculate the scroll position we should be in
// given the start and end point of the scroll
// the time elapsed from the beginning of the scroll
// and the total duration of the scroll (default 500ms)
const position = (start, end, elapsed, duration) => {
  if (elapsed > duration) return end;
  return start + (end - start) * easeInOutCubic(elapsed / duration);
};

// we use requestAnimationFrame to be called by the browser before every repaint
// if the first argument is an element then scroll to the top of this element
// if the first argument is numeric then scroll to this location
// if the callback exist, it is called when the scrolling is finished
// if context is set then scroll that element, else scroll window
const smoothScroll = (el, durationParam, callback) => {
  const duration = durationParam || 500;
  const start = window.pageYOffset;
  let end;

  if (typeof el === 'number') {
    end = parseInt(el, 10);
  } else {
    end = getTop(el);
  }

  const clock = Date.now();
  const requestAnimationFrame = window.requestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      ((fn) => { window.setTimeout(fn, 15); });

  const step = () => {
    const elapsed = Date.now() - clock;
    window.scroll(0, position(start, end, elapsed, duration));

    if (elapsed > duration) {
      if (typeof callback === 'function') {
        callback(el);
      }
    } else {
      requestAnimationFrame(step);
    }
  };
  step();
};

export default smoothScroll;
<|endoftext|>


<commit_before>var soloView = require('./soloView/soloview');
var groupView = require('./groupView/groupView');

var ProjectViewController = function ($state){
    var pvCtrl = this;

    pvCtrl.state = $state;
};

angular.module('app.projectview', [
    'app.projectview.groupview',
    'app.projectview.soloview'])
    .controller('ProjectViewController', ProjectViewController);

module.exports = ProjectViewController;<commit_msg>Fixing typo<commit_after>var soloView = require('./soloView/soloView');
var groupView = require('./groupView/groupView');

var ProjectViewController = function ($state){
    var pvCtrl = this;

    pvCtrl.state = $state;
};

angular.module('app.projectview', [
    'app.projectview.groupview',
    'app.projectview.soloview'])
    .controller('ProjectViewController', ProjectViewController);

module.exports = ProjectViewController;<|endoftext|>


<commit_before>'use strict';

angular.module('impactApp')
  .factory('RequestService', function RequestService($http) {
    function allMandatoryFilesPresent(request) {
      return request.documents && request.documents.obligatoires && Object.keys(request.documents.obligatoires).length === 3;
    }

    function hasInvalidFileInCategories(categories) {
      let found = false;
      _.forEach(categories, function(category) {
        category.documentList.forEach(function(document) {
          if (document.isInvalid === true) {
            found = true;
          }
        });
      });

      return found;
    }

    function hasInvalidFile(request) {
      return hasInvalidFileInCategories(request.documents.obligatoires) || hasInvalidFileInCategories(request.documents.complementaires);
    }

    function allAskedFilesPresent(request) {
      var allAskedFilesComplete = true;

      _.forEach(request.askedDocumentTypes, function(askedType) {
        let askedDocs = _.get(request.documents, ['complementaires', askedType, 'documentList']);
        if (typeof askedDocs === 'undefined' || askedDocs.length === 0) {
          allAskedFilesComplete = false;
        }
      });

      return allAskedFilesComplete;
    }

    function getCompletion(request) {
      if (!request.documents) {
        return false;
      }

      return allMandatoryFilesPresent(request) && !hasInvalidFile(request) && allAskedFilesPresent(request);
    }

    function findInvalid(categories) {
      var invalidDocuments = [];

      _.forEach(categories, function(category) {
        _.forEach(category.documentList, function(document) {
          if (document.isInvalid) {
            invalidDocuments.push(document);
          }
        });
      });

      return invalidDocuments;
    }

    function findRefusedDocuments(request) {
      if (!request.documents) {
        return {
          obligatoires: [],
          complementaires: []
        };
      }

      var obligatoires = findInvalid(request.documents.obligatoires);
      var complementaires = findInvalid(request.documents.complementaires);

      return {
        obligatoires: obligatoires,
        complementaires: complementaires
      };
    }

    function getAskedDocumentTypes(request) {
      if (!request.askedDocumentTypes) {
        return [];
      }

      return request.askedDocumentTypes;
    }

    function getMandatoryTypes(documentTypes) {
      return _.filter(documentTypes, {mandatory: true});
    }

    function findExistingTypes(request) {
      return _.pluck(request.documents.complementaires, 'documentType');
    }

    function findAskedTypes(request, documentTypes) {
      return _(documentTypes)
        .filter(function(documentType) {
          return !documentType.mandatory && request.askedDocumentTypes.indexOf(documentType.id) > -1;
        })
        .map(function(documentType) {
          documentType.asked = true;
          return documentType;
        })
        .value();
    }

    function concatTypes(accumulator, type) {
      if (_.find(accumulator, {id: type.id})) {
        return accumulator;
      }

      accumulator.push(type);
      return accumulator;
    }

    function computeSelectedDocumentTypes(request, documentTypes) {
      var selectedDocumentTypes = [];

      var mandatoryTypes = getMandatoryTypes(documentTypes);
      var existingTypes = findExistingTypes(request, documentTypes);
      var askedTypes = findAskedTypes(request, documentTypes);

      _.reduce(mandatoryTypes, concatTypes, selectedDocumentTypes);
      _.reduce(existingTypes, concatTypes, selectedDocumentTypes);
      _.reduce(askedTypes, concatTypes, selectedDocumentTypes);

      return selectedDocumentTypes;
    }

    return {
      findRefusedDocuments,
      getAskedDocumentTypes,
      getCompletion,
      computeSelectedDocumentTypes,

      groupByAge(requests) {
        if (typeof requests === 'undefined' || requests.length === 0) {
          return null;
        }

        var currentMoment = moment();
        var groupedByAge = {
          new: [],
          standard: [],
          old: []
        };

        _.reduce(requests, function(result, request) {
          var submissionMoment = moment(request.submittedAt);
          var deltaMonths = currentMoment.diff(submissionMoment, 'months');

          if (deltaMonths <= 1) {
            result.new.push(request);
          } else if (deltaMonths > 1 && deltaMonths < 3) {
            result.standard.push(request);
          } else {
            result.old.push(request);
          }

          return result;
        }, groupedByAge);

        return groupedByAge;
      },

      postAction(request, action) {
        return $http.post(`api/requests/${request.shortId}/action`, action);
      },

      generateReceptionMail(request) {
        return $http.get(`api/requests/${request.shortId}/generate-reception-mail`);
      },

      generateMedicMail(request, emailMedic) {
        return $http.post(`api/requests/${request.shortId}/generate-medic-mail`, {emailMedic});
      }
    };
  });
<commit_msg>Remove weird check if every file is valid.<commit_after>'use strict';

angular.module('impactApp')
  .factory('RequestService', function RequestService($http) {
    function allMandatoryFilesPresent(request) {
      return request.documents && request.documents.obligatoires && Object.keys(request.documents.obligatoires).length === 3;
    }

    function allAskedFilesPresent(request) {
      var allAskedFilesComplete = true;

      _.forEach(request.askedDocumentTypes, function(askedType) {
        let askedDocs = _.get(request.documents, ['complementaires', askedType, 'documentList']);
        if (typeof askedDocs === 'undefined' || askedDocs.length === 0) {
          allAskedFilesComplete = false;
        }
      });

      return allAskedFilesComplete;
    }

    function getCompletion(request) {
      if (!request.documents) {
        return false;
      }

      return allMandatoryFilesPresent(request) && allAskedFilesPresent(request);
    }

    function findInvalid(categories) {
      var invalidDocuments = [];

      _.forEach(categories, function(category) {
        _.forEach(category.documentList, function(document) {
          if (document.isInvalid) {
            invalidDocuments.push(document);
          }
        });
      });

      return invalidDocuments;
    }

    function findRefusedDocuments(request) {
      if (!request.documents) {
        return {
          obligatoires: [],
          complementaires: []
        };
      }

      var obligatoires = findInvalid(request.documents.obligatoires);
      var complementaires = findInvalid(request.documents.complementaires);

      return {
        obligatoires: obligatoires,
        complementaires: complementaires
      };
    }

    function getAskedDocumentTypes(request) {
      if (!request.askedDocumentTypes) {
        return [];
      }

      return request.askedDocumentTypes;
    }

    function getMandatoryTypes(documentTypes) {
      return _.filter(documentTypes, {mandatory: true});
    }

    function findExistingTypes(request) {
      return _.pluck(request.documents.complementaires, 'documentType');
    }

    function findAskedTypes(request, documentTypes) {
      return _(documentTypes)
        .filter(function(documentType) {
          return !documentType.mandatory && request.askedDocumentTypes.indexOf(documentType.id) > -1;
        })
        .map(function(documentType) {
          documentType.asked = true;
          return documentType;
        })
        .value();
    }

    function concatTypes(accumulator, type) {
      if (_.find(accumulator, {id: type.id})) {
        return accumulator;
      }

      accumulator.push(type);
      return accumulator;
    }

    function computeSelectedDocumentTypes(request, documentTypes) {
      var selectedDocumentTypes = [];

      var mandatoryTypes = getMandatoryTypes(documentTypes);
      var existingTypes = findExistingTypes(request, documentTypes);
      var askedTypes = findAskedTypes(request, documentTypes);

      _.reduce(mandatoryTypes, concatTypes, selectedDocumentTypes);
      _.reduce(existingTypes, concatTypes, selectedDocumentTypes);
      _.reduce(askedTypes, concatTypes, selectedDocumentTypes);

      return selectedDocumentTypes;
    }

    return {
      findRefusedDocuments,
      getAskedDocumentTypes,
      getCompletion,
      computeSelectedDocumentTypes,

      groupByAge(requests) {
        if (typeof requests === 'undefined' || requests.length === 0) {
          return null;
        }

        var currentMoment = moment();
        var groupedByAge = {
          new: [],
          standard: [],
          old: []
        };

        _.reduce(requests, function(result, request) {
          var submissionMoment = moment(request.submittedAt);
          var deltaMonths = currentMoment.diff(submissionMoment, 'months');

          if (deltaMonths <= 1) {
            result.new.push(request);
          } else if (deltaMonths > 1 && deltaMonths < 3) {
            result.standard.push(request);
          } else {
            result.old.push(request);
          }

          return result;
        }, groupedByAge);

        return groupedByAge;
      },

      postAction(request, action) {
        return $http.post(`api/requests/${request.shortId}/action`, action);
      },

      generateReceptionMail(request) {
        return $http.get(`api/requests/${request.shortId}/generate-reception-mail`);
      },

      generateMedicMail(request, emailMedic) {
        return $http.post(`api/requests/${request.shortId}/generate-medic-mail`, {emailMedic});
      }
    };
  });
<|endoftext|>


<commit_before>/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import ChatCommandDispatcher from '../dispatcher/ChatCommandDispatcher';
import CommandTypeMod from '../script/model/CommandType';

const CommandType = CommandTypeMod.type;

class MessageActionCreator {
    constructor() {
    }

    /**
     *  @return {ChatCommandDispatcher}
     */
    getDispatcher() {
        return ChatCommandDispatcher;
    }

    /**
     *  @param  {string}  targetId
     *  @param  {string}  command
     *    The command string.
     *  @return {void}
     */
    inputCommand(targetId, command) {
        if ( command.startsWith(CommandType.CLEAR) ) {
            ChatCommandDispatcher.clearMessage.onNext();
            return;
        }

        ChatCommandDispatcher.sendCommand.onNext({
            targetId: targetId,
            text: command,
        });
    }
}

export default new MessageActionCreator();
<commit_msg>Fix path of model/CommandType.<commit_after>/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import ChatCommandDispatcher from '../dispatcher/ChatCommandDispatcher';
import CommandTypeMod from '../model/CommandType';

const CommandType = CommandTypeMod.type;

class MessageActionCreator {
    constructor() {
    }

    /**
     *  @return {ChatCommandDispatcher}
     */
    getDispatcher() {
        return ChatCommandDispatcher;
    }

    /**
     *  @param  {string}  targetId
     *  @param  {string}  command
     *    The command string.
     *  @return {void}
     */
    inputCommand(targetId, command) {
        if ( command.startsWith(CommandType.CLEAR) ) {
            ChatCommandDispatcher.clearMessage.onNext();
            return;
        }

        ChatCommandDispatcher.sendCommand.onNext({
            targetId: targetId,
            text: command,
        });
    }
}

export default new MessageActionCreator();
<|endoftext|>